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

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

Introduction

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

Prototype

public static <T> T deserialize(final byte[] objectData) 

Source Link

Document

Deserializes a single Object from an array of bytes.

Usage

From source file:org.force66.beantester.tests.SerializableTest.java

@Override
public boolean testBeanClass(Class<?> klass, Object[] constructorArgs) {
    this.setFailureReason(null);
    Object bean = InstantiationUtils.safeNewInstance(klass, constructorArgs);
    if (bean instanceof Serializable) {
        InjectionUtils.injectValues(bean, valueGeneratorFactory, false);

        Serializable sBean = (Serializable) bean;
        Serializable sBeanReconstituted = null;
        byte[] serializedObj;
        try {//from www .j  a v a2s.com
            serializedObj = SerializationUtils.serialize(sBean);
            sBeanReconstituted = SerializationUtils.deserialize(serializedObj);
        } catch (Throwable e) {
            this.setFailureReason("Error serializing bean that implements serializable");
            throw new BeanTesterException("Error serializing bean that implements serializable", e)
                    .addContextValue("class", klass.getName());
        }

        /*
         * An equals() test is only valid if the bean isn't relying on Object.equals().
         */
        Method equalsMethod = MethodUtils.getAccessibleMethod(klass, "equals", Object.class);
        if (!equalsMethod.getDeclaringClass().equals(Object.class) && !sBean.equals(sBeanReconstituted)) {
            this.setFailureReason(
                    "Bean implements serializable, but the reconstituted bean doesn't equal it's original");
            throw new BeanTesterException(
                    "Bean implements serializable, but the reconstituted bean doesn't equal it's original")
                            .addContextValue("class", klass.getName());
        }
    }
    return true;
}

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

