/** * method to save a suggestion in the DB * @param data * @return * @throws JsonProcessingException */ @RabbitListener(queues = "#{saveSuggestionQueue.name}") public String saveEvent(byte[] data){ String res = ""; Suggestion s = (Suggestion)SerializationUtils.deserialize(data); s = repository.save(s); ObjectMapper mapper = new ObjectMapper(); Log .forContext("MemberName", "saveSuggestion") .forContext("Service", appName) .information("RabbitMQ : saveSuggestion"); try { res = mapper.writeValueAsString(s); } catch (JsonProcessingException e1) { Log .forContext("MemberName", "saveSuggestion") .forContext("Service", appName) .error(e1,"JsonProcessingException"); } return res; }
public void init(int mode, byte[] key, byte[] iv, AlgorithmParameterSpec params) { Preconditions.checkNotNull(key); this.mode = mode; try { if (mode == TRANSFORM_MODE) { reKey = new BBS98ReEncryptionKeySpec(key); this.params = params; } else { Preconditions.checkNotNull(iv); BBS98KeySpec keySpec = new BBS98KeySpec(key, "BBS98"); this.blockSize = 30; this.key = (ECKey) SerializationUtils.deserialize(keySpec.getKeyMaterial()); this.params = this.key.getParameters(); } engine = new WrapperBBS98(this.params, random); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } this.iv = iv; }
/** * Method to save an event with RabbitMq * @param id * @return * @throws ParseException */ @RequestMapping(value = "/saveSuggestion", method = RequestMethod.POST) public String saveSuggestion(@RequestParam Map<String, String> body){ ObjectMapper mapper = new ObjectMapper(); Suggestion suggestion = null; try { suggestion = mapper.readValue((String) body.get("suggestion"),Suggestion.class); } catch (IOException e1) { Log .forContext("MemberName", "saveSuggestion") .forContext("Service", appName) .error(e1," IOException"); } Log .forContext("MemberName", "saveSuggestion") .forContext("Service", appName) .forContext("suggestion", body.get("suggestion")) .information("Request : saveSuggestion"); return new RabbitClient(EXCHANGE).rabbitRPCRoutingKeyExchange(SerializationUtils.serialize(suggestion),"saveSuggestion"); }
/** * Method to save an event with RabbitMq * @return */ @RequestMapping(value = "/saveEvent", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public String updateEvent(@RequestParam Map<String, String> body) { ObjectMapper mapper = new ObjectMapper(); Event event = null; try { event = mapper.readValue(body.get("event"),Event.class); } catch (IOException e1) { Log .forContext("MemberName", "saveEvent") .forContext("Service", appName) .error(e1," IOException"); } Log .forContext("MemberName", "saveEvent") .forContext("Service", appName) .forContext("event", body.get("event")) .information("Request : saveEvent"); new RabbitClient(EXCHANGE).rabbitRPCRoutingKeyExchange(SerializationUtils.serialize(event),"saveEvent"); return "{\"response\":\"success\"}"; }
/** * method to save an event in the DB * @param data * @return * @throws JsonProcessingException */ @RabbitListener(queues = "#{saveEventQueue.name}") public String saveEvent(byte[] data){ String res = null; Event e = (Event)SerializationUtils.deserialize(data); Event event = null; if (e.checkEvent()){ event = repository.save(e); } else{ Log .forContext("MemberName", "saveEvent") .forContext("Service", appName) .error(new IllegalArgumentException(),"IllegalArgumentException"); } ObjectMapper mapper = new ObjectMapper(); Log .forContext("MemberName", "saveEvent") .forContext("Service", appName) .information("RabbitMQ : saveEvent"); try { res = mapper.writeValueAsString(event); } catch (JsonProcessingException e1) { Log .forContext("MemberName", "saveEvent") .forContext("Service", appName) .error(e1,"JsonProcessingException"); } return res; }
/** * method to find all events by owner * @param owner * @return * @throws UnsupportedEncodingException */ @RabbitListener(queues = "#{findByOwnerQueue.name}") public String findByOwner(byte[] owner){ Log .forContext("MemberName", "findByOwner") .forContext("Service", appName) .information("RabbitMQ : findByOwner"); return repository.findByOwner((Person)SerializationUtils.deserialize(owner)).toString(); }
/** * method to find all event of a person * @param owner * @return * @throws JsonProcessingException * @throws UnsupportedEncodingException */ @RabbitListener(queues = "#{getEventsByPersonQueue.name}") public String getEventsByPerson(byte[] person) throws JsonProcessingException{ List<Event> res; Log .forContext("MemberName", "getEventsByPerson") .forContext("Service", appName) .information("RabbitMQ : getEventsByPerson"); res = repository.getEventsByPerson((Person)SerializationUtils.deserialize(person)); ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(res); }
/** * Method to add a Person in DataBase, works with RabbitMq * @param data * @return * @throws JsonProcessingException */ @RabbitListener(queues = "#{addPersonQueue.name}") public String addPerson(byte[] data) throws JsonProcessingException{ Person p = (Person) SerializationUtils.deserialize(data); if (p.checkPerson()){ p = repository.save(p); } else{ Log .forContext("MemberName", "addPerson") .forContext("Service", appName) .error(new IllegalArgumentException(),"IllegalArgumentException"); } String res = ""; ObjectMapper mapper = new ObjectMapper(); Log .forContext("MemberName", "addPerson") .forContext("Service", appName) .information("Request : addPerson"); try { res = mapper.writeValueAsString(p); } catch (JsonProcessingException e) { Log .forContext("MemberName", "addPerson") .forContext("Service", appName) .error(e,"JsonProcessingException"); } return res; }
@Override public Map<String, Verification> getVerifications(Project project, String commit) { Environment env = getEnv(project.getId().toString()); Store store = getStore(env, VERIFICATIONS_STORE); return env.computeInTransaction(new TransactionalComputable<Map<String, Verification>>() { @SuppressWarnings("unchecked") @Override public Map<String, Verification> compute(Transaction txn) { byte[] bytes = getBytes(store.get(txn, new StringByteIterable(commit))); if (bytes != null) return (Map<String, Verification>) SerializationUtils.deserialize(bytes); else return new HashMap<>(); } }); }
@Override public Collection<String> getVerificationNames(Project project) { Environment env = getEnv(project.getId().toString()); Store store = getStore(env, DEFAULT_STORE); return env.computeInTransaction(new TransactionalComputable<Collection<String>>() { @SuppressWarnings("unchecked") @Override public Collection<String> compute(Transaction txn) { byte[] bytes = getBytes(store.get(txn, new StringByteIterable(VERIFICATION_NAMES_KEY))); if (bytes != null) return ((Map<String, Date>) SerializationUtils.deserialize(bytes)).keySet(); else return null; } }); }
@Test public void canBeSerialized() throws Exception { long timeout = 2; TimeUnit timeUnit = TimeUnit.SECONDS; boolean lookingForStuckThread = true; SerializableTimeout instance = SerializableTimeout.builder().withTimeout(timeout, timeUnit) .withLookingForStuckThread(lookingForStuckThread).build(); assertThat(readField(Timeout.class, instance, FIELD_TIMEOUT)).isEqualTo(timeout); assertThat(readField(Timeout.class, instance, FIELD_TIME_UNIT)).isEqualTo(timeUnit); assertThat(readField(Timeout.class, instance, FIELD_LOOK_FOR_STUCK_THREAD)) .isEqualTo(lookingForStuckThread); SerializableTimeout cloned = (SerializableTimeout) SerializationUtils.clone(instance); assertThat(readField(Timeout.class, cloned, FIELD_TIMEOUT)).isEqualTo(timeout); assertThat(readField(Timeout.class, cloned, FIELD_TIME_UNIT)).isEqualTo(timeUnit); assertThat(readField(Timeout.class, cloned, FIELD_LOOK_FOR_STUCK_THREAD)) .isEqualTo(lookingForStuckThread); }
@Override public RowDataPacket nextRow() { RowDataPacket rp = super.nextRow(); if (rp == null) return null; else { DGRowPacket newRow = new DGRowPacket(orgFieldCount, sumSize); for (int index = 0; index < sumSize; index++) { byte[] b = rp.getValue(index); if (b != null) { Object obj = SerializationUtils.deserialize(b); newRow.setSumTran(index, obj, b.length); } } for (int index = sumSize; index < this.fieldCount; index++) { newRow.add(rp.getValue(index)); } return newRow; } }
private static void testSerialization(final byte[] state, final List<ReplicatedLogEntry> unapplied) { long lastIndex = 6; long lastTerm = 2; long lastAppliedIndex = 5; long lastAppliedTerm = 1; long electionTerm = 3; String electionVotedFor = "member-1"; ServerConfigurationPayload serverConfig = new ServerConfigurationPayload(Arrays.asList( new ServerInfo("1", true), new ServerInfo("2", false))); Snapshot expected = Snapshot.create(ByteState.of(state), unapplied, lastIndex, lastTerm, lastAppliedIndex, lastAppliedTerm, electionTerm, electionVotedFor, serverConfig); Snapshot cloned = (Snapshot) SerializationUtils.clone(expected); assertEquals("lastIndex", expected.getLastIndex(), cloned.getLastIndex()); assertEquals("lastTerm", expected.getLastTerm(), cloned.getLastTerm()); assertEquals("lastAppliedIndex", expected.getLastAppliedIndex(), cloned.getLastAppliedIndex()); assertEquals("lastAppliedTerm", expected.getLastAppliedTerm(), cloned.getLastAppliedTerm()); assertEquals("unAppliedEntries", expected.getUnAppliedEntries(), cloned.getUnAppliedEntries()); assertEquals("electionTerm", expected.getElectionTerm(), cloned.getElectionTerm()); assertEquals("electionVotedFor", expected.getElectionVotedFor(), cloned.getElectionVotedFor()); assertEquals("state", expected.getState(), cloned.getState()); assertEquals("serverConfig", expected.getServerConfiguration().getServerConfig(), cloned.getServerConfiguration().getServerConfig()); }
@Test public void testSerialization() { byte[] data = new byte[1000]; for (int i = 0, j = 0; i < data.length; i++) { data[i] = (byte)j; if (++j >= 255) { j = 0; } } ServerConfigurationPayload serverConfig = new ServerConfigurationPayload(Arrays.asList( new ServerInfo("leader", true), new ServerInfo("follower", false))); InstallSnapshot expected = new InstallSnapshot(3L, "leaderId", 11L, 2L, data, 5, 6, Optional.<Integer>of(54321), Optional.of(serverConfig)); Object serialized = expected.toSerializable(RaftVersions.CURRENT_VERSION); assertEquals("Serialized type", InstallSnapshot.class, serialized.getClass()); InstallSnapshot actual = (InstallSnapshot) SerializationUtils.clone((Serializable) serialized); verifyInstallSnapshot(expected, actual); expected = new InstallSnapshot(3L, "leaderId", 11L, 2L, data, 5, 6); actual = (InstallSnapshot) SerializationUtils.clone((Serializable) expected.toSerializable( RaftVersions.CURRENT_VERSION)); verifyInstallSnapshot(expected, actual); }
@Test public void testSerialization() { NormalizedNode<?, ?> data = ImmutableContainerNodeBuilder.create() .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)) .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build(); ReadDataReply expected = new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION); Object serialized = expected.toSerializable(); assertEquals("Serialized type", ReadDataReply.class, serialized.getClass()); ReadDataReply actual = ReadDataReply.fromSerializable(SerializationUtils.clone( (Serializable) serialized)); assertEquals("getVersion", DataStoreVersions.CURRENT_VERSION, actual.getVersion()); assertEquals("getNormalizedNode", expected.getNormalizedNode(), actual.getNormalizedNode()); }
@Test public void testSerialization() { CommitTransactionReply expected = CommitTransactionReply.instance(DataStoreVersions.CURRENT_VERSION); Object serialized = expected.toSerializable(); assertEquals("Serialized type", CommitTransactionReply.class, serialized.getClass()); CommitTransactionReply actual = (CommitTransactionReply)SerializationUtils.clone((Serializable) serialized); assertEquals("getVersion", DataStoreVersions.CURRENT_VERSION, actual.getVersion()); }
@Test public void testSerialization() { byte[] data = new byte[1000]; for (int i = 0, j = 0; i < data.length; i++) { data[i] = (byte)j; if (++j >= 255) { j = 0; } } MessageSlice expected = new MessageSlice(new StringIdentifier("test"), data, 2, 3, 54321, TestProbe.apply(actorSystem).ref()); MessageSlice cloned = (MessageSlice) SerializationUtils.clone(expected); assertEquals("getIdentifier", expected.getIdentifier(), cloned.getIdentifier()); assertEquals("getSliceIndex", expected.getSliceIndex(), cloned.getSliceIndex()); assertEquals("getTotalSlices", expected.getTotalSlices(), cloned.getTotalSlices()); assertEquals("getLastSliceHashCode", expected.getLastSliceHashCode(), cloned.getLastSliceHashCode()); assertArrayEquals("getData", expected.getData(), cloned.getData()); assertEquals("getReplyTo", expected.getReplyTo(), cloned.getReplyTo()); }
private Set<Integer> getDesiredContainerList() { log.debug("Fetching the latest container assignment from ZooKeeper."); if (hostContainerMapNode.getCurrentData() != null) { //Check if path exists. //read data from zk. byte[] containerToHostMapSer = hostContainerMapNode.getCurrentData().getData(); if (containerToHostMapSer != null) { @SuppressWarnings("unchecked") val controlMapping = (Map<Host, Set<Integer>>) SerializationUtils.deserialize(containerToHostMapSer); return controlMapping.entrySet().stream() .filter(ep -> ep.getKey().equals(this.host)) .map(Map.Entry::getValue) .findFirst().orElse(Collections.emptySet()); } } return null; }
private static void createPatchForDependencies() { List<Plugin> pluginsList = pluginService.getAllPlugins(); for (Plugin plugin : pluginsList) { ArrayList<Dependency> pluginDependencies = new ArrayList<Dependency>(plugin.getDependencies()); changePluginIdToName(pluginDependencies); pluginNameVsDependencyMap.put(plugin.getPluginName(), pluginDependencies); } try { File serializedExportFile = new File(upgradePatchFolderPath + File.separator + DataAccessConstant.DEPENDENCY_UPDATE + SERIALIZATION_EXT); SerializationUtils.serialize(pluginNameVsDependencyMap, new FileOutputStream(serializedExportFile)); } catch (FileNotFoundException e) { LOG.error(ERROR_OCCURRED_WHILE_CREATING_THE_SERIALIZABLE_FILE + e.getMessage(), e); } }
public void reduce(Text keyname, Iterable<Text> str, Context context) throws IOException, InterruptedException { if(analysis == null) analysis = new ResearcherMapReduceAnalysis(context.getConfiguration()); for(Text val : str) { if(!(analysis.reduce(val.toString()) == true)) continue; passNum++; if(passNum % 10 == 0) System.gc(); } // System.out.println("Final array: " + Arrays.toString((double[])analysis.serializer.serializeMe)); byte[] databyte = SerializationUtils.serialize(analysis.serializer); String byte_to_string = Base64.encodeBase64String(databyte); context.write(new Text("Run#" + passNum.toString()), new Text(byte_to_string)); }
@Override public synchronized void put(T... datas) throws InterruptedException, ThorStoreException { if (ArrayUtils.isEmpty(datas)) { return; } FireQueue queue = getQueue(); if (queue == null) { throw new ThorStoreException("FireQueue is null!"); } for (T obj : datas) { if (obj == null) { continue; } byte[] byteDta = SerializationUtils.serialize(obj); if (ArrayUtils.isEmpty(byteDta)) { continue; } queue.push(byteDta); this.notifyAll(); } }
public void updateBindings() throws ConnectionException { // Check if there is a difference if (getAddress().equals(currentBinding)) { return; } // Remove old binding try { if(currentBinding != null) { ownRegistry.getRegistry().unbind(currentBinding.getName()); } } catch (RemoteException | NotBoundException e) { safeLogMessage("Trying to unbind a non-existent binding: " + currentBinding + " from " + ownRegistry, LogType.WARN); } // Add new binding socket = LocalSocket.connectTo(getAddress()); socket.register(getAddress()); socket.addMessageReceivedHandler(this); safeLogMessage("Successfully rebounded the binding " + currentBinding + " to " + getAddress(), LogType.DEBUG); currentBinding = (NodeAddress) SerializationUtils.clone(getAddress()); }
public static void configureHeaders(Configuration conf, Path[] vcfs, String sampleGroup) throws IOException { List<VCFHeader> headers = new ArrayList<>(); for (Path vcf : vcfs) { InputStream inputStream = vcf.getFileSystem(conf).open(vcf); VcfBlockIterator iterator = new VcfBlockIterator(inputStream, new FullVcfCodec()); VCFHeader header = iterator.getHeader(); header.addMetaDataLine(new VCFHeaderLine(VARIANT_SET_ID, vcf.getName())); headers.add(header); } VCFHeader[] headersArray = headers.toArray(new VCFHeader[headers.size()]); conf.set(VARIANT_HEADERS, Base64.encodeBase64String(SerializationUtils.serialize(headersArray))); if (sampleGroup != null) { conf.set(SAMPLE_GROUP, sampleGroup); } }
@Override public void write(DataOutput output) throws IOException { // write model type WritableUtils.writeString(output, modelType); // write learning rate output.writeFloat(learningRate); // write model path if (this.modelPath != null) { WritableUtils.writeString(output, modelPath); } else { WritableUtils.writeString(output, "null"); } // serialize the class Class<? extends FloatFeatureTransformer> featureTransformerCls = this.featureTransformer .getClass(); byte[] featureTransformerBytes = SerializationUtils .serialize(featureTransformerCls); output.writeInt(featureTransformerBytes.length); output.write(featureTransformerBytes); }
public void testSerializationAndDeserialization() throws Exception { final NumberResult result1 = new NumberResult(42); final AnalyzerResultFuture<NumberResult> future = new AnalyzerResultFutureImpl<>("foo", new ImmutableRef<>(result1)); future.addListener(new Listener<NumberResult>() { @Override public void onSuccess(final NumberResult result) { // do nothing - this is just a non-serializable listener } @Override public void onError(final RuntimeException error) { // do nothing - this is just a non-serializable listener } }); final byte[] bytes = SerializationUtils.serialize(future); final AnalyzerResultFuture<?> copy = (AnalyzerResultFuture<?>) SerializationUtils.deserialize(bytes); assertEquals("foo", copy.getName()); assertEquals("42", copy.get().toString()); }
private static void saveOrThrow(final AnalysisResult analysisResult, final Resource resource) { final SimpleAnalysisResult simpleAnalysisResult; if (analysisResult instanceof SimpleAnalysisResult) { simpleAnalysisResult = (SimpleAnalysisResult) analysisResult; } else { simpleAnalysisResult = new SimpleAnalysisResult(analysisResult.getResultMap(), analysisResult.getCreationDate()); } final OutputStream out = resource.write(); try { SerializationUtils.serialize(simpleAnalysisResult, out); } catch (final SerializationException e) { logger.error("Error serializing analysis result: " + analysisResult, e); throw e; } finally { FileHelper.safeClose(out); } }
/** * Gets a map of unsafe result elements, ie. elements that cannot be saved * because serialization fails. * * @return */ public Map<ComponentJob, AnalyzerResult> getUnsafeResultElements() { if (_unsafeResultElements == null) { _unsafeResultElements = new LinkedHashMap<>(); final Map<ComponentJob, AnalyzerResult> resultMap = _analysisResult.getResultMap(); for (final Entry<ComponentJob, AnalyzerResult> entry : resultMap.entrySet()) { final AnalyzerResult analyzerResult = entry.getValue(); try { SerializationUtils.serialize(analyzerResult, new NullOutputStream()); } catch (final SerializationException e) { _unsafeResultElements.put(entry.getKey(), analyzerResult); } } } return _unsafeResultElements; }
public void testSerializationAndDeserializationOfAllDatastoreTypes() throws Exception { final List<UsageAwareDatastore<?>> datastores = new ArrayList<>(); datastores.add(new AccessDatastore("access", "bar.mdb")); datastores.add(new CsvDatastore("csv", "bar.csv")); datastores.add(new DbaseDatastore("dbase", "bar.dbf")); datastores.add(new ExcelDatastore("excel", null, "bar.xls")); datastores.add(new JdbcDatastore("jdbc", "url")); datastores.add(new FixedWidthDatastore("fixedwidth", "foo.txt", "UTF8", new int[] { 1, 2, 3 })); datastores.add(new CompositeDatastore("foo", Arrays.asList(datastores.get(0), datastores.get(1), datastores.get(3)))); for (final UsageAwareDatastore<?> ds : datastores) { System.out.println("Cloning datastore: " + ds); final Object clone = SerializationUtils.clone(ds); assertEquals(ds, clone); } }
public void testSerializeAndDeserialize() throws Exception { final RowAnnotationFactory annotationFactory = RowAnnotations.getDefaultFactory(); final RowAnnotation annotation = annotationFactory.createAnnotation(); final InputColumn<String> col1 = new MockInputColumn<>("foo", String.class); final InputColumn<String> col2 = new MockInputColumn<>("bar", String.class); annotationFactory.annotate(new MockInputRow().put(col1, "1").put(col2, "2"), 1, annotation); annotationFactory.annotate(new MockInputRow().put(col1, "3").put(col2, "4"), 1, annotation); final AnnotatedRowsResult result1 = new AnnotatedRowsResult(annotation, annotationFactory, col1); performAssertions(result1); final AnnotatedRowsResult result2 = (AnnotatedRowsResult) SerializationUtils.deserialize(SerializationUtils.serialize(result1)); performAssertions(result2); }
public void testSerializationAndDeserializationOfDictionaries() throws Exception { final String[] dictionaryNames = referenceDataCatalog.getDictionaryNames(); for (final String name : dictionaryNames) { final Dictionary dict = referenceDataCatalog.getDictionary(name); if (dict instanceof AbstractReferenceData) { System.out.println("Cloning dictionary: " + dict); final Object clone = SerializationUtils.clone(dict); if (!dict.equals(clone)) { dict.equals(clone); } assertEquals(dict, clone); } } }
public void testSerializationAndDeserializationOfStringPatterns() throws Exception { final String[] patternNames = referenceDataCatalog.getStringPatternNames(); for (final String name : patternNames) { final StringPattern pattern = referenceDataCatalog.getStringPattern(name); if (pattern instanceof AbstractReferenceData) { System.out.println("Cloning string pattern: " + pattern); final Object clone = SerializationUtils.clone(pattern); if (!pattern.equals(clone)) { System.out.println(); } assertEquals(pattern, clone); } } }
@Override public Model train(ModelConfig config, List<Object[]> instances) throws FOSException { checkNotNull(instances, "Instances must be supplied"); checkNotNull(config, "Config must be supplied"); long time = System.currentTimeMillis(); WekaModelConfig wekaModelConfig = new WekaModelConfig(config, wekaManagerConfig); Classifier classifier = WekaClassifierFactory.create(config); FastVector attributes = WekaUtils.instanceFields2Attributes(wekaModelConfig.getClassIndex(), config.getAttributes()); InstanceSetter[] instanceSetters = WekaUtils.instanceFields2ValueSetters(config.getAttributes(), InstanceType.TRAINING); Instances wekaInstances = new Instances(config.getProperty(WekaModelConfig.CLASSIFIER_IMPL), attributes, instances.size()); for (Object[] objects : instances) { wekaInstances.add(WekaUtils.objectArray2Instance(objects, instanceSetters, attributes)); } trainClassifier(wekaModelConfig.getClassIndex(), classifier, wekaInstances); final byte[] bytes = SerializationUtils.serialize(classifier); logger.debug("Trained model with {} instances in {}ms", instances.size(), (System.currentTimeMillis() - time)); return new ModelBinary(bytes); }
/** * This has to be called before this object will be persistet. */ public void prepareForStore(PersistenceBroker broker) { if(object != null) { if(useIdentity) { Identity oid = broker.serviceIdentity().buildIdentity(object); this.oid = SerializationUtils.serialize(oid); } else { this.oid = SerializationUtils.serialize((Serializable) object); } } }
/** * Merge the given source {@link ConnectionRepository} with the * existing target. If parameter * <tt>deep</tt> is set <code>true</code> deep copies of source objects were made. * <br/> * Note: Using <tt>deep copy mode</tt> all descriptors will be serialized * by using the default class loader to resolve classes. This can be problematic * when classes are loaded by a context class loader. * <p> * Note: All classes within the repository structure have to implement * <code>java.io.Serializable</code> to be able to create a cloned copy. */ public void mergeConnectionRepository( ConnectionRepository targetRepository, ConnectionRepository sourceRepository, boolean deep) { List list = sourceRepository.getAllDescriptor(); for (Iterator iterator = list.iterator(); iterator.hasNext();) { JdbcConnectionDescriptor jcd = (JdbcConnectionDescriptor) iterator.next(); if (deep) { //TODO: adopt copy/clone methods for metadata classes? jcd = (JdbcConnectionDescriptor) SerializationUtils.clone(jcd); } targetRepository.addDescriptor(jcd); } }
/** * Merge the given {@link org.apache.ojb.broker.metadata.DescriptorRepository} * files, the source objects will be pushed to the target repository. If parameter * <tt>deep</tt> is set <code>true</code> deep copies of source objects were made. * <br/> * Note: Using <tt>deep copy mode</tt> all descriptors will be serialized * by using the default class loader to resolve classes. This can be problematic * when classes are loaded by a context class loader. * <p> * Note: All classes within the repository structure have to implement * <code>java.io.Serializable</code> to be able to create a cloned copy. * * @see #isEnablePerThreadChanges * @see #setEnablePerThreadChanges */ public void mergeDescriptorRepository( DescriptorRepository targetRepository, DescriptorRepository sourceRepository, boolean deep) { Iterator it = sourceRepository.iterator(); while (it.hasNext()) { ClassDescriptor cld = (ClassDescriptor) it.next(); if (deep) { //TODO: adopt copy/clone methods for metadata classes? cld = (ClassDescriptor) SerializationUtils.clone(cld); } targetRepository.put(cld.getClassOfObject(), cld); cld.setRepository(targetRepository); } }
/** * lock object and lock serialized unmodified version again */ public void testChangeMainFields_3() throws Exception { String name = "testChangeMainFields_3_" + System.currentTimeMillis(); Date date = new Date(); byte[] cover = new byte[]{2,3,4,5,6,7,8,9}; Book book = new Book(name, date, cover); TransactionExt tx = (TransactionExt) odmg.newTransaction(); tx.begin(); database.makePersistent(book); tx.commit(); Integer version = book.getVersion(); tx.begin(); tx.lock(book, Transaction.WRITE); book = (Book) SerializationUtils.clone(book); tx.lock(book, Transaction.WRITE); tx.commit(); assertEquals(version, book.getVersion()); }
public void testDoubleStore() { long timestamp = System.currentTimeMillis(); Person person = new Person(); person.setFirstname("testDoubleStore_" + timestamp); person.setLastname("time_" + timestamp); broker.beginTransaction(); // Identity used to assign PK of object Identity oid = new Identity(person, broker); Person serializedPerson = (Person) SerializationUtils.clone(person); broker.store(person); broker.store(person); broker.store(serializedPerson); broker.commitTransaction(); Criteria crit = new Criteria(); crit.addLike("firstName", "testDoubleStore_" + timestamp); Query query = QueryFactory.newQuery(Person.class, crit); Collection result = broker.getCollectionByQuery(query); assertEquals("Expect to find exact 1 object for "+oid, 1, result.size()); }
public void testSerializeAndDeserialize() throws Exception { RowAnnotationFactory annotationFactory = new InMemoryRowAnnotationFactory(); RowAnnotation annotation = annotationFactory.createAnnotation(); InputColumn<String> col1 = new MockInputColumn<String>("foo", String.class); InputColumn<String> col2 = new MockInputColumn<String>("bar", String.class); annotationFactory.annotate(new MockInputRow().put(col1, "1").put(col2, "2"), 1, annotation); annotationFactory.annotate(new MockInputRow().put(col1, "3").put(col2, "4"), 1, annotation); AnnotatedRowsResult result1 = new AnnotatedRowsResult(annotation, annotationFactory, col1); performAssertions(result1); AnnotatedRowsResult result2 = (AnnotatedRowsResult) SerializationUtils.deserialize(SerializationUtils .serialize(result1)); performAssertions(result2); }
public void testSerializationAndDeserialization() throws Exception { final NumberResult result1 = new NumberResult(42); final AnalyzerResultFuture<NumberResult> future = new AnalyzerResultFuture<>("foo", new ImmutableRef<NumberResult>(result1)); future.addListener(new Listener<NumberResult>() { @Override public void onSuccess(NumberResult result) { // do nothing - this is just a non-serializable listener } @Override public void onError(RuntimeException error) { // do nothing - this is just a non-serializable listener } }); final byte[] bytes = SerializationUtils.serialize(future); final AnalyzerResultFuture<?> copy = (AnalyzerResultFuture<?>) SerializationUtils.deserialize(bytes); assertEquals("foo", copy.getName()); assertEquals("42", copy.get().toString()); }
public void testSerializationAndDeserializationOfStringPatterns() throws Exception { String[] patternNames = referenceDataCatalog.getStringPatternNames(); for (String name : patternNames) { StringPattern pattern = referenceDataCatalog.getStringPattern(name); if (pattern instanceof AbstractReferenceData) { System.out.println("Cloning string pattern: " + pattern); Object clone = SerializationUtils.clone(pattern); if (!pattern.equals(clone)) { System.out.println(); } assertEquals(pattern, clone); } } }