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

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

Introduction

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

Prototype

public static byte[] serialize(Serializable obj) 

Source Link

Document

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

Usage

From source file:com.zia.freshdocs.preference.CMISPreferencesManager.java

public void storeFavorites(Context ctx, Set<NodeRef> favorites) {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    byte[] enc = Base64.encodeBase64(SerializationUtils.serialize((Serializable) favorites));
    Editor prefsEditor = sharedPrefs.edit();
    prefsEditor.putString(FAVORITES_KEY, new String(enc));
    prefsEditor.commit();/* w w w  .  java2 s. co  m*/
}

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> createStateIfAbsent(State state) {
    Preconditions.checkNotNull(state);//  w w w  .j a v  a  2  s.  c  o  m

    synchronized (lock) {
        if (this.state == null) {
            this.state = new Data<>(SerializationUtils.serialize(state), 0);
        }
    }
    return CompletableFuture.completedFuture(null);
}

From source file:io.pravega.controller.store.stream.PersistentStreamBase.java

@Override
public CompletableFuture<Boolean> updateState(final State state) {
    return getStateData().thenCompose(currState -> {
        if (State.isTransitionAllowed((State) SerializationUtils.deserialize(currState.getData()), state)) {
            return setStateData(new Data<>(SerializationUtils.serialize(state), currState.getVersion()))
                    .thenApply(x -> true);
        } else {/*from ww  w . j  av  a2s.c  om*/
            return FutureHelpers.failedFuture(StoreException.create(StoreException.Type.OPERATION_NOT_ALLOWED,
                    "Stream: " + getName() + " State: " + state.name()));
        }
    });
}

From source file:com.moz.fiji.mapreduce.kvstore.lib.InMemoryMapKeyValueStore.java

@Override
public void storeToConf(KeyValueStoreConfiguration conf) throws IOException {
    try {/*www . j a  v a2 s.  co m*/
        conf.set(CONF_MAP, Base64.encodeBase64String(SerializationUtils.serialize(mMap)));
    } catch (SerializationException se) {
        // Throw a more helpful error message for the user.
        throw new SerializationException(
                "InMemoryKeyValueStore requires that its keys and values are Serializable", se);
    }
}

From source file:com.impetus.ankush.common.domain.Node.java

public void setNodeConfig(NodeConfig nodeConf) {
    this.setConfBytes(SerializationUtils.serialize(nodeConf));
}

From source file:io.pravega.service.server.host.ZKSegmentContainerMonitorTest.java

@Test
public void testShutdownNotYetStartedContainer() throws Exception {
    @Cleanup//from  w w w  .  j a  va2 s.co m
    CuratorFramework zkClient = startClient();
    initializeHostContainerMapping(zkClient);

    SegmentContainerRegistry containerRegistry = createMockContainerRegistry();
    @Cleanup
    ZKSegmentContainerMonitor segMonitor = createContainerMonitor(containerRegistry, zkClient);
    segMonitor.initialize(Duration.ofSeconds(1));

    // Simulate a container that takes a long time to start. Should be greater than a few monitor loops.
    ContainerHandle containerHandle = mock(ContainerHandle.class);
    when(containerHandle.getContainerId()).thenReturn(2);
    CompletableFuture<ContainerHandle> startupFuture = FutureHelpers
            .delayedFuture(() -> CompletableFuture.completedFuture(containerHandle), 3000, executorService());
    when(containerRegistry.startContainer(eq(2), any())).thenReturn(startupFuture);

    // Use ZK to send that information to the Container Manager.
    HashMap<Host, Set<Integer>> currentData = deserialize(zkClient, PATH);
    currentData.put(PRAVEGA_SERVICE_ENDPOINT, Collections.singleton(2));
    zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData));

    // Verify it's not yet started.
    verify(containerRegistry, timeout(10000).atLeastOnce()).startContainer(eq(2), any());
    assertEquals(0, segMonitor.getRegisteredContainers().size());

    // Now simulate shutting it down.
    when(containerRegistry.stopContainer(any(), any())).thenReturn(CompletableFuture.completedFuture(null));

    currentData.clear();
    zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData));

    verify(containerRegistry, timeout(10000).atLeastOnce()).stopContainer(any(), any());
    Thread.sleep(2000);
    assertEquals(0, segMonitor.getRegisteredContainers().size());
}

From source file:io.pravega.segmentstore.server.host.ZKSegmentContainerMonitorTest.java