private void performRoundTrip(Object obj) {
    bean = new TestBean();
    bean.setFieldValue(obj);//from  www  .j ava2s  .c  o m
    byte[] serializedObj = SerializationUtils.serialize(bean);
    Serializable sBeanReconstituted = SerializationUtils.deserialize(serializedObj);
    Assert.assertTrue(bean.equals(sBeanReconstituted));
}

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 {//ww w.j av  a2s. 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.remoting.HillviewServer.java

/**
 * Implementation of map() service in hillview.proto.
 *//* www.j a  v  a2 s. c o m*/
@Override
@SuppressWarnings("unchecked")
public void map(final Command command, final StreamObserver<PartialResponse> responseObserver) {
    try {
        final UUID commandId = this.getId(command);
        final IDataSet dataset = this.getIfValid(command.getIdsIndex(), responseObserver);
        if (dataset == null)
            return;
        final byte[] bytes = command.getSerializedOp().toByteArray();
        if (this.respondIfReplyIsMemoized(command, responseObserver, true)) {
            HillviewLogger.instance.info("Found memoized map", "on IDataSet#{0}", command.getIdsIndex());
            return;
        }

        final MapOperation mapOp = SerializationUtils.deserialize(bytes);
        final Observable<PartialResult<IDataSet>> observable = dataset.map(mapOp.mapper);
        Subscriber subscriber = this.createSubscriber(command, commandId, "map", responseObserver);
        final Subscription sub = observable.unsubscribeOn(ExecutorUtils.getUnsubscribeScheduler())
                .subscribe(subscriber);
        boolean unsub = this.saveSubscription(commandId, sub, "map");
        if (unsub)
            sub.unsubscribe();
    } catch (final Exception e) {
        HillviewLogger.instance.error("Exception in map", e);
        e.printStackTrace();
        responseObserver.onError(asStatusRuntimeException(e));
    }
}

From source file:org.hillview.dataset.remoting.HillviewServer.java

/**
 * Implementation of flatMap() service in hillview.proto.
 *///  ww  w .j a  va2s  .  c  o m
@Override
@SuppressWarnings("unchecked")
public void flatMap(final Command command, final StreamObserver<PartialResponse> responseObserver) {
    try {
        final UUID commandId = this.getId(command);
        final IDataSet dataset = this.getIfValid(command.getIdsIndex(), responseObserver);
        if (dataset == null)
            return;
        final byte[] bytes = command.getSerializedOp().toByteArray();

        if (this.respondIfReplyIsMemoized(command, responseObserver, true)) {
            HillviewLogger.instance.info("Found memoized flatMap", "on IDataSet#{0}", command.getIdsIndex());
            return;
        }
        final FlatMapOperation mapOp = SerializationUtils.deserialize(bytes);
        final Observable<PartialResult<IDataSet>> observable = dataset.flatMap(mapOp.mapper);
        Subscriber subscriber = this.createSubscriber(command, commandId, "flatMap", responseObserver);
        final Subscription sub = observable.unsubscribeOn(ExecutorUtils.getUnsubscribeScheduler())
                .subscribe(subscriber);
        boolean unsub = this.saveSubscription(commandId, sub, "flatMap");
        if (unsub)
            sub.unsubscribe();
    } catch (final Exception e) {
        HillviewLogger.instance.error("Exception in flatMap", e);
        e.printStackTrace();
        responseObserver.onError(asStatusRuntimeException(e));
    }
}

From source file:org.hillview.dataset.remoting.HillviewServer.java

/**
 * Implementation of sketch() service in hillview.proto.
 *///from   w ww  .java2  s . com
@Override
@SuppressWarnings("unchecked")
public void sketch(final Command command, final StreamObserver<PartialResponse> responseObserver) {
    try {
        final UUID commandId = this.getId(command);
        boolean memoize = MEMOIZE; // The value may change while we execute
        final IDataSet dataset = this.getIfValid(command.getIdsIndex(), responseObserver);
        if (dataset == null)
            return;
        if (this.respondIfReplyIsMemoized(command, responseObserver, false)) {
            HillviewLogger.instance.info("Found memoized sketch", "on IDataSet#{0}", command.getIdsIndex());
            return;
        }
        final byte[] bytes = command.getSerializedOp().toByteArray();
        final SketchOperation sketchOp = SerializationUtils.deserialize(bytes);
        final Observable<PartialResult> observable = dataset.sketch(sketchOp.sketch);
        Subscriber subscriber = new Subscriber<PartialResult>() {
            @Nullable
            private Object sketchResultAccumulator = memoize ? sketchOp.sketch.getZero() : null;
            private CompletableFuture queue = CompletableFuture.completedFuture(null);

            @Override
            public void onCompleted() {
                queue = queue.thenRunAsync(() -> {
                    responseObserver.onCompleted();
                    HillviewServer.this.removeSubscription(commandId, "sketch completed");

                    if (memoize && this.sketchResultAccumulator != null) {
                        final OperationResponse<PartialResult> res = new OperationResponse<PartialResult>(
                                new PartialResult(1.0, this.sketchResultAccumulator));
                        final byte[] bytes = SerializationUtils.serialize(res);
                        final PartialResponse memoizedResult = PartialResponse.newBuilder()
                                .setSerializedOp(ByteString.copyFrom(bytes)).build();
                        HillviewServer.this.memoizedCommands.insert(command, memoizedResult, 0);
                    }
                }, executorService);
            }

            @Override
            public void onError(final Throwable e) {
                queue = queue.thenRunAsync(() -> {
                    HillviewLogger.instance.error("Exception in sketch", e);
                    e.printStackTrace();
                    responseObserver.onError(asStatusRuntimeException(e));
                    HillviewServer.this.removeSubscription(commandId, "sketch onError");
                }, executorService);
            }

            @Override
            public void onNext(final PartialResult pr) {
                queue = queue.thenRunAsync(() -> {
                    if (memoize && this.sketchResultAccumulator != null)
                        this.sketchResultAccumulator = sketchOp.sketch.add(this.sketchResultAccumulator,
                                pr.deltaValue);
                    final OperationResponse<PartialResult> res = new OperationResponse<PartialResult>(pr);
                    final byte[] bytes = SerializationUtils.serialize(res);
                    responseObserver.onNext(
                            PartialResponse.newBuilder().setSerializedOp(ByteString.copyFrom(bytes)).build());
                }, executorService);
            }
        };
        final Subscription sub = observable.unsubscribeOn(ExecutorUtils.getUnsubscribeScheduler())
                .subscribe(subscriber);
        boolean unsub = this.saveSubscription(commandId, sub, "sketch");
        if (unsub)
            sub.unsubscribe();
    } catch (final Exception e) {
        HillviewLogger.instance.error("Exception in sketch", e);
        e.printStackTrace();
        responseObserver.onError(asStatusRuntimeException(e));
    }
}

From source file:org.hillview.dataset.remoting.HillviewServer.java

/**
 * Implementation of manage() service in hillview.proto.
 *///ww  w .  j a va2  s .c  om
@Override
@SuppressWarnings("unchecked")
public void manage(Command command, StreamObserver<PartialResponse> responseObserver) {
    try {
        final UUID commandId = this.getId(command);
        // TODO: handle errors in a better way in manage commands
        final IDataSet dataset = this.getIfValid(command.getIdsIndex(), responseObserver);
        if (dataset == null)
            return;
        final byte[] bytes = command.getSerializedOp().toByteArray();
        final ManageOperation manage = SerializationUtils.deserialize(bytes);
        Observable<PartialResult<ControlMessage.StatusList>> observable = dataset.manage(manage.message);
        final Callable<ControlMessage.StatusList> callable = () -> {
            HillviewLogger.instance.info("Starting manage", "{0}", manage.message.toString());
            ControlMessage.Status status;
            try {
                status = manage.message.remoteServerAction(this);
            } catch (final Throwable t) {
                status = new ControlMessage.Status("Exception", t);
            }
            ControlMessage.StatusList result = new ControlMessage.StatusList(status);
            HillviewLogger.instance.info("Completed manage", "{0}", manage.message.toString());
            return result;
        };
        Observable<JsonList<ControlMessage.Status>> executed = Observable.fromCallable(callable);
        observable = observable.mergeWith(executed.map(l -> new PartialResult(0, l)));

        Subscriber subscriber = new Subscriber<PartialResult<ControlMessage.StatusList>>() {
            @Override
            public void onCompleted() {
                responseObserver.onCompleted();
                HillviewServer.this.removeSubscription(commandId, "manage completed");
            }

            @Override
            public void onError(final Throwable e) {
                HillviewLogger.instance.error("Exception in manage operation", e);
                e.printStackTrace();
                responseObserver.onError(e);
                HillviewServer.this.removeSubscription(commandId, "manage onError");
            }

            @Override
            public void onNext(final PartialResult pr) {
                final OperationResponse<PartialResult> res = new OperationResponse<PartialResult>(pr);
                final byte[] bytes = SerializationUtils.serialize(res);
                responseObserver.onNext(
                        PartialResponse.newBuilder().setSerializedOp(ByteString.copyFrom(bytes)).build());
            }
        };
        // Results of management commands are never memoized.
        final Subscription sub = observable.unsubscribeOn(ExecutorUtils.getUnsubscribeScheduler())
                .subscribe(subscriber);
        boolean unsub = this.saveSubscription(commandId, sub, "manage");
        if (unsub)
            sub.unsubscribe();
    } catch (final Exception e) {
        HillviewLogger.instance.error("Exception in manage", e);
        e.printStackTrace();
    }
}

From source file:org.hillview.dataset.remoting.HillviewServer.java

/**
 * Implementation of zip() service in hillview.proto.
 *//*w  w  w  .  j  a va  2  s . com*/
@Override
@SuppressWarnings("unchecked")
public void zip(final Command command, final StreamObserver<PartialResponse> responseObserver) {
    try {
        final UUID commandId = this.getId(command);
        final byte[] bytes = command.getSerializedOp().toByteArray();
        final ZipOperation zipOp = SerializationUtils.deserialize(bytes);
        final IDataSet left = this.getIfValid(command.getIdsIndex(), responseObserver);
        if (left == null)
            return;
        final IDataSet right = this.getIfValid(zipOp.datasetIndex, responseObserver);
        if (right == null)
            return;
        if (this.respondIfReplyIsMemoized(command, responseObserver, true)) {
            HillviewLogger.instance.info("Found memoized zip", "on IDataSet#{0}", command.getIdsIndex());
            return;
        }

        final Observable<PartialResult<IDataSet>> observable = left.zip(right);
        Subscriber subscriber = this.createSubscriber(command, commandId, "zip", responseObserver);
        final Subscription sub = observable.unsubscribeOn(ExecutorUtils.getUnsubscribeScheduler())
                .subscribe(subscriber);
        boolean unsub = this.saveSubscription(commandId, sub, "zip");
        if (unsub)
            sub.unsubscribe();
    } catch (final Exception e) {
        HillviewLogger.instance.error("Exception in zip", e);
        e.printStackTrace();
        responseObserver.onError(asStatusRuntimeException(e));
    }
}

From source file:org.hillview.dataset.remoting.HillviewServer.java

/**
 * Implementation of unsubscribe() service in hillview.proto.
 *//*w ww . j  a v a 2s. c  o  m*/
@Override
public void unsubscribe(final Command command, final StreamObserver<Ack> responseObserver) {
    try {
        final byte[] bytes = command.getSerializedOp().toByteArray();
        final UnsubscribeOperation unsubscribeOp = SerializationUtils.deserialize(bytes);
        HillviewLogger.instance.info("Unsubscribing", "{0}", unsubscribeOp.id);
        @Nullable
        final Subscription subscription = this.removeSubscription(unsubscribeOp.id, "unsubscribe request");
        if (subscription != null) {
            subscription.unsubscribe();
        } else {
            HillviewLogger.instance.warn("Could not find subscription", "{0}", unsubscribeOp.id);
            this.toUnsubscribe.put(unsubscribeOp.id, true);
        }
    } catch (final Exception e) {
        HillviewLogger.instance.error("Exception in unsubscribe", e);
        responseObserver.onError(asStatusRuntimeException(e));
    }
}

From source file:org.hobbit.spatiotemporalbenchmark.platformConnection.TaskGenerator.java

@Override
protected void generateTask(byte[] data) throws Exception {
    LOGGER.info("generateTask");
    try {//  ww w. j  a v a 2s . c om
        // Create tasks based on the incoming data inside this method.
        // You might want to use the id of this task generator and the
        // number of all task generators running in parallel.
        //        int dataGeneratorId = getGeneratorId();
        //        int numberOfGenerators = getNumberOfGenerators();

        targetReceiver = SimpleFileReceiver.create(this.incomingDataQueueFactory, "target_file");

        String[] receivedFiles_target = targetReceiver.receiveData("./datasets/TargetDatasets/");

        for (String f : receivedFiles_target) {
            // define a queue name, e.g., read it from the environment
            String queueName = "task_target_file";
            File file = new File("./datasets/TargetDatasets/" + f);
            // create the sender
            SimpleFileSender sender = SimpleFileSender.create(this.outgoingDataQueuefactory, queueName);

            InputStream is = null;
            try {
                // create input stream, e.g., by opening a file
                is = new FileInputStream(file);
                // send data
                sender.streamData(is, file.getName());
            } catch (Exception e) {
                // handle exception
            } finally {
                IOUtils.closeQuietly(is);
            }
            // close the sender
            IOUtils.closeQuietly(sender);

        }

        // Create an ID for the task
        Task task = (Task) SerializationUtils.deserialize(data);
        String taskId = task.getTaskId();

        byte[] target = task.getTarget();
        ByteBuffer taskBuffer = ByteBuffer.wrap(target);
        String format = RabbitMQUtils.readString(taskBuffer);
        String path = RabbitMQUtils.readString(taskBuffer);

        byte[][] taskDataArray = new byte[2][];
        taskDataArray[0] = RabbitMQUtils.writeString(format);
        taskDataArray[1] = RabbitMQUtils.writeString(path);
        byte[] taskData = RabbitMQUtils.writeByteArrays(taskDataArray);
        byte[] expectedAnswerData = task.getExpectedAnswers();
        // Send the task to the system (and store the timestamp)
        long timestamp = System.currentTimeMillis();
        sendTaskToSystemAdapter(taskId, taskData);
        LOGGER.info("Task " + taskId + " sent to System Adapter.");

        // Send the expected answer to the evaluation store
        //            sendTaskToEvalStorage(taskId, timestamp, expectedAnswerData);
        sendTaskToEvalStorage(taskId, timestamp, expectedAnswerData);
        LOGGER.info("Expected answers of task " + taskId + " sent to Evaluation Storage.");

    } catch (Exception e) {
        LOGGER.error("Exception caught while reading the tasks and their expected answers", e);
    }
}