Example usage for org.apache.commons.lang3 SerializationUtils serialize

List of usage examples for org.apache.commons.lang3 SerializationUtils serialize

Introduction

In this page you can find the example usage for org.apache.commons.lang3 SerializationUtils serialize.

Prototype

public static byte[] serialize(final Serializable obj) 

Source Link

Document

Serializes an Object to a byte array for storage/serialization.

Usage

From source file:org.force66.beantester.utils.GenericProxyHandlerTest.java

private void performRoundTrip(Object obj) {
    bean = new TestBean();
    bean.setFieldValue(obj);//from w w w .  ja v  a2 s  .  c om
    byte[] serializedObj = SerializationUtils.serialize(bean);
    Serializable sBeanReconstituted = SerializationUtils.deserialize(serializedObj);
    Assert.assertTrue(bean.equals(sBeanReconstituted));
}

From source file:org.glassfish.jersey.examples.feedcombiner.resources.CombinedFeedControllerTest.java

private InputStream serializedDatastore() {
    HashMap<String, Serializable> datastore = new HashMap<>();
    byte[] serialized = SerializationUtils.serialize(datastore);
    return new ByteArrayInputStream(serialized);
}

From source file:org.glassfish.jersey.examples.feedcombiner.store.ReadWriteLockDataStoreTest.java

@Test
public void loadDatastoreIsNotClosed() {
    try {//www. j a  v a2s.c om
        byte[] serializedDatastore = SerializationUtils.serialize(new HashMap<String, Serializable>());

        testedClass.load(new InputStreamStub(serializedDatastore));
    } catch (UnsupportedOperationException e) {
        fail("It is not allowed to call a method close on InputStream");
    } catch (IOException e) {
        fail("Unexpected Error");
    }
}

From source file:org.glassfish.jersey.examples.feedcombiner.store.ReadWriteLockDataStoreTest.java

@Test
public void testLoadDatastore() {
    // Insert new combined Feed
    String id = "1";
    CombinedFeed feed = new CombinedFeed.CombinedFeedBuilder(id, "http://localhost").title("title")
            .description("description").refreshPeriod(5L).build();

    // call save mock
    observer.save(feed);/*from  w w w.j  a  v a2  s. c  o  m*/

    // Create a datastore with one Combined Feed and serialize it
    String id2 = "2";
    CombinedFeed deserializedFeed = new CombinedFeed.CombinedFeedBuilder(id2, "http://localhost")
            .title("deserialized_title").description("deserialized_description").refreshPeriod(5L).build();

    HashMap<String, Serializable> datastore = new HashMap<>();
    datastore.put(id2, deserializedFeed);

    // call mocks after a load of the datastore
    Capture<Set<String>> captureRemoveAll = EasyMock.newCapture();
    Capture<Collection<Serializable>> captureSaveAll = EasyMock.newCapture();
    observer.removeAll(capture(captureRemoveAll));
    observer.saveAll(capture(captureSaveAll));

    replayAll();

    // Insert feed into the old datastore
    testedClass.put(id, feed);

    byte[] serializedDatastore = SerializationUtils.serialize(datastore);

    // Load the serialized datastore
    ByteArrayInputStream input = new ByteArrayInputStream(serializedDatastore);
    try {
        testedClass.load(input);

        // Test that the new datastore does not contain old Combined Feed
        CombinedFeed previousCombinedFeed = testedClass.get(id, CombinedFeed.class);
        if (previousCombinedFeed != null) {
            fail("The previous combined feed should be deleted.");
        }

        // Test that the new datastore contains new Combined Feed
        CombinedFeed newCombinedFeed = testedClass.get(id2, CombinedFeed.class);
        assertEquals(deserializedFeed, newCombinedFeed);
    } catch (IOException e) {
        fail(e.getMessage());
    }

    verifyAll();

    // Verify captured values
    // Check whether the registered observer was called because of removing entities
    Set<String> previousKeySet = captureRemoveAll.getValue();
    if (!previousKeySet.contains(id)) {
        fail("The previous keys should be deleted.");
    }

    // Check whether the registered observer was called because of saving entities
    Collection<Serializable> newlySavedEntities = captureSaveAll.getValue();
    assertEquals(1, newlySavedEntities.size());
    boolean exists = newlySavedEntities.stream().map(CombinedFeed.class::cast)
            .anyMatch(entity -> Objects.equals(entity.getId(), id2));
    if (!exists) {
        fail("The new stored CombinedFeed was not found.");
    }
}

