org.apache.commons.lang3.SerializationUtils#clone ( )源码实例Demo

下面列出了org.apache.commons.lang3.SerializationUtils#clone ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Bats   文件: StramLocalCluster.java
@Override
public ContainerHeartbeatResponse processHeartbeat(ContainerHeartbeat msg) throws IOException
{
  if (injectShutdown.containsKey(msg.getContainerId())) {
    ContainerHeartbeatResponse r = new ContainerHeartbeatResponse();
    r.shutdown = ShutdownType.ABORT;
    return r;
  }
  try {
    ContainerHeartbeatResponse rsp = dnmgr.processHeartbeat(msg);
    if (rsp != null) {
      // clone to not share attributes (stream codec etc.) between threads.
      rsp = SerializationUtils.clone(rsp);
    }
    return rsp;
  } finally {
    LocalStreamingContainer c = childContainers.get(msg.getContainerId());
    synchronized (c.heartbeatCount) {
      c.heartbeatCount.incrementAndGet();
      c.heartbeatCount.notifyAll();
    }
  }
}
 
源代码2 项目: NeurophFramework   文件: CrossValidationBak.java
@Override
public EvaluationResult call() {
    NeuralNetwork neuralNet = SerializationUtils.clone(this.neuralNetwork);

    DataSet trainingSet = new DataSet(dataSet.size() - foldSize);
    DataSet testSet = new DataSet(foldSize);

    int startIndex = foldSize * foldIndex;
    int endIndex = foldSize * (foldIndex + 1);

    for (int i = 0; i < dataSet.size(); i++) {
        if (i >= startIndex && i < endIndex) {
            testSet.add(dataSet.getRowAt(i));
        } else {
            trainingSet.add(dataSet.getRowAt(i));
        }
    }
    neuralNet.learn(trainingSet);
    EvaluationResult evaluationResult = new EvaluationResult();
    evaluationResult.setNeuralNetwork(neuralNet);
    evaluationResult = evaluation.evaluate(neuralNet, testSet);
    return evaluationResult;
}
 
源代码3 项目: singleton   文件: PseudoMessagesUtils.java
@SuppressWarnings({ "unchecked", "rawtypes" })
public static TranslationDTO getPseudoMessages2(
        TranslationDTO translationDTO, PseudoConfig pseudoConfig) {
    TranslationDTO t = SerializationUtils.clone(translationDTO);
    JSONArray pseudoList = new JSONArray();
    JSONArray ja = t.getBundles();
    for (Object ob : ja) {
        if (pseudoConfig.isEnabled()) {
            JSONObject jo = (JSONObject) ob;
            Map messages = (Map) jo.get(ConstantsKeys.MESSAGES);
            jo.put(ConstantsKeys.MESSAGES,
                    JSONUtils.getOrderedMapForPseudo(messages,
                            pseudoConfig.getExistSourceTag()));
            pseudoList.add(jo);
        }
    }
    t.setBundles(pseudoList);
    return t;
}
 
private Table cloneTable(MetadataFactory factory, Table table) throws Exception {
    Table matTable = SerializationUtils.clone(table);
    matTable.setVirtual(false);
    matTable.setMaterialized(false);
    matTable.setSupportsUpdate(true);
    matTable.setName(sanitize(factory.getVdbName() + "_" + table.getFullName()));
    factory.addColumn("LoadNumber", "long", matTable);
    //matTable.setUUID(UUID.randomUUID().toString());

    for (Column c : matTable.getColumns()) {
        c.setUpdatable(true);
    }

    // remove any matview specific properties that carried over from the original table
    for (String key : matTable.getProperties().keySet()) {
        if (key.startsWith("teiid_rel:MATVIEW")) {
            matTable.setProperty(key, null);
        }
    }
    // if this is going to Infinispan assign the cache name
    if (this.type.equalsIgnoreCase(VdbCodeGeneratorMojo.ISPN)) {
        matTable.setProperty("teiid_ispn:cache", matTable.getName());
    }
    return matTable;
}
 
源代码5 项目: batfish   文件: PaloAltoSecurityRuleTest.java
private PaloAltoConfiguration parsePaloAltoConfig(String hostname) {
  String src = readResource(TESTCONFIGS_PREFIX + hostname, UTF_8);
  Settings settings = new Settings();
  configureBatfishTestSettings(settings);
  PaloAltoCombinedParser parser = new PaloAltoCombinedParser(src, settings, null);
  ParserRuleContext tree =
      Batfish.parse(parser, new BatfishLogger(BatfishLogger.LEVELSTR_FATAL, false), settings);
  PaloAltoControlPlaneExtractor extractor =
      new PaloAltoControlPlaneExtractor(src, parser, new Warnings());
  extractor.processParseTree(TEST_SNAPSHOT, tree);
  PaloAltoConfiguration pac = (PaloAltoConfiguration) extractor.getVendorConfiguration();
  pac.setVendor(ConfigurationFormat.PALO_ALTO);
  ConvertConfigurationAnswerElement answerElement = new ConvertConfigurationAnswerElement();
  pac.setFilename(TESTCONFIGS_PREFIX + hostname);
  // crash if not serializable
  pac = SerializationUtils.clone(pac);
  pac.setAnswerElement(answerElement);
  return pac;
}
 
