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.obsidianbox.obsidian.message.builtin.AddFileMessage.java

@SideOnly(Side.SERVER)
public AddFileMessage(String addonIdentifier, String name, Path path) {
    this.addonIdentifier = addonIdentifier;
    this.name = name;
    data = SerializationUtils.serialize(path.toFile());
}

From source file:org.obsidianbox.obsidian.message.builtin.DownloadLinkMessage.java

@Override
public void encode(Game game, ByteBuf buf) throws Exception {
    if (game.getSide().isClient()) {
        throw new IOException("Client is not allowed to send links!");
    }/*from   ww  w .j av  a2 s .  co m*/
    final byte[] data = SerializationUtils.serialize(url);
    ByteBufUtils.writeUTF8String(buf, addonIdentifier);
    buf.writeBytes(data);
}

From source file:org.omnaest.utils.structure.container.ByteArrayContainer.java

/**
 * Serializes any given {@link Serializable} element and stores it
 * //from  www .  j  ava2s  .c o m
 * @see #toDeserializedElement()
 * @param element
 * @return this
 */
public <S extends Serializable> ByteArrayContainer copyFromAsSerialized(S element) {
    final byte[] content = element != null ? SerializationUtils.serialize(element) : null;
    this.setContent(content);

    return this;
}

From source file:org.omnaest.utils.table.impl.persistence.SimpleFileBasedTablePersistence.java

private void writeToFile() {
    if (this.file != null) {
        try {/* w  ww.  j  a va2s  .c  o m*/
            byte[] data = SerializationUtils.serialize((Serializable) this.elementsList);
            FileUtils.writeByteArrayToFile(this.file, data);
        } catch (Exception e) {
            if (this.exceptionHandler != null) {
                this.exceptionHandler.handleException(e);
            }
        }
    }
}

From source file:org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransactionSerializer.java

@Override
public byte[] toBinary(final Object obj) {
    Preconditions.checkArgument(obj instanceof ReadyLocalTransaction, "Unsupported object type %s",
            obj.getClass());/*ww w  . j  av  a2  s  .c om*/
    final ReadyLocalTransaction readyLocal = (ReadyLocalTransaction) obj;
    final BatchedModifications batched = new BatchedModifications(readyLocal.getTransactionID(),
            readyLocal.getRemoteVersion());
    batched.setDoCommitOnReady(readyLocal.isDoCommitOnReady());
    batched.setTotalMessagesSent(1);
    batched.setReady(true);

    readyLocal.getModification().applyToCursor(new BatchedCursor(batched));

    return SerializationUtils.serialize(batched);
}

From source file:org.opendaylight.controller.cluster.datastore.shardmanager.ShardManager.java

private void onGetSnapshot() {
    LOG.debug("{}: onGetSnapshot", persistenceId());

    List<String> notInitialized = null;
    for (ShardInformation shardInfo : localShards.values()) {
        if (!shardInfo.isShardInitialized()) {
            if (notInitialized == null) {
                notInitialized = new ArrayList<>();
            }//from ww  w  .j a  v  a  2  s  . c  om

            notInitialized.add(shardInfo.getShardName());
        }
    }

    if (notInitialized != null) {
        getSender().tell(new Status.Failure(new IllegalStateException(
                String.format("%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))),
                getSelf());
        return;
    }

    byte[] shardManagerSnapshot = null;
    if (currentSnapshot != null) {
        shardManagerSnapshot = SerializationUtils.serialize(currentSnapshot);
    }

    ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
            new ArrayList<>(localShards.keySet()), type, shardManagerSnapshot, getSender(), persistenceId(),
            datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));

    for (ShardInformation shardInfo : localShards.values()) {
        shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
    }
}

From source file:org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerTest.java

@Test
public void testRestoreFromSnapshot() throws Throwable {
    LOG.info("testRestoreFromSnapshot starting");

    datastoreContextBuilder.shardInitializationTimeout(3, TimeUnit.SECONDS);

    JavaTestKit kit = new JavaTestKit(getSystem());

    MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
            .put("shard1", Collections.<String>emptyList()).put("shard2", Collections.<String>emptyList())
            .put("astronauts", Collections.<String>emptyList()).build());

    ShardManagerSnapshot snapshot = new ShardManagerSnapshot(Arrays.asList("shard1", "shard2", "astronauts"));
    DatastoreSnapshot restoreFromSnapshot = new DatastoreSnapshot(shardMrgIDSuffix,
            SerializationUtils.serialize(snapshot), Collections.<ShardSnapshot>emptyList());
    TestActorRef<TestShardManager> shardManager = actorFactory
            .createTestActor(newTestShardMgrBuilder(mockConfig).restoreFromSnapshot(restoreFromSnapshot).props()
                    .withDispatcher(Dispatchers.DefaultDispatcherId()));

    shardManager.underlyingActor().waitForRecoveryComplete();

    shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), ActorRef.noSender());

    waitForShardInitialized(shardManager, "shard1", kit);
    waitForShardInitialized(shardManager, "shard2", kit);
    waitForShardInitialized(shardManager, "astronauts", kit);

    shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());

    DatastoreSnapshot datastoreSnapshot = expectMsgClassOrFailure(DatastoreSnapshot.class, kit, "GetSnapshot");

    assertEquals("getType", shardMrgIDSuffix, datastoreSnapshot.getType());

    byte[] snapshotBytes = datastoreSnapshot.getShardManagerSnapshot();
    assertNotNull("Expected ShardManagerSnapshot", snapshotBytes);
    snapshot = SerializationUtils.deserialize(snapshotBytes);
    assertEquals("Shard names", Sets.newHashSet("shard1", "shard2", "astronauts"),
            Sets.newHashSet(snapshot.getShardList()));

    LOG.info("testRestoreFromSnapshot ending");
}