@Test
public void testShutdownNotYetStartedContainer() throws Exception {
    @Cleanup/*from  www.  j  ava2s  .c o  m*/
    CuratorFramework zkClient = startClient();
    initializeHostContainerMapping(zkClient);

    SegmentContainerRegistry containerRegistry = createMockContainerRegistry();
    @Cleanup
    ZKSegmentContainerMonitor segMonitor = createContainerMonitor(containerRegistry, zkClient);
    segMonitor.initialize(Duration.ofSeconds(1));

    // Simulate a container that takes a long time to start. Should be greater than a few monitor loops.
    ContainerHandle containerHandle = mock(ContainerHandle.class);
    when(containerHandle.getContainerId()).thenReturn(2);
    CompletableFuture<ContainerHandle> startupFuture = FutureHelpers
            .delayedFuture(() -> CompletableFuture.completedFuture(containerHandle), 3000, executorService());
    when(containerRegistry.startContainer(eq(2), any())).thenReturn(startupFuture);

    // Use ZK to send that information to the Container Manager.
    HashMap<Host, Set<Integer>> currentData = deserialize(zkClient, PATH);
    currentData.put(PRAVEGA_SERVICE_ENDPOINT, Collections.singleton(2));
    zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData));

    // Verify it's not yet started.
    verify(containerRegistry, timeout(1000).atLeastOnce()).startContainer(eq(2), any());
    assertEquals(0, segMonitor.getRegisteredContainers().size());

    // Now simulate shutting it down.
    when(containerRegistry.stopContainer(any(), any())).thenReturn(CompletableFuture.completedFuture(null));

    currentData.clear();
    zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData));

    verify(containerRegistry, timeout(10000).atLeastOnce()).stopContainer(any(), any());
    Thread.sleep(2000);
    assertEquals(0, segMonitor.getRegisteredContainers().size());
}

From source file:co.cask.cdap.internal.app.runtime.schedule.DataSetBasedScheduleStore.java

private void persistJob(OrderedTable table, JobDetail job) throws Exception {
    byte[][] cols = new byte[1][];
    byte[][] values = new byte[1][];

    cols[0] = Bytes.toBytes(job.getKey().toString());
    values[0] = SerializationUtils.serialize(job);
    table.put(JOB_KEY, cols, values);//  w  w  w .  ja v a2  s  .  com
}

From source file:com.janrain.backplane.server.MessageProcessor.java

/**
 * Processor to pull messages off queue and make them available
 *
 *//*ww w.  j  a v a2 s. c o  m*/