源代码6 项目: batfish   文件: AristaGrammarTest.java
private static @Nonnull AristaConfiguration parseVendorConfig(String hostname) {
  String src = readResource(TESTCONFIGS_PREFIX + hostname, UTF_8);
  Settings settings = new Settings();
  configureBatfishTestSettings(settings);
  AristaCombinedParser ciscoParser = new AristaCombinedParser(src, settings);
  AristaControlPlaneExtractor extractor =
      new AristaControlPlaneExtractor(
          src, ciscoParser, ConfigurationFormat.ARISTA, new Warnings());
  ParserRuleContext tree =
      Batfish.parse(
          ciscoParser, new BatfishLogger(BatfishLogger.LEVELSTR_FATAL, false), settings);
  extractor.processParseTree(TEST_SNAPSHOT, tree);
  AristaConfiguration vendorConfiguration =
      (AristaConfiguration) extractor.getVendorConfiguration();
  vendorConfiguration.setFilename(TESTCONFIGS_PREFIX + hostname);
  // crash if not serializable
  return SerializationUtils.clone(vendorConfiguration);
}
 
源代码7 项目: OpenID-Attacker   文件: DiscoverySpoofingAttack.java
@Override
protected void beforeAttack() {
    super.beforeAttack();
        
    // copy of HTML and XRDS Discovery information by serialization
    htmlConfigCopy = SerializationUtils.clone(serverController.getConfig().getHtmlConfiguration());
    xrdsConfigCopy = SerializationUtils.clone(serverController.getConfig().getXrdsConfiguration());    
}
 
源代码8 项目: syncope   文件: MailTemplateTest.java
@Test
public void optin() throws IOException {
    Map<String, Object> ctx = new HashMap<>();

    String username = "test" + UUID.randomUUID().toString();
    UserTO user = new UserTO();
    user.setUsername(username);
    user.getPlainAttrs().add(new Attr.Builder("firstname").value("John").build());
    user.getPlainAttrs().add(new Attr.Builder("surname").value("Doe").build());
    user.getPlainAttrs().add(new Attr.Builder("email").value("[email protected]").build());
    user.getMemberships().add(new MembershipTO.Builder(UUID.randomUUID().toString()).groupName("a group").build());
    ctx.put("user", user);

    String token = "token " + UUID.randomUUID().toString();
    List<String> input = new ArrayList<>();
    input.add(token);
    ctx.put("input", input);

    UserTO recipient = SerializationUtils.clone(user);
    recipient.getPlainAttr("email").get().getValues().set(0, "[email protected]");
    ctx.put("recipients", List.of(recipient));

    ctx.put("events", List.of("event1"));

    String htmlBody = evaluate(OPTIN_TEMPLATE, ctx);

    assertNotNull(htmlBody);

    assertTrue(htmlBody.contains("Hi John Doe,"));
    assertTrue(htmlBody.contains("Your email address is [email protected]"));
    assertTrue(htmlBody.contains("<li>[email protected]</li>"));
    assertTrue(htmlBody.contains("<li>a group</li>"));
    assertTrue(htmlBody.contains("<li>event1</li>"));
}
 
源代码9 项目: x-pipe   文件: ReplicationStoreMetaTest.java
@Test
public void testEquals(){
	
	ReplicationStoreMeta meta = createRandomMeta();

	ReplicationStoreMeta meta2 = SerializationUtils.clone(meta);
	Assert.assertEquals(meta, meta2);

	ReplicationStoreMeta meta3 = new ReplicationStoreMeta(meta);
	Assert.assertEquals(meta, meta3);
	
	meta3.setBeginOffset(meta3.getBeginOffset()+1);
	Assert.assertNotEquals(meta, meta3);
}
 
