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:com.iveely.computing.api.StreamChannel.java

/**
 * Emit data to output.//  w  w w  . j a  v  a2 s .c  om
 */
public void emit(IWritable key, IWritable value) {
    // 1. record emit count on zookeeper.
    recordEmitCount(emitCount++);

    this.outputClients.entrySet().stream().forEach((entry) -> {
        List<AsynClient> list = (List<AsynClient>) entry.getValue();
        int code = Math.abs(key.hashCode() % list.size());

        // 2. Prepare stream packet.
        StreamPacket streamPacket = new StreamPacket();
        streamPacket.setData(SerializationUtils.serialize(new DataTuple(key, value)));
        streamPacket.setType(StreamType.DATASENDING);
        streamPacket.setGuid((String) this.outputGuids.get(entry.getKey()).get(code));
        streamPacket.setName(this.name);
        buffer.push(code, streamPacket);

        // 3. Check buffer, if reach state of full will be send.
        checkBuffer(code, list.get(code));
    });
}

From source file:com.splicemachine.derby.stream.output.delete.DeleteTableWriterBuilder.java

public String getDeleteTableWriterBuilderBase64String() throws IOException, StandardException {
    return Base64.encodeBase64String(SerializationUtils.serialize(this));
}

From source file:glluch.com.ontotaxoseeker.TestsGen.java

public void testtestConceptsCountResults() throws IOException {
    TaxoPath tp = new TaxoPath();
    PathsCount pc = tp.findPaths(DOC);//from   w  w  w  .  java2 s .co m
    File target = new File("resources/test/testConceptsCountResults.bin");
    byte[] vs = SerializationUtils.serialize(pc);
    FileUtils.writeByteArrayToFile(target, vs);
}

From source file:gobblin.runtime.api.TestJobSpec.java

@Test
public void testSerDe() {
    JobSpec.Builder b = new JobSpec.Builder("test:job");

    JobSpec js1 = b.build();//from   w ww .  j av  a  2  s.c o  m
    byte[] serializedBytes = SerializationUtils.serialize(js1);
    JobSpec js1Deserialized = SerializationUtils.deserialize(serializedBytes);

    Assert.assertEquals(js1Deserialized.getUri().toString(), js1.getUri().toString());
    Assert.assertEquals(js1Deserialized.getVersion(), js1.getVersion());
    Assert.assertNotNull(js1Deserialized.getDescription());
    Assert.assertTrue(js1Deserialized.getDescription().contains(js1.getDescription()));
    Assert.assertEquals(js1Deserialized.getConfig().entrySet().size(), 0);
    Assert.assertEquals(js1Deserialized.getConfigAsProperties().size(), 0);

    Properties props = new Properties();
    props.put("a1", "a_value");
    props.put("a2.b", "1");
    props.put("a2.c.d", "12.34");
    props.put("a2.c.d2", "true");

    b = new JobSpec.Builder("test:job2").withVersion("2").withDescription("A test job")
            .withConfigAsProperties(props);

    JobSpec js2 = b.build();
    serializedBytes = SerializationUtils.serialize(js2);
    JobSpec js2Deserialized = SerializationUtils.deserialize(serializedBytes);

    Assert.assertEquals(js2Deserialized.getUri().toString(), js2.getUri().toString());
    Assert.assertEquals(js2Deserialized.getVersion(), js2.getVersion());
    Assert.assertEquals(js2Deserialized.getDescription(), js2.getDescription());
    Assert.assertEquals(js2Deserialized.getConfig().getString("a1"), "a_value");
    Assert.assertEquals(js2Deserialized.getConfig().getLong("a2.b"), 1L);
    Assert.assertEquals(js2Deserialized.getConfig().getDouble("a2.c.d"), 12.34);
    Assert.assertTrue(js2Deserialized.getConfig().getBoolean("a2.c.d2"));
}

From source file:com.nesscomputing.sequencer.AbstractSequencerTest.java

@Test
public void testFullSerialization() {
    final S seq = extend(createEmpty(), "aaa", "bbb", "ccc", "ddd");
    byte[] bytes = SerializationUtils.serialize(seq);
    assertEquals(seq, SerializationUtils.deserialize(bytes));
}

From source file:io.hakbot.controller.plugin.BasePlugin.java

protected void setRemoteInstance(Job job, RemoteInstance remoteInstance) {
    final byte[] content = SerializationUtils.serialize(remoteInstance);
    try (QueryManager qm = new QueryManager()) {
        qm.setJobArtifact(job, JobArtifact.Type.REMOTE_INSTANCE, JobArtifact.MimeType.OBJECT.value(), content,
                null, null);//from ww w.  j ava 2 s . c o  m
    }
}

From source file:glluch.com.ontotaxoseeker.TestsGen.java

public void testTermsResults() throws IOException, FileNotFoundException, ClassNotFoundException {
    Terms ts = (Terms) TestsGen.load("resources/test/Terms.ser");
    ArrayList<Term> terms = ts.terms();
    Iterator iter = terms.iterator();
    ArrayList<String> lemas = new ArrayList<>();
    while (iter.hasNext()) {
        Term next = (Term) iter.next();/*from w  w w  . j  av a  2s  .  c o  m*/
        lemas.add(next.getLema());
    }
    File target = new File("resources/test/testTermsResults.bin");
    byte[] vs = SerializationUtils.serialize(lemas);
    FileUtils.writeByteArrayToFile(target, vs);
}

