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:org.archive.state.ModuleTestBase.java

/**
 * Tests that the module can be serialized.  The value returned by 
 * {@link #makeModule} is serialized to a byte array, and then 
 * deserialized, and then serialized to a second byte array.  The results
 * are passed to {@link #verifySerialization}, which will simply compare
 * the two byte arrays for equality.  (That won't always work; see
 * that method for details)./* w ww . j  a v a2 s .c  o  m*/
 * 
 * <p>If nothing else, this test is useful for catching NotSerializable
 * exceptions for your module or classes it depends on.
 * 
 * @throws Exception   if the module cannot be serialized
 */
public void testSerializationIfAppropriate() throws Exception {
    Object first = makeModule();
    if (!(first instanceof Serializable)) {
        return;
    }
    byte[] firstBytes = SerializationUtils.serialize((Serializable) first);

    Object second = SerializationUtils.deserialize(firstBytes);
    byte[] secondBytes = SerializationUtils.serialize((Serializable) second);

    Object third = SerializationUtils.deserialize(secondBytes);
    byte[] thirdBytes = SerializationUtils.serialize((Serializable) third);

    // HashMap serialization reverses order of items in linked buckets 
    // each roundtrip -- so don't check one roundtrip, check two.
    //
    // NOTE This is JVM-dependent behaviour, and since <= 1.7.0_u51 this
    // ordering of serialisation cannot be relied upon. However, a TreeMap
    // can be used instead of a HashMap, and this appears to have
    // predictable serialisation behaviour.
    //
    // @see
    // http://stackoverflow.com/questions/22392258/serialization-round-trip-of-hash-map-does-not-preserve-order
    //
    // verifySerialization(first, firstBytes, second, secondBytes);
    verifySerialization(first, firstBytes, third, thirdBytes);
}

From source file:org.archive.url.UsableURIFactoryTest.java

/**
 * A UURI's string representation should be same after a 
 * serialization roundtrip. //from   w  w  w. j  a  v  a  2  s.  c  o  m
 *  
 * @throws URIException
 */
public final void testSerializationRoundtrip() throws URIException {
    UsableURI uuri = UsableURIFactory.getInstance("http://www.example.com/path?query#anchor");
    UsableURI uuri2 = (UsableURI) SerializationUtils.deserialize(SerializationUtils.serialize(uuri));
    assertEquals("Not equal", uuri.toString(), uuri2.toString());
    uuri = UsableURIFactory.getInstance("file://///boo_hoo/wwwroot/CMS/Images1/Banner.gif");
    uuri2 = (UsableURI) SerializationUtils.deserialize(SerializationUtils.serialize(uuri));
    assertEquals("Not equal", uuri.toString(), uuri2.toString());
}

From source file:org.azrul.langmera.QLearningAnalytics.java