源代码10 项目: batfish   文件: CumulusConversionsTest.java
@Test
public void testToAsPathAccessList() {
  long permitted = 11111;
  long denied = 22222;
  IpAsPathAccessList asPathAccessList = new IpAsPathAccessList("name");
  asPathAccessList.addLine(new IpAsPathAccessListLine(LineAction.DENY, denied));
  asPathAccessList.addLine(new IpAsPathAccessListLine(LineAction.PERMIT, permitted));
  AsPathAccessList viList = toAsPathAccessList(asPathAccessList);

  // Cache initialization only happens in AsPathAccessList on deserialization o.O
  viList = SerializationUtils.clone(viList);

  List<AsPathAccessListLine> expectedViLines =
      ImmutableList.of(
          new AsPathAccessListLine(LineAction.DENY, String.format("(^| )%s($| )", denied)),
          new AsPathAccessListLine(LineAction.PERMIT, String.format("(^| )%s($| )", permitted)));
  assertThat(viList, equalTo(new AsPathAccessList("name", expectedViLines)));

  // Matches paths containing permitted ASN
  long other = 33333;
  assertTrue(viList.permits(AsPath.ofSingletonAsSets(permitted)));
  assertTrue(viList.permits(AsPath.ofSingletonAsSets(permitted, other)));
  assertTrue(viList.permits(AsPath.ofSingletonAsSets(other, permitted)));
  assertTrue(viList.permits(AsPath.ofSingletonAsSets(other, permitted, other)));

  // Does not match if denied ASN is in path, even if permitted is also there
  assertFalse(viList.permits(AsPath.ofSingletonAsSets(denied)));
  assertFalse(viList.permits(AsPath.ofSingletonAsSets(denied, permitted)));
  assertFalse(viList.permits(AsPath.ofSingletonAsSets(permitted, denied)));
  assertFalse(viList.permits(AsPath.ofSingletonAsSets(permitted, denied, permitted)));

  // Does not match by default
  assertFalse(viList.permits(AsPath.ofSingletonAsSets(other)));
}
 
源代码11 项目: SmartApplianceEnabler   文件: AbstractTimeframe.java
protected TimeframeInterval createTimeframeInterval(Interval interval, Schedule schedule) {
    Request clonedRequest = SerializationUtils.clone(schedule.getRequest());
    // "enabled" has to be transient since it is not contained in XML; therefore it has to be set after cloning
    clonedRequest.setEnabled(true);

    TimeframeInterval timeframeInterval = new TimeframeInterval(interval, clonedRequest);
    return timeframeInterval;
}
 
源代码12 项目: x-pipe   文件: RedisKeeperServerStateUnknownTest.java
@Test
public void testBackup() throws IOException{
			
	//active
	KeeperMeta keeperMeta = SerializationUtils.clone(redisKeeperServer.getCurrentKeeperMeta());
	keeperMeta.setPort(keeperMeta.getPort() + 1);
	ShardStatus shardStatus = createShardStatus(keeperMeta, null, redisMasterMeta);
	unknown.setShardStatus(shardStatus);
	
	RedisKeeperServerState newState = redisKeeperServer.getRedisKeeperServerState();
	Assert.assertTrue(newState instanceof RedisKeeperServerStateBackup);
	Assert.assertEquals(new InetSocketAddress(keeperMeta.getIp(), keeperMeta.getPort()),
			newState.getMaster().getSocketAddress());
	
}
 
源代码13 项目: hesperides   文件: PlatformHistory.java
public void addPlatformBuilder(PlatformBuilder platformBuilder) {
    if (platforms.stream().anyMatch(platform -> !platform.isDeleted && platform.getPlatformKey().equals(platformBuilder.buildPlatformKey()))) {
        throw new RuntimeException("Platform " + platformBuilder.getApplicationName() + "-" + platformBuilder.getPlatformName() + " already exists in platform history");
    }
    PlatformBuilder newPlatformBuilder = SerializationUtils.clone(platformBuilder);
    platforms.add(new PlatformTimestampedBuilders(newPlatformBuilder));
}
 
源代码14 项目: hesperides   文件: PlatformBuilder.java
public void updateDeployedModuleBuilder(DeployedModuleBuilder deployedModuleBuilder) {
    deployedModuleBuilder.incrementPropertiesVersionId();
    DeployedModuleBuilder updatedDeployedModuleBuilder = SerializationUtils.clone(deployedModuleBuilder);
    deployedModuleBuilders = deployedModuleBuilders.stream()
            .map(existingDeployedModuleBuilder -> existingDeployedModuleBuilder.equalsByKey(updatedDeployedModuleBuilder)
                    ? updatedDeployedModuleBuilder : existingDeployedModuleBuilder)
            .collect(Collectors.toList());
}
 
源代码15 项目: onedev   文件: EntityCriteria.java
/**
 * Get an executable instance of <literal>Criteria</literal>,
 * to actually run the query.
 */
