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:com.dalendev.meteotndata.servlet.UpdateStationDataServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww  w. j a  va  2 s .c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream inputStream = request.getInputStream();
    ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();

    int length;
    byte[] buffer = new byte[1024];
    while ((length = inputStream.read(buffer)) >= 0) {
        byteArrayStream.write(buffer, 0, length);
    }

    if (byteArrayStream.size() > 0) {
        Station station = SerializationUtils.deserialize(byteArrayStream.toByteArray());
        Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO, station.getCode());

        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance(MeasurementList.class);
            Unmarshaller u = jc.createUnmarshaller();
            URL url = new URL(
                    "http://dati.meteotrentino.it/service.asmx/ultimiDatiStazione?codice=" + station.getCode());
            StreamSource src = new StreamSource(url.openStream());
            JAXBElement je = u.unmarshal(src, MeasurementList.class);
            MeasurementList measurementList = (MeasurementList) je.getValue();

            MeasurmentSamplerService mss = new MeasurmentSamplerService();
            mss.mergeMeasurment(station, measurementList);
            List<Measurement> sampledList = mss.getSampledMeasurementList();
            MeasurementDAO.storeStation(sampledList);

            if (sampledList.size() > 0) {
                Measurement lastMeasurement = sampledList.get(sampledList.size() - 1);
                station.setLastUpdate(lastMeasurement.getTimestamp());
                StationDAO.storeStation(station);
            }

            Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO,
                    "Station {0} has {1} new measurements",
                    new Object[] { station.getCode(), sampledList.size() });
        } catch (JAXBException ex) {
            Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        response.setStatus(200);
    } else {
        Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO,
                "Cannot retrieve Station's serialization");
    }
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle arguments = getArguments();// ww  w  .  j av  a 2  s.  c  om

    if (arguments == null) {
        throw new IllegalArgumentException("arguments is not set");
    }

    mConsumerKey = arguments.getString("consumerKey");
    mConsumerSecret = arguments.getString("consumerSecret");
    if (TextUtils.isEmpty(mConsumerKey) || TextUtils.isEmpty(mConsumerSecret)) {
        throw new IllegalArgumentException("both consumerKey and consumerSecret is required");
    }

    SharedPreferences preferences = getActivity().getSharedPreferences("twitter", Activity.MODE_PRIVATE);
    if (preferences.contains("access_token_str")) {
        String ats = preferences.getString("access_token_str", "");
        if (!TextUtils.isEmpty(ats)) {
            byte[] decode = Base64.decode(ats, Base64.DEFAULT);
            mAccessToken = SerializationUtils.deserialize(decode);
        }
    }

}

From source file:com.mirth.connect.connectors.tests.ConnectorTests.java

@Test
public final void testJavaScriptWriter() throws Exception {
    final String script = "globalMap.put('message' + connectorMessage.getMessageId(), connectorMessage.getEncoded().getContent() + '123');";

    JavaScriptDispatcherProperties connectorProperties = new JavaScriptDispatcherProperties();
    connectorProperties.setScript(script);

    JavaScriptDispatcher javaScriptWriter = new JavaScriptDispatcher();
    javaScriptWriter.setConnectorProperties(connectorProperties);

    ChannelController.getInstance().deleteAllMessages(TestUtils.CHANNEL_ID);

    DummyChannel channel = new DummyChannel(TestUtils.CHANNEL_ID, TestUtils.SERVER_ID, null, javaScriptWriter);
    channel.start(null);/*www  . jav a 2  s.c om*/

    DonkeyDao dao = Donkey.getInstance().getDaoFactory().getDao();

    for (int i = 0; i < TEST_SIZE; i++) {
        ConnectorMessage sourceMessage = TestUtils
                .createAndStoreNewMessage(new RawMessage(TestUtils.TEST_HL7_MESSAGE), channel.getChannelId(),
                        channel.getName(), channel.getServerId(), dao)
                .getConnectorMessages().get(0);
        dao.commit();

        Message message = channel.process(sourceMessage, true);
        connectorProperties = (JavaScriptDispatcherProperties) SerializationUtils
                .deserialize(message.getConnectorMessages().get(1).getSent().getContent().getBytes());

        assertEquals(TestUtils.TEST_HL7_MESSAGE + "123",
                GlobalVariableStore.getInstance().getVariables().get("message" + message.getMessageId()));
    }

    channel.stop();
    dao.close();
}

From source file:com.uber.hoodie.common.util.collection.converter.HoodieRecordConverter.java