From source file:org.glassfish.jersey.examples.feedcombiner.store.ReadWriteLockDataStoreTest.java

@Test
public void testLoadCastException() {
    byte[] serializedObject = SerializationUtils.serialize("Wrong object");
    ByteArrayInputStream input = new ByteArrayInputStream(serializedObject);

    try {//ww  w  . j  a  va 2  s . co m
        testedClass.load(input);
    } catch (IOException e) {
        fail("Any IOException should not occur.");
    }
}

From source file:org.grouplens.grapht.reflect.QualifiersTest.java

@Test
public void testClassMatcherBadClassError() {
    Qualifiers.AnnotationClassMatcher.SerialProxy proxy = new Qualifiers.AnnotationClassMatcher.SerialProxy(
            String.class);
    byte[] data = SerializationUtils.serialize(proxy);
    try {//w w  w  .  j a v  a  2 s. com
        SerializationUtils.deserialize(data);
        fail("deserialization should fail with error");
    } catch (SerializationException e) {
        assertThat(e.getCause(), instanceOf(InvalidObjectException.class));
        assertThat(e.getCause().getCause(), instanceOf(ClassCastException.class));
    }
}

From source file:org.hillview.dataset.RemoteDataSet.java

/**
 * Map operations on a RemoteDataSet result in only one onNext
 * invocation that will return the final IDataSet.
 *///w  w  w.j  a  v  a  2 s  . co  m
@Override
public <S> Observable<PartialResult<IDataSet<S>>> map(final IMap<T, S> mapper) {
    final MapOperation<T, S> mapOp = new MapOperation<T, S>(mapper);
    final byte[] serializedOp = SerializationUtils.serialize(mapOp);
    final UUID operationId = UUID.randomUUID();
    final Command command = Command.newBuilder().setIdsIndex(this.remoteHandle)
            .setSerializedOp(ByteString.copyFrom(serializedOp)).setHighId(operationId.getMostSignificantBits())
            .setLowId(operationId.getLeastSignificantBits()).build();
    final SerializedSubject<PartialResult<IDataSet<S>>, PartialResult<IDataSet<S>>> subj = createSerializedSubject();
    final StreamObserver<PartialResponse> responseObserver = new NewDataSetObserver<S>(subj);
    return subj.unsubscribeOn(ExecutorUtils.getUnsubscribeScheduler()).doOnSubscribe(
            () -> this.stub.withDeadlineAfter(TIMEOUT, TimeUnit.MILLISECONDS).map(command, responseObserver))
            .doOnUnsubscribe(() -> this.unsubscribe(operationId));
}

From source file:org.hillview.dataset.RemoteDataSet.java

@Override
public <S> Observable<PartialResult<IDataSet<S>>> flatMap(IMap<T, List<S>> mapper) {
    final FlatMapOperation<T, S> mapOp = new FlatMapOperation<T, S>(mapper);
    final byte[] serializedOp = SerializationUtils.serialize(mapOp);
    final UUID operationId = UUID.randomUUID();
    final Command command = Command.newBuilder().setIdsIndex(this.remoteHandle)
            .setSerializedOp(ByteString.copyFrom(serializedOp)).setHighId(operationId.getMostSignificantBits())
            .setLowId(operationId.getLeastSignificantBits()).build();
    final SerializedSubject<PartialResult<IDataSet<S>>, PartialResult<IDataSet<S>>> subj = createSerializedSubject();
    final StreamObserver<PartialResponse> responseObserver = new NewDataSetObserver<S>(subj);
    return subj// www . j a  v a 2s  .c o m
            .unsubscribeOn(ExecutorUtils.getUnsubscribeScheduler()).doOnSubscribe(() -> this.stub
                    .withDeadlineAfter(TIMEOUT, TimeUnit.MILLISECONDS).flatMap(command, responseObserver))
            .doOnUnsubscribe(() -> this.unsubscribe(operationId));
}