public Criteria getExecutableCriteria(Session session) {
	CriteriaImpl clone = (CriteriaImpl) SerializationUtils.clone(impl);
	clone.setSession( ( SessionImplementor ) session );
	return clone;
}
 
源代码16 项目: streams   文件: RssTypeConverterTest.java
@Test
public void testSerializability() {
  RssTypeConverter converter = new RssTypeConverter();
  RssTypeConverter clone = SerializationUtils.clone(converter);
}
 
源代码17 项目: streams   文件: TestLinkUnwinderProcessor.java
@Ignore
@Test
public void testLinkResolverSerializability() {
    LinkResolver resolver = new LinkResolver("http://bit.ly/1cX5Rh4");
    LinkResolver clone = SerializationUtils.clone(resolver);
}
 
源代码18 项目: beakerx   文件: Text.java
@Override
public Object clone() throws CloneNotSupportedException {
  return SerializationUtils.clone(this);
}
 
源代码19 项目: Saiy-PS   文件: EndsWithHelper.java
/**
 * Method to iterate through the voice data and attempt to match the user's custom commands
 * using that are marked as {@link Algorithm#REGEX}
 * specifically {@link ai.saiy.android.api.request.Regex#ENDS_WITH}
 *
 * @return a {@link CustomCommand} should the regular express be successful, otherwise null
 */
public CustomCommand executeCustomCommand() {

    long then = System.nanoTime();

    CustomCommand customCommand = null;

    String phrase;
    CustomCommandContainer container;
    int size = genericData.size();

    outer:
    for (int i = 0; i < size; i++) {
        container = (CustomCommandContainer) genericData.get(i);
        phrase = container.getKeyphrase().toLowerCase(loc).trim();

        for (String vd : inputData) {
            vd = vd.toLowerCase(loc).trim();

            if (DEBUG) {
                MyLog.i(CLS_NAME, "ends with: " + vd + " ~ " + phrase);
            }

            if (vd.endsWith(phrase)) {

                final CustomCommandContainer ccc = SerializationUtils.clone(container);
                final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
                customCommand = gson.fromJson(ccc.getSerialised(), CustomCommand.class);
                customCommand.setExactMatch(true);
                customCommand.setUtterance(vd);
                customCommand.setScore(1.0);
                customCommand.setAlgorithm(Algorithm.REGEX);

                break outer;
            }
        }
    }

    if (DEBUG) {
        MyLog.getElapsed(EndsWithHelper.class.getSimpleName(), then);
    }

    return customCommand;
}
 
源代码20 项目: syncope   文件: AuditITCase.java
@Test
public void findByConnector() throws JsonProcessingException {
    String connectorKey = "74141a3b-0762-4720-a4aa-fc3e374ef3ef";

    AuditQuery query = new AuditQuery.Builder().
            entityKey(connectorKey).
            orderBy("event_date desc").
            type(AuditElements.EventCategoryType.LOGIC).
            category("ConnectorLogic").
            event("update").
            result(AuditElements.Result.SUCCESS).
            build();
    List<AuditEntry> entries = query(query, 0);
    int pre = entries.size();

    ConnInstanceTO ldapConn = connectorService.read(connectorKey, null);
    String originalDisplayName = ldapConn.getDisplayName();
    Set<ConnectorCapability> originalCapabilities = new HashSet<>(ldapConn.getCapabilities());
    ConnConfProperty originalConfProp = SerializationUtils.clone(
            ldapConn.getConf("maintainPosixGroupMembership").get());
    assertEquals(1, originalConfProp.getValues().size());
    assertEquals("false", originalConfProp.getValues().get(0));

    ldapConn.setDisplayName(originalDisplayName + " modified");
    ldapConn.getCapabilities().clear();
    ldapConn.getConf("maintainPosixGroupMembership").get().getValues().set(0, "true");
    connectorService.update(ldapConn);

    ldapConn = connectorService.read(connectorKey, null);
    assertNotEquals(originalDisplayName, ldapConn.getDisplayName());
    assertNotEquals(originalCapabilities, ldapConn.getCapabilities());
    assertNotEquals(originalConfProp, ldapConn.getConf("maintainPosixGroupMembership"));

    entries = query(query, MAX_WAIT_SECONDS);
    assertEquals(pre + 1, entries.size());

    ConnInstanceTO restore = OBJECT_MAPPER.readValue(entries.get(0).getBefore(), ConnInstanceTO.class);
    connectorService.update(restore);

    ldapConn = connectorService.read(connectorKey, null);
    assertEquals(originalDisplayName, ldapConn.getDisplayName());
    assertEquals(originalCapabilities, ldapConn.getCapabilities());
    assertEquals(originalConfProp, ldapConn.getConf("maintainPosixGroupMembership").get());
}