@Override
public HoodieRecord getData(byte[] bytes) {
    try {//from  w  ww.  j  a  v  a2s .  com
        Triple<Pair<String, String>, Pair<byte[], byte[]>, byte[]> data = SerializationUtils.deserialize(bytes);
        Optional<GenericRecord> payload = Optional.empty();
        HoodieRecordLocation currentLocation = null;
        HoodieRecordLocation newLocation = null;
        if (data.getRight().length > 0) {
            // This can happen if the record is deleted, the payload is optional with 0 bytes
            payload = Optional.of(HoodieAvroUtils.bytesToAvro(data.getRight(), schema));
        }
        // Get the currentLocation for the HoodieRecord
        if (data.getMiddle().getLeft().length > 0) {
            currentLocation = SerializationUtils.deserialize(data.getMiddle().getLeft());
        }
        // Get the newLocation for the HoodieRecord
        if (data.getMiddle().getRight().length > 0) {
            newLocation = SerializationUtils.deserialize(data.getMiddle().getRight());
        }
        HoodieRecord<? extends HoodieRecordPayload> hoodieRecord = new HoodieRecord<>(
                new HoodieKey(data.getLeft().getKey(), data.getLeft().getValue()),
                ReflectionUtils.loadPayload(payloadClazz, new Object[] { payload }, Optional.class));
        hoodieRecord.setCurrentLocation(currentLocation);
        hoodieRecord.setNewLocation(newLocation);
        return hoodieRecord;
    } catch (IOException io) {
        throw new HoodieNotSerializableException("Cannot de-serialize value from bytes", io);
    }
}

From source file:at.jps.sanction.model.queue.file.FileQueue.java

@Override
public X getNextMessage(final boolean wait) {
    X message = null;//from w w w.  ja  va2 s. c om
    try {
        if (wait) {
            while (isEmpty()) {
                Thread.sleep(100);
            }
        }
        // } else {
        // message = getQueue().remove();
        if (!isEmpty()) {
            final byte[] object = getQueue().dequeue();
            if (object != null) {
                message = SerializationUtils.deserialize(object);
            }
        }
        super.getNextMessage(wait);
    } catch (final Exception x) {
        logger.error(getName() + ": Message retrieve Error: " + x.toString());
        logger.debug("Exception: ", x);
    }
    return message;
}

From source file:com.sangupta.shire.util.WebResponseCacheInterceptor.java

/**
 * Get {@link WebResponse} as previously saved from the cache dir, if
 * available/*from   w w w  . j  av  a 2s  .  co  m*/
 * 
 * @param url
 *            the URL that needs to be hit
 * 
 * @return the response as available
 */
private WebResponse getFromCache(String url) {
    File cache = getCacheFile(url);
    if (cache == null || !cache.exists()) {
        return null;
    }

    try {
        WebResponse response = (WebResponse) SerializationUtils
                .deserialize(FileUtils.readFileToByteArray(cache));
        return response;
    } catch (IOException e) {
        // eat up
    }

    return null;
}

From source file:hr.caellian.m3l.util.nbt.NbtSerializable.java

/**
 * This method deserializes stored object and returns it.
 *
 * @return Object version of serialized data.
 *///from  w  w w  .  ja  v  a2  s. c om
@SuppressWarnings("unchecked")
public Object getObject() {
    return SerializationUtils.deserialize(this.getDataValue());
}

From source file:com.omertron.themoviedbapi.AbstractTests.java

/**
 * Read the object back from a file//ww w.j a  va  2  s  . c  om
 *
 * @param <T>
 * @param filename
 * @return
 */
private static <T> T readObject(final String baseFilename) {
    String filename = baseFilename + FILENAME_EXT;
    File serFile = new File(filename);

    if (serFile.exists()) {
        long diff = System.currentTimeMillis() - serFile.lastModified();
        if (diff < TimeUnit.HOURS.toMillis(1)) {
            LOG.info("File '{}' is current, no need to reacquire", filename);
        } else {
            LOG.info("File '{}' is too old, re-acquiring", filename);
            return null;
        }
    } else {
        LOG.info("File '{}' doesn't exist", filename);
        return null;
    }

    LOG.info("Reading object from '{}'", filename);
    try {
        byte[] serObject = FileUtils.readFileToByteArray(serFile);
        return (T) SerializationUtils.deserialize(serObject);
    } catch (IOException ex) {
        LOG.info("Failed to read {}: {}", filename, ex.getMessage(), ex);
        return null;
    }
}

From source file:example.RepoContract.java

public static RepoContract toRepoObj(byte[] byteArr) {
    return (RepoContract) SerializationUtils.deserialize(byteArr);
}

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

/**
 * Test of terms method, of class Terms.
 * @throws java.io.IOException// www.  ja va2  s. c om
 * @throws java.io.FileNotFoundException
 * @throws java.lang.ClassNotFoundException
 */
@Test
public void testTerms() throws IOException, FileNotFoundException, ClassNotFoundException {
    TermsTest.resetTs();
    System.out.println("Terms.terms");
    Terms instance = TermsTest.ts;
    File file = new File("resources/test/testTermsResults.bin");
    byte[] v = FileUtils.readFileToByteArray(file);
    ArrayList<String> expResult = SerializationUtils.deserialize(v);
    ArrayList<Term> result = instance.terms();
    Iterator iter = result.iterator();
    ArrayList<String> lemas = new ArrayList<>();
    while (iter.hasNext()) {
        Term next = (Term) iter.next();
        lemas.add(next.getLema());
    }
    Object[] lemas1 = lemas.toArray();
    Object[] exp = expResult.toArray();
    java.util.Arrays.sort(lemas1);
    java.util.Arrays.sort(exp);
    //Out.p(lemas1);
    //Out.p(exp);
    Assert.assertArrayEquals(exp, lemas1);

}