From source file:org.hillview.dataset.RemoteDataSet.java

/**
 * Sketch operation that streams partial results from the server to the caller.
 *//* w  ww . ja va  2s  .co  m*/
@Override
public <R> Observable<PartialResult<R>> sketch(final ISketch<T, R> sketch) {
    final SketchOperation<T, R> sketchOp = new SketchOperation<T, R>(sketch);
    final byte[] serializedOp = SerializationUtils.serialize(sketchOp);
    final UUID operationId = UUID.randomUUID();
    final Command command = Command.newBuilder().setIdsIndex(this.remoteHandle)
            .setSerializedOp(ByteString.copyFrom(serializedOp)).setHighId(operationId.getMostSignificantBits())
            .setLowId(operationId.getLeastSignificantBits()).build();
    final SerializedSubject<PartialResult<R>, PartialResult<R>> subj = createSerializedSubject();
    final StreamObserver<PartialResponse> responseObserver = new SketchObserver<R>(subj);
    return subj
            .doOnSubscribe(() -> this.stub.withDeadlineAfter(TIMEOUT, TimeUnit.MILLISECONDS).sketch(command,
                    responseObserver))
            .unsubscribeOn(ExecutorUtils.getUnsubscribeScheduler())
            .doOnUnsubscribe(() -> this.unsubscribe(operationId));
}

From source file:org.hillview.dataset.RemoteDataSet.java

/**
 * Zip operation on two IDataSet objects that need to reside on the same remote server.
 *///  w  w  w.  ja v a  2 s  .co  m
@Override
public <S> Observable<PartialResult<IDataSet<Pair<T, S>>>> zip(final IDataSet<S> other) {
    if (!(other instanceof RemoteDataSet<?>)) {
        throw new RuntimeException("Unexpected type in Zip " + other);
    }
    final RemoteDataSet<S> rds = (RemoteDataSet<S>) other;

    // zip commands are not valid if the RemoteDataSet instances point to different
    // actor systems or different nodes.
    final HostAndPort leftAddress = this.serverEndpoint;
    final HostAndPort rightAddress = rds.serverEndpoint;
    if (!leftAddress.equals(rightAddress)) {
        throw new RuntimeException("Zip command invalid for RemoteDataSets "
                + "across different servers | left: " + leftAddress + ", right:" + rightAddress);
    }

    final ZipOperation zip = new ZipOperation(rds.remoteHandle);
    final byte[] serializedOp = SerializationUtils.serialize(zip);
    final UUID operationId = UUID.randomUUID();
    final Command command = Command.newBuilder().setIdsIndex(this.remoteHandle)
            .setSerializedOp(ByteString.copyFrom(serializedOp)).setHighId(operationId.getMostSignificantBits())
            .setLowId(operationId.getLeastSignificantBits()).build();
    final SerializedSubject<PartialResult<IDataSet<Pair<T, S>>>, PartialResult<IDataSet<Pair<T, S>>>> subj = createSerializedSubject();
    final StreamObserver<PartialResponse> responseObserver = new NewDataSetObserver<Pair<T, S>>(subj);
    return subj.unsubscribeOn(ExecutorUtils.getUnsubscribeScheduler()).doOnSubscribe(
            () -> this.stub.withDeadlineAfter(TIMEOUT, TimeUnit.MILLISECONDS).zip(command, responseObserver))
            .doOnUnsubscribe(() -> this.unsubscribe(operationId));
}