From source file:org.opendaylight.controller.cluster.datastore.ShardManager.java

private void onGetSnapshot() {
    LOG.debug("{}: onGetSnapshot", persistenceId());

    List<String> notInitialized = null;
    for (ShardInformation shardInfo : localShards.values()) {
        if (!shardInfo.isShardInitialized()) {
            if (notInitialized == null) {
                notInitialized = new ArrayList<>();
            }/*www.  j av a 2  s .c o m*/

            notInitialized.add(shardInfo.getShardName());
        }
    }

    if (notInitialized != null) {
        getSender().tell(
                new akka.actor.Status.Failure(new IllegalStateException(String
                        .format("%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))),
                getSelf());
        return;
    }

    byte[] shardManagerSnapshot = null;
    if (currentSnapshot != null) {
        shardManagerSnapshot = SerializationUtils.serialize(currentSnapshot);
    }

    ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
            new ArrayList<>(localShards.keySet()), type, shardManagerSnapshot, getSender(), persistenceId(),
            datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));

    for (ShardInformation shardInfo : localShards.values()) {
        shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
    }
}

From source file:org.opendaylight.controller.cluster.datastore.ShardManagerTest.java

@Test
public void testRestoreFromSnapshot() throws Throwable {
    LOG.info("testRestoreFromSnapshot starting");

    JavaTestKit kit = new JavaTestKit(getSystem());

    MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
            .put("shard1", Collections.<String>emptyList()).put("shard2", Collections.<String>emptyList())
            .put("astronauts", Collections.<String>emptyList()).build());

    ShardManagerSnapshot snapshot = new ShardManagerSnapshot(Arrays.asList("shard1", "shard2", "astronauts"));
    DatastoreSnapshot restoreFromSnapshot = new DatastoreSnapshot(shardMrgIDSuffix,
            SerializationUtils.serialize(snapshot), Collections.<ShardSnapshot>emptyList());
    TestActorRef<TestShardManager> shardManager = actorFactory
            .createTestActor(newTestShardMgrBuilder(mockConfig).restoreFromSnapshot(restoreFromSnapshot).props()
                    .withDispatcher(Dispatchers.DefaultDispatcherId()));

    shardManager.underlyingActor().waitForRecoveryComplete();

    shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), ActorRef.noSender());

    waitForShardInitialized(shardManager, "shard1", kit);
    waitForShardInitialized(shardManager, "shard2", kit);
    waitForShardInitialized(shardManager, "astronauts", kit);

    shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());

    DatastoreSnapshot datastoreSnapshot = expectMsgClassOrFailure(DatastoreSnapshot.class, kit, "GetSnapshot");

    assertEquals("getType", shardMrgIDSuffix, datastoreSnapshot.getType());

    byte[] snapshotBytes = datastoreSnapshot.getShardManagerSnapshot();
    assertNotNull("Expected ShardManagerSnapshot", snapshotBytes);
    snapshot = SerializationUtils.deserialize(snapshotBytes);
    assertEquals("Shard names", Sets.newHashSet("shard1", "shard2", "astronauts"),
            Sets.newHashSet(snapshot.getShardList()));

    LOG.info("testRestoreFromSnapshot ending");
}

From source file:org.opendaylight.controller.cluster.messaging.MessageAssemblerTest.java

@Test
public void testSingleMessageSlice() {
    try (MessageAssembler assembler = newMessageAssembler("testSingleMessageSlice")) {
        final FileBackedOutputStream fileBackStream = spy(new FileBackedOutputStream(100000000, null));
        doReturn(fileBackStream).when(mockFiledBackedStreamFactory).newInstance();

        final MessageSliceIdentifier identifier = new MessageSliceIdentifier(IDENTIFIER, 1);
        final BytesMessage message = new BytesMessage(new byte[] { 1, 2, 3 });

        final MessageSlice messageSlice = new MessageSlice(identifier, SerializationUtils.serialize(message), 1,
                1, SlicedMessageState.INITIAL_SLICE_HASH_CODE, testProbe.ref());
        assembler.handleMessage(messageSlice, testProbe.ref());

        final MessageSliceReply reply = testProbe.expectMsgClass(MessageSliceReply.class);
        assertSuccessfulMessageSliceReply(reply, IDENTIFIER, 1);

        assertAssembledMessage(mockAssembledMessageCallback, message, testProbe.ref());

        assertFalse("MessageAssembler did not remove state for " + identifier, assembler.hasState(identifier));
        verify(fileBackStream).cleanup();
    }/*w  ww.  j ava  2  s  .c  om*/
}