private void insertMessages() {

    try {
        logger.info("v1 message processor started");

        List<String> insertionTimes = new ArrayList<String>();
        do {

            logger.debug("beginning message processor loop");

            Jedis jedis = null;

            try {

                jedis = Redis.getInstance().getWriteJedis();
                logger.debug("retrieved jedis connection: " + jedis.toString());

                // set watch on V1_LAST_ID
                // needs to be set before retrieving the value stored at this key
                jedis.watch(V1_LAST_ID);
                Pair<String, Date> lastIdAndDate = getLastMessageId(jedis);
                String newId = lastIdAndDate.getLeft();

                // retrieve a handful of messages (ten) off the queue for processing
                List<byte[]> messagesToProcess = jedis
                        .lrange(RedisBackplaneMessageDAO.V1_MESSAGE_QUEUE.getBytes(), 0, 9);

                logger.debug("number of messages to process: " + messagesToProcess.size());

                // only enter the next block if we have messages to process
                if (messagesToProcess.size() > 0) {

                    Transaction transaction = jedis.multi();

                    insertionTimes.clear();

                    // <ATOMIC> - redis transaction
                    for (byte[] messageBytes : messagesToProcess) {

                        if (messageBytes != null) {
                            BackplaneMessage backplaneMessage = (BackplaneMessage) SerializationUtils
                                    .deserialize(messageBytes);

                            if (backplaneMessage != null) {

                                // retrieve the expiration config per the bus
                                BusConfig1 busConfig1 = DaoFactory.getBusDAO().get(backplaneMessage.getBus());
                                int retentionTimeSeconds = 60;
                                int retentionTimeStickySeconds = 3600;
                                if (busConfig1 != null) {
                                    // should be here in normal flow
                                    retentionTimeSeconds = busConfig1.getRetentionTimeSeconds();
                                    retentionTimeStickySeconds = busConfig1.getRetentionTimeStickySeconds();
                                }

                                String oldId = backplaneMessage.getIdValue();
                                insertionTimes.add(oldId);

                                // TOTAL ORDER GUARANTEE
                                // verify that the date portion of the new message ID is greater than all existing message ID dates
                                // if not, uptick id by 1 ms and insert
                                // this means that all message ids have unique time stamps, even if they
                                // arrived at the same time.

                                lastIdAndDate = backplaneMessage.updateId(lastIdAndDate);
                                newId = backplaneMessage.getIdValue();

                                // messageTime is guaranteed to be a unique identifier of the message
                                // because of the TOTAL ORDER mechanism above
                                long messageTime = BackplaneMessage.getDateFromId(newId).getTime();

                                // save the individual message by key
                                transaction.set(RedisBackplaneMessageDAO.getKey(newId),
                                        SerializationUtils.serialize(backplaneMessage));
                                // set the message TTL
                                if (backplaneMessage.isSticky()) {
                                    transaction.expire(RedisBackplaneMessageDAO.getKey(newId),
                                            retentionTimeStickySeconds);
                                } else {
                                    transaction.expire(RedisBackplaneMessageDAO.getKey(newId),
                                            retentionTimeSeconds);
                                }

                                // add message id to channel list
                                transaction.rpush(
                                        RedisBackplaneMessageDAO.getChannelKey(backplaneMessage.getChannel()),
                                        newId.getBytes());

                                // add message id to sorted set of all message ids as an index
                                String metaData = backplaneMessage.getBus() + " "
                                        + backplaneMessage.getChannel() + " " + newId;
                                transaction.zadd(RedisBackplaneMessageDAO.V1_MESSAGES.getBytes(), messageTime,
                                        metaData.getBytes());

                                // add message id to sorted set keyed by bus as an index
                                transaction.zadd(RedisBackplaneMessageDAO.getBusKey(backplaneMessage.getBus()),
                                        messageTime, newId.getBytes());

                                // make sure all subscribers get the update
                                transaction.publish("alerts", newId);

                                // pop one message off the queue - which will only happen if this transaction is successful
                                transaction.lpop(RedisBackplaneMessageDAO.V1_MESSAGE_QUEUE);

                                logger.info("pipelined message " + oldId + " -> " + newId);
                            }
                        }
                    } // for messages

                    transaction.set(V1_LAST_ID, newId);

                    logger.info("processing transaction with " + insertionTimes.size() + " message(s)");
                    if (transaction.exec() == null) {
                        // the transaction failed
                        continue;
                    }
                    // </ATOMIC> - redis transaction

                    logger.info("flushed " + insertionTimes.size() + " messages");
                    long now = System.currentTimeMillis();
                    for (String insertionId : insertionTimes) {
                        Date oldIdDate = BackplaneMessage.getDateFromId(insertionId);
                        long diff = now - oldIdDate.getTime();
                        timeInQueue.update(diff);
                        if (diff < 0 || diff > 2880000) {
                            logger.warn("time diff is bizarre at: " + diff + "; now: "
                                    + DateTimeUtils.ISO8601.get().format(new Date(now)) + ", oldId: "
                                    + DateTimeUtils.ISO8601.get().format(oldIdDate));
                        }
                    }

                    Thread.sleep(150);

                } // messagesToProcess > 0

            } catch (Exception e) {
                try {
                    logger.warn("error " + e.getMessage());
                    if (jedis != null) {
                        Redis.getInstance().releaseBrokenResourceToPool(jedis);
                        jedis = null;
                    }
                } catch (Exception e1) {
                    //ignore
                }
                Thread.sleep(2000);
            } finally {
                try {
                    if (jedis != null) {
                        jedis.unwatch();
                        Redis.getInstance().releaseToPool(jedis);
                    }

                } catch (Exception e) {
                    Redis.getInstance().releaseBrokenResourceToPool(jedis);
                }
            }

        } while (isLeader());

    } catch (Exception e) {
        logger.warn("exception thrown in message processor thread: " + e.getMessage());
    }
}

From source file:co.cask.cdap.internal.app.runtime.schedule.store.DatasetBasedTimeScheduleStore.java

private void persistJob(Table table, JobDetail job) throws Exception {
    byte[][] cols = new byte[1][];
    byte[][] values = new byte[1][];

    cols[0] = Bytes.toBytes(job.getKey().toString());
    values[0] = SerializationUtils.serialize(job);
    table.put(JOB_KEY, cols, values);/* w  ww . java  2s .com*/
}