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.thingsboard.server.service.cluster.discovery.ZkDiscoveryService.java

@Override
public synchronized void publishCurrentServer() {
    ServerInstance self = this.serverInstance.getSelf();
    if (currentServerExists()) {
        log.info("[{}:{}] ZK node for current instance already exists, NOT created new one: {}", self.getHost(),
                self.getPort(), nodePath);
    } else {/*from   ww  w .jav  a  2 s  .  co  m*/
        try {
            log.info("[{}:{}] Creating ZK node for current instance", self.getHost(), self.getPort());
            nodePath = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                    .forPath(zkNodesDir + "/", SerializationUtils.serialize(self.getServerAddress()));
            log.info("[{}:{}] Created ZK node for current instance: {}", self.getHost(), self.getPort(),
                    nodePath);
            client.getConnectionStateListenable().addListener(checkReconnect(self));
        } catch (Exception e) {
            log.error("Failed to create ZK node", e);
            throw new RuntimeException(e);
        }
    }
}

From source file:org.wso2.carbon.identity.application.authentication.framework.handler.sequence.impl.GraphBasedSequenceHandlerCustomFunctionsTest.java

@Test
public void testHandleDynamicJavascriptSerialization() throws Exception {

    JsFunctionRegistry jsFunctionRegistrar = new JsFunctionRegistryImpl();
    FrameworkServiceDataHolder.getInstance().setJsFunctionRegistry(jsFunctionRegistrar);
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "fn1",
            (Function<JsAuthenticationContext, String>) GraphBasedSequenceHandlerCustomFunctionsTest::customFunction1);

    ServiceProvider sp1 = getTestServiceProvider("js-sp-dynamic-1.xml");

    AuthenticationContext context = getAuthenticationContext(sp1);

    SequenceConfig sequenceConfig = configurationLoader.getSequenceConfig(context,
            Collections.<String, String[]>emptyMap(), sp1);
    context.setSequenceConfig(sequenceConfig);

    byte[] serialized = SerializationUtils.serialize(context);

    AuthenticationContext deseralizedContext = (AuthenticationContext) SerializationUtils
            .deserialize(serialized);//from w  w  w.ja  va  2  s .  co m
    assertNotNull(deseralizedContext);

    HttpServletRequest req = mock(HttpServletRequest.class);
    addMockAttributes(req);

    HttpServletResponse resp = mock(HttpServletResponse.class);

    UserCoreUtil.setDomainInThreadLocal("test_domain");

    graphBasedSequenceHandler.handle(req, resp, deseralizedContext);

    List<AuthHistory> authHistories = deseralizedContext.getAuthenticationStepHistory();
    assertNotNull(authHistories);
    assertEquals(3, authHistories.size());
    assertEquals(authHistories.get(0).getAuthenticatorName(), "BasicMockAuthenticator");
    assertEquals(authHistories.get(1).getAuthenticatorName(), "HwkMockAuthenticator");
    assertEquals(authHistories.get(2).getAuthenticatorName(), "FptMockAuthenticator");
}

From source file:protocole.Request.java

@SuppressWarnings("empty-statement")
public static byte[] marshall(Request requete) {
    // TODO Auto-generated method stub
    return SerializationUtils.serialize((Serializable) requete);
}

From source file:pt.ieeta.jlay.jlay.agent.DataStream.java

public void sendData(Serializable message) {
    String url = GlobalSettings.getHTTPServerRootURL() + "receiveMessage";
    URL obj = null;/*  w  w  w. j  av  a2 s.  c o  m*/
    try {
        obj = new URL(url);

        //HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + MULTIPART_BOUNDARY);
        con.setRequestProperty("charset", "utf-8");

        String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
        con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());

        byte[] data = SerializationUtils.serialize(message);

        wr.write(data);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());
    } catch (Exception ex) {
        Logger.getLogger(DataStream.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:uk.org.lidalia.sysoutslf4j.integration.CrossClassLoaderTestUtils.java

private static Object moveToCurrentClassLoaderViaSerialization(Serializable objectFromOtherClassLoader) {
    try {//from w ww. j av  a 2  s .co  m
        byte[] objectAsBytes = SerializationUtils.serialize(objectFromOtherClassLoader);
        return SerializationUtils.deserialize(objectAsBytes);
    } catch (Exception e) {
        Exceptions.throwUnchecked(e);
        throw new AssertionError("Unreachable");
    }
}

From source file:uk.q3c.krail.core.guice.uiscope.UIScope.java

/**
 * Writes out the cache by using {@link GuiceKeyProxy} to replace {@link Key}.  It also
 *
 * @param out/*  w  w w.  ja  v  a 2 s . c o m*/
 * @throws IOException
 */
private void writeObject(ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();
    Map<UIKey, Map<GuiceKeyProxy, Serializable>> proxyMap = new HashMap<>();
    for (Map.Entry<UIKey, Map<Key<?>, Object>> entry : cache.entrySet()) {
        Map<GuiceKeyProxy, Serializable> targetDetail = new HashMap<>();
        proxyMap.put(entry.getKey(), targetDetail);
        Map<Key<?>, Object> sourceDetail = entry.getValue();
        for (Map.Entry<Key<?>, Object> detailEntry : sourceDetail.entrySet()) {
            GuiceKeyProxy proxy = new GuiceKeyProxy(detailEntry.getKey());
            Object detailValue = detailEntry.getValue();
            if (Serializable.class.isAssignableFrom(detailValue.getClass())) {
                byte[] serValue = SerializationUtils.serialize(detailValue.getClass());
                targetDetail.put(proxy, serValue);
            } else {
                targetDetail.put(proxy, proxy);
            }

        }
    }
    out.writeObject(proxyMap);
}