From source file:com.francetelecom.clara.cloud.paas.activation.v1.async.AmqpTaskHandler.java

@Override
public void onTaskPolled(TaskStatus taskStatus, final RetryContext retryContext, final String communicationId) {
    log.trace("onTaskPolled taskStatus={}", taskStatus.toString());
    // callback delegation
    final TaskStatus t = taskHandlerCallback.onTaskPolled(taskStatus);
    log.trace("[after] onTaskPolled taskStatus={}", t.toString());
    if (t.isComplete()) {
        log.trace("task is complete. no need to keep polling. Sends task Status to reply queue");
        MessageProperties props;// w w  w.  j  av  a2 s .c  o  m
        props = MessagePropertiesBuilder.newInstance()
                .setContentType(MessageProperties.CONTENT_TYPE_SERIALIZED_OBJECT)
                .setMessageId(UUID.randomUUID().toString()).setCorrelationId(communicationId.getBytes())
                .build();
        Message message = MessageBuilder.withBody(SerializationUtils.serialize(t)).andProperties(props).build();
        amqpReplyTemplate.send(message);
    }

    else {
        if (!retryPolicy.canRetry(retryContext.getRetryCount())) {
            // max retry count exceeded. no need to keep polling. Sends
            // Exception to error queue
            log.warn("Max retry count reached: " + retryPolicy.getMaxAttempts());
            MessageProperties props = MessagePropertiesBuilder.newInstance()
                    .setContentType(MessageProperties.CONTENT_TYPE_SERIALIZED_OBJECT)
                    .setMessageId(UUID.randomUUID().toString()).setCorrelationId(communicationId.getBytes())
                    .build();
            Message message = MessageBuilder
                    .withBody(SerializationUtils.serialize(new MaxRetryCountExceededException(
                            "Max retry count reached : " + retryPolicy.getMaxAttempts())))
                    .andProperties(props).build();
            amqpErrorTemplate.send(message);
        } else {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                log.warn("Thread sleeping before sending message back to Request queue has been interrupted.");
            }
            log.trace("task is not complete. Must keep polling. Sends task Status to request queue");
            MessageProperties props = MessagePropertiesBuilder.newInstance()
                    .setContentType(MessageProperties.CONTENT_TYPE_SERIALIZED_OBJECT)
                    .setMessageId(UUID.randomUUID().toString()).setCorrelationId(communicationId.getBytes())
                    .setHeader("retryCount", retryContext.getRetryCount() + 1).build();
            Message message = MessageBuilder.withBody(SerializationUtils.serialize(t)).andProperties(props)
                    .build();
            amqpRequestTemplate.send(message);

        }
    }
}

From source file:example.RepoContract.java

public byte[] toByteArr() {
    byte[] data = SerializationUtils.serialize(this);
    return data;//byte[] this;

}

From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java

@Override
public void open(@NonNull final Callback callback) {
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(mConsumerKey)
            .setOAuthConsumerSecret(mConsumerSecret).build();

    final Twitter instance = new TwitterFactory(configuration).getInstance();
    if (mAccessToken != null) {
        instance.setOAuthAccessToken(mAccessToken);
    }/* w ww .j av  a2 s. co  m*/

    doValidate(mAccessToken, instance).continueWithTask(new Continuation<User, Task<AccessToken>>() {
        @Override
        public Task<AccessToken> then(Task<User> task) throws Exception {
            if (task.isFaulted()) {
                SharedPreferences preferences = getActivity().getSharedPreferences("twitter",
                        Activity.MODE_PRIVATE);
                preferences.edit().clear().apply();

                mAccessToken = null;
                instance.setOAuthAccessToken(null);
                return doGetAuthenticationURL(instance)
                        .onSuccessTask(new Continuation<RequestToken, Task<Bundle>>() {
                            @Override
                            public Task<Bundle> then(Task<RequestToken> task) throws Exception {
                                return doDialogAuthentication(task.getResult());
                            }
                        }).onSuccessTask(new Continuation<Bundle, Task<AccessToken>>() {
                            @Override
                            public Task<AccessToken> then(Task<Bundle> task) throws Exception {
                                return doGetAccessToken(instance, task.getResult());
                            }
                        }).continueWith(new Continuation<AccessToken, AccessToken>() {
                            @Override
                            public AccessToken then(Task<AccessToken> task) throws Exception {
                                if (task.isFaulted()) {
                                    Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError());
                                    //                                Toast.makeText(getActivity(), task.getError().getMessage(), Toast.LENGTH_LONG).show();
                                    callback.onCancelled();
                                } else if (task.isCompleted()) {
                                    AccessToken accessToken = task.getResult();
                                    String serialized = Base64.encodeToString(
                                            SerializationUtils.serialize(accessToken), Base64.DEFAULT);

                                    SharedPreferences preferences = getActivity()
                                            .getSharedPreferences("twitter", Activity.MODE_PRIVATE);
                                    preferences.edit().putString("access_token_str", serialized).apply();
                                    callback.onSessionOpened(accessToken);
                                    mAccessToken = accessToken;

                                    return accessToken;
                                }

                                return null;
                            }
                        });
            } else {
                callback.onSessionOpened(mAccessToken);
                return Task.forResult(mAccessToken);
            }
        }
    });
}