@Override
public void learn(DecisionFeedback currentFeedback, Vertx vertx, Runnable responseAction) {

    LocalMap<String, DetailDecisionFeedback> decisionFeedbackMap = vertx.sharedData()
            .getLocalMap("DECISION_FEEDBACK");
    LocalMap<String, DecisionRequest> decisionRequestMap = vertx.sharedData().getLocalMap("DECISION_REQUEST");
    LocalMap<String, DecisionResponse> decisionResponseMap = vertx.sharedData()
            .getLocalMap("DECISION_RESPONSE");
    LocalMap<String, Double> q = vertx.sharedData().getLocalMap("Q");
    LocalMap<Long, String> trackers = vertx.sharedData().getLocalMap("FEEDBACK_TRACKER");

    int feedbackCount = decisionFeedbackMap.size();
    boolean skipLearning = false;
    if (decisionRequestMap.get(currentFeedback.getDecisionId()) == null) {
        skipLearning = true;//  w w w .  j  av  a2 s. com
    }
    if (decisionResponseMap.get(currentFeedback.getDecisionId()) == null) {
        skipLearning = true;
    }
    if (skipLearning == false) {
        String context = decisionRequestMap.get(currentFeedback.getDecisionId()).getContext();
        String decision = decisionResponseMap.get(currentFeedback.getDecisionId()).getDecision();

        DetailDecisionFeedback detailFB = new DetailDecisionFeedback();
        detailFB.setFeedback(currentFeedback);
        detailFB.setContext(context);
        detailFB.setDecision(decision);
        decisionFeedbackMap.put(currentFeedback.getDecisionId(), detailFB);

        Long trackerKey = (new Date()).getTime();
        trackers.put(trackerKey, currentFeedback.getDecisionId());

        int feedbackCountByDecision = 0;
        List<Double> rewards = new ArrayList<>();
        for (DetailDecisionFeedback fb : decisionFeedbackMap.values()) {
            if (context.equals(decisionFeedbackMap.get(fb.getFeedback().getDecisionId()).getContext())
                    && decision
                            .equals(decisionFeedbackMap.get(fb.getFeedback().getDecisionId()).getDecision())) {
                feedbackCountByDecision++;
                rewards.add(fb.getFeedback().getScore());
            }
        }

        Double w = 0.0;
        Double alpha = config.getProperty("alpha", Double.class);

        //if no step parameter is configured, calculate it
        if (alpha == null) {
            alpha = 1.0 / (feedbackCountByDecision);
        }

        //non-stationary q-learning
        int i = 0;
        for (Double ri : rewards) {
            i++;
            w = w + alpha * (Math.pow(1 - alpha, feedbackCountByDecision - i)) * ri;
        }
        Double newQ = w;

        //System.out.println(feedbackCount+" Q:["+context + ":" + decision+"]"+newQ);
        //save what we learn
        if (newQ.isInfinite() || newQ.isNaN()) {
            //skip
        } else {
            String key = context + ":" + decision;
            q.put(key, newQ);
        }

        //Limit the number of history taken into account - prevents memory leak
        if (feedbackCount > config.getProperty("maxHistoryRetained", Integer.class)) {
            Long tk = Collections.min(trackers.keySet());
            String decisionIDWithMinTracker = trackers.get(tk);
            decisionFeedbackMap.remove(decisionIDWithMinTracker);
            trackers.remove(tk);
        }

        //clear cached req/resp once the feedback has come back
        decisionRequestMap.remove(currentFeedback.getDecisionId());
        decisionResponseMap.remove(currentFeedback.getDecisionId());

        //Get maxQ
        Double maxQ = Double.NEGATIVE_INFINITY;
        String decisionWithMaxQ = null;
        for (String contextDecision : q.keySet()) {
            if (q.get(contextDecision) > maxQ) {
                decisionWithMaxQ = contextDecision;
                maxQ = q.get(contextDecision);
            }
        }

        //keep traces
        if (Boolean.TRUE.equals(config.getProperty("collect.traces", Boolean.class))) {
            Date now = new Date();
            for (String contextDecision : q.keySet()) {
                List<Double> qtrace = traces.get(contextDecision);
                if (qtrace == null) {
                    qtrace = new ArrayList<Double>();
                    qtrace.add(q.get(contextDecision));
                    traces.put(contextDecision, qtrace);
                } else {
                    qtrace.add(q.get(contextDecision));
                }
                String[] c = contextDecision.split(":");
                Trace trace = new Trace(currentFeedback.getDecisionId(), c[0], q.get(contextDecision), maxQ,
                        now, c[1], currentFeedback.getScore());
                vertx.eventBus().publish("SAVE_TRACE_TO_TRACE",
                        SerializationUtils.serialize((Serializable) trace));
            }
        }

        //            //put in in-memory DB
        //            
        //            
        //            String[] c = decisionWithMaxQ.split(":");
        //            if (InMemoryDB.store.get(0)==null){
        //                List<Object> imContext = new ArrayList<Object>();
        //                imContext.add(c[0]);
        //                InMemoryDB.store.add(0,imContext);
        //            }else{
        //                InMemoryDB.store.get(0).add(c[0]);
        //            }
        //            
        //            if (InMemoryDB.store.get(1)==null){
        //                List<Object> imDecision = new ArrayList<Object>();
        //                imDecision.add(c[1]);
        //                InMemoryDB.store.add(1,imDecision);
        //            }else{
        //                InMemoryDB.store.get(1).add(c[1]);
        //            }
        //            
        //            if (InMemoryDB.store.get(2)==null){
        //                List<Object> imMaxQ = new ArrayList<Object>();
        //                imMaxQ.add(maxQ);
        //                InMemoryDB.store.add(2,imMaxQ);
        //            }else{
        //                InMemoryDB.store.get(2).add(maxQ);
        //            }
        //            
        //            if (InMemoryDB.store.get(3)==null){
        //                List<Object> imTime= new ArrayList<Object>();
        //                imTime.add(new Date());
        //                InMemoryDB.store.add(3,imTime);
        //            }else{
        //                InMemoryDB.store.get(3).add(new Date());
        //            }

        responseAction.run();
        if (Boolean.TRUE.equals(currentFeedback.getTerminal())) {
            long delta = (new Date()).getTime() - startTime;
            System.out.println("Time taken to process " + feedbackCount + " msgs:" + delta + " ms");
            System.out.println("Time taken per msg: " + (delta / feedbackCount) + " ms");
            System.out
                    .println("Msgs per s: " + ((1000.0 * (double) feedbackCount) / ((double) delta)) + " msgs");
            if (Boolean.TRUE.equals(config.getProperty("collect.traces", Boolean.class))
                    && Boolean.TRUE.equals(config.getProperty("display.desktop.chart", Boolean.class))) {
                final LineChart demo = new LineChart(chartDesc, traces);
                demo.pack();
                demo.setVisible(true);
            }
        }
    } else {
        logger.log(Level.WARNING, "Attempt to learn from a feedback with no corresponding request/response");
        responseAction.run();
    }
    //
    //select qmovies,qsports,qconcerts from 
    //   (select t1.qvalue as qsports,t1.decisionid from trace t1 where t1.decision='SPORTS' order by t1.decisiontime) as A1 
    //   join (select t2.qvalue as qmovies,t2.decisionid from trace t2 where t2.decision='MOVIES' order by t2.decisiontime) as A2 on A1.decisionid = A2.decisionid
    //   join (select t3.qvalue as qconcerts,t3.decisionid from trace t3 where t3.decision='CONCERTS' order by t3.decisiontime) as A3 on A1.decisionid = A3.decisionid

}

From source file:org.brocalc.domain.SerializationTest.java

@Test
public void brokerageScheduleShouldSerialize() {
    Broker broker = new Broker("TestBroker");

    BrokerageScheduleFactory brokerageScheduleFactory = new BrokerageScheduleFactory();
    BrokerageSchedule brokerageSchedule = brokerageScheduleFactory.createBrokerageSchedule(broker,
            EXAMPLE_SCHEDULE);/*from   w  w  w .j av a2s .  c om*/

    byte[] serializedForm = SerializationUtils.serialize(brokerageSchedule);
    brokerageSchedule = (BrokerageSchedule) SerializationUtils.deserialize(serializedForm);
}

From source file:org.codehaus.httpcache4j.cache.KeyTest.java

@Test
public void testSerializationWithEmptyVary() {
    Key key1 = Key.create(URI.create("foo"), new Vary());
    byte[] bytes = SerializationUtils.serialize(key1);
    Key key2 = (Key) SerializationUtils.deserialize(bytes);
    Assert.assertEquals(key1, key2);/*from  ww w. j a  va 2 s.  com*/
}

From source file:org.codehaus.httpcache4j.cache.KeyTest.java

@Test
public void testSerializationOneItemInVary() {
    Key key1 = Key.create(URI.create("foo"), new Vary(Collections.singletonMap("Accept-Language", "en")));
    byte[] bytes = SerializationUtils.serialize(key1);
    Key key2 = (Key) SerializationUtils.deserialize(bytes);
    Assert.assertEquals(key1, key2);//from  w ww  . ja v  a2  s.c  o  m
}

From source file:org.codekaizen.vtj.AbstractValueTypeTest.java

/**
 * Verifies that <code>Serializable</code> is implemented correctly.
 *//*from   w  ww  .jav a  2s.c  om*/
@Test(groups = { "api" })
public final void shouldImplementSerialization() {
    final ValueType<?> vt1 = getDefaultTestInstance();
    final ValueType<?> vt2 = (ValueType<?>) SerializationUtils.deserialize(SerializationUtils.serialize(vt1));
    assertEquals(vt2, vt1);
}

From source file:org.codekaizen.vtj.hibernate3.AbstractValueTypeUserTypeTest.java

@Test
public void shouldSerializeWithoutComplaint() {
    UserType ut1 = this.newUserTypeInstance();
    UserType ut2 = (UserType) SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) ut1));
    assertEquals(ut2.returnedClass(), ut1.returnedClass());
}

From source file:org.codekaizen.vtj.text.BpDateFormatTest.java

/**
 * DOCUMENT ME!/*from   w  ww . j a  v  a2 s. c om*/
 *
 * @throws  Exception  DOCUMENT ME!
 */
public void testSerialization() throws Exception {
    BpDateFormat fmt1 = null;
    BpDateFormat fmt2 = null;
    fmt1 = new BpDateFormat(BpDateFormat.ISO_DATE_TIME, null);
    fmt2 = (BpDateFormat) SerializationUtils.deserialize(SerializationUtils.serialize(fmt1));
    assertEquals(fmt1, fmt2);
}

From source file:org.codekaizen.vtj.text.BpNumberFormatTest.java

/**
 * DOCUMENT ME!// w ww  .  j  ava  2  s  . c o m
 *
 * @throws  Exception  DOCUMENT ME!
 */
@Test
public void testSerialization() throws Exception {
    BpNumberFormat fmt1 = null;
    BpNumberFormat fmt2 = null;

    fmt1 = new BpNumberFormat(BpNumberFormat.JVM_CURRENCY, null);
    fmt2 = (BpNumberFormat) SerializationUtils.deserialize(SerializationUtils.serialize(fmt1));
    assertEquals(fmt1, fmt2);

}