下面列出了org.apache.commons.lang3.SerializationUtils#clone ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
}
}
@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;
}
@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;
}
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;
}
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);
}
@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());
}
@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>"));
}
@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);
}
@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)));
}
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;
}
@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());
}
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));
}
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());
}
/**
* 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;
}
@Test
public void testSerializability() {
RssTypeConverter converter = new RssTypeConverter();
RssTypeConverter clone = SerializationUtils.clone(converter);
}
@Ignore
@Test
public void testLinkResolverSerializability() {
LinkResolver resolver = new LinkResolver("http://bit.ly/1cX5Rh4");
LinkResolver clone = SerializationUtils.clone(resolver);
}
@Override
public Object clone() throws CloneNotSupportedException {
return SerializationUtils.clone(this);
}
/**
* 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;
}
@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());
}