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:com.avego.oauth.migration.OauthDataMigrator.java

/**
 * This migrates the oauth access tokens
 * @throws IOException If an IO error occurs such as when serializing/deserializing data
 * @throws ClassNotFoundException If a class not found when serializing/deserializing data
 * @throws InvocationTargetException If an invocation target exception occurs when using reflection to convert to the new objects
 * @throws IllegalAccessException If an IllegalAccessException exception occurs when using reflection to convert to the new objects
 * @throws NoSuchMethodException If a NoSuchMethodException exception occurs when using reflection to convert to the new objects
 * @throws InstantiationException/*from   ww  w. j a v  a  2s. c o m*/
 * @throws IllegalArgumentException
 */
@SuppressWarnings("unchecked")
protected void migrateAccessTokens() throws IOException, ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, IllegalArgumentException, InstantiationException {

    int numTokens = this.dao.countUnmigratedAccessTokens();
    int pageSize = PAGE_SIZE;

    int numMigrated = 0;
    System.out.println("Starting Migrating " + numTokens + " access token(s) ...");

    while (numTokens > 0) {

        List<OauthAccessTokenRecord> accessTokens = this.dao.getUnmigratedOauthAccessTokenRecords(pageSize);

        for (OauthAccessTokenRecord tokenRecord : accessTokens) {

            String oldTokenId = tokenRecord.getTokenId();
            System.out.println("Migrating token with id: " + oldTokenId + "...");

            String newTokenId = this.dao.generateNewTokenKey(tokenRecord.getTokenId());
            String newRefreshToken = this.dao.generateNewTokenKey(tokenRecord.getRefreshToken());

            if (this.removeRefreshTokens) {
                newRefreshToken = null;
            }

            System.out.println("New token id: " + newTokenId);
            System.out.println("New refresh token id: " + newRefreshToken);

            // deserialize the token, note this is backward compatible
            OAuth2AccessToken accessToken = null;
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(tokenRecord.getToken()));
            try {
                Object obj = ois.readObject();
                accessToken = (OAuth2AccessToken) obj;
            } finally {
                ois.close();
            }

            // replace the token value in the access token..
            if (this.serializeNewTokenValues) {

                Constructor<OAuth2AccessToken> constructor = null;

                // see if it has a set value method
                Method setValueMethod = MethodUtils.getAccessibleMethod(accessToken.getClass(), "setValue",
                        String.class);
                if (setValueMethod != null) {
                    Object res = setValueMethod.invoke(accessToken, newTokenId);
                    if (res != null && res instanceof OAuth2AccessToken) {
                        accessToken = (OAuth2AccessToken) res;
                    }
                } else {

                    // look for constructors that we can use
                    constructor = (Constructor<OAuth2AccessToken>) ConstructorUtils
                            .getAccessibleConstructor(accessToken.getClass(), String.class);
                    if (constructor != null) {

                        OAuth2AccessToken newAccessToken = constructor.newInstance(newTokenId);

                        // we also need to invoke setters for other fields
                        MethodUtils.invokeMethod(newAccessToken, "setAdditionalInformation",
                                accessToken.getAdditionalInformation());
                        MethodUtils.invokeMethod(newAccessToken, "setExpiration", accessToken.getExpiration());
                        MethodUtils.invokeMethod(newAccessToken, "setScope", accessToken.getScope());
                        MethodUtils.invokeMethod(newAccessToken, "setTokenType", accessToken.getTokenType());

                        accessToken = newAccessToken;

                    } else {
                        throw new IllegalStateException("The access token with the class: "
                                + accessToken.getClass().getName()
                                + " did not have a set value method nor a constructor taking a string which we need to update its token value");
                    }

                }

                // we also need to overwrite the refresh token
                String newRefreshTokenValue = this.dao
                        .generateNewTokenKey(accessToken.getRefreshToken().getValue());
                OAuth2RefreshToken refreshToken = replaceOAuth2RefreshTokenValue(accessToken.getRefreshToken(),
                        newRefreshTokenValue);
                MethodUtils.invokeMethod(accessToken, "setRefreshToken", refreshToken);
            }

            if (this.removeRefreshTokens) {
                MethodUtils.invokeMethod(accessToken, "setRefreshToken", new Object[] { null },
                        new Class<?>[] { OAuth2RefreshToken.class });
            }

            byte[] tokenData = SerializationUtils.serialize((Serializable) accessToken);

            // deserialise the authenticated, this is NOT backward compatible so we have to read using a diff class loader
            OAuth2Authentication auth = deserializeOAuth2Authentication(tokenRecord.getAuthentication());
            byte[] authData = SerializationUtils.serialize(auth);

            // this does the actual migration of the token
            this.dao.updateOauthAccessToken(oldTokenId, newTokenId, newRefreshToken, tokenData, authData);

            System.out.println("Migrated token with id: " + oldTokenId);
            numMigrated++;
            System.out.println("");
        }
        numTokens = this.dao.countUnmigratedAccessTokens();
    }

    System.out.println("Finished Migrating " + numMigrated + " access token(s).");

}

From source file:com.splicemachine.derby.impl.sql.execute.operations.scanner.TableScannerBuilder.java

public String getTableScannerBuilderBase64String() throws IOException, StandardException {
    return Base64.encodeBase64String(SerializationUtils.serialize(this));
}

From source file:com.avego.oauth.migration.OauthDataMigrator.java

/**
 * This migrates the oauth refresh tokens
 * @throws IOException If an IO error occurs such as when serializing/deserializing data
 * @throws ClassNotFoundException If a class not found when serializing/deserializing data
 * @throws InvocationTargetException If an invocation target exception occurs when using reflection to convert to the new objects
 * @throws IllegalAccessException If an IllegalAccessException exception occurs when using reflection to convert to the new objects
 * @throws NoSuchMethodException If a NoSuchMethodException exception occurs when using reflection to convert to the new objects
 * @throws InstantiationException//from   ww w. j a  v a  2s . co  m
 * @throws IllegalArgumentException
 */
protected void migrateRefreshTokens() throws IOException, ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, IllegalArgumentException, InstantiationException {

    int numTokens = this.dao.countUnmigratedRefreshTokens();

    if (this.removeRefreshTokens) {
        System.out.println("Clearing " + numTokens + " refresh token(s)...");
        this.dao.clearRefreshTokens();
        System.out.println("Finished clearing refresh token(s).");
    } else {

        int pageSize = PAGE_SIZE;

        int numMigrated = 0;
        System.out.println("Starting Migrating " + numTokens + " refresh token(s) ...");

        while (numTokens > 0) {

            List<OauthRefreshTokenRecord> refreshTokens = this.dao
                    .getUnmigratedOauthRefreshTokenRecords(pageSize);

            for (OauthRefreshTokenRecord tokenRecord : refreshTokens) {

                String oldTokenId = tokenRecord.getTokenId();

                System.out.println("Migrating token with id: " + oldTokenId + "...");

                String newTokenId = this.dao.generateNewTokenKey(tokenRecord.getTokenId());

                System.out.println("New token id: " + newTokenId);

                // deserialize the token, note this is backward compatible
                OAuth2RefreshToken refreshToken = null;
                ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(tokenRecord.getToken()));
                try {
                    Object obj = ois.readObject();
                    refreshToken = (OAuth2RefreshToken) obj;
                } finally {
                    ois.close();
                }

                // replace the token value in the refresh token..
                if (this.serializeNewTokenValues) {
                    refreshToken = replaceOAuth2RefreshTokenValue(refreshToken, newTokenId);
                }

                byte[] tokenData = SerializationUtils.serialize((Serializable) refreshToken);

                // deserialise the authenticated, this is NOT backward compatible so we have to read using a diff class loader
                OAuth2Authentication auth = deserializeOAuth2Authentication(tokenRecord.getAuthentication());
                byte[] authData = SerializationUtils.serialize(auth);

                // this does the actual migration of the token
                this.dao.updateOauthRefreshToken(oldTokenId, newTokenId, tokenData, authData);

                System.out.println("Migrated token with id: " + oldTokenId);
                numMigrated++;
                System.out.println("");
            }
            numTokens = this.dao.countUnmigratedRefreshTokens();
        }

        System.out.println("Finished Migrating " + numMigrated + " refresh token(s).");
    }
}

From source file:com.jkoolcloud.tnt4j.utils.Utils.java

/**
 * Serialize a given object into a byte array
 *
 * @param obj/*  w  w w  . ja  v a2s .c  om*/
 *            serializable object
 *
 * @return byte array containing flat object
 */
public static byte[] serialize(Serializable obj) {
    return SerializationUtils.serialize(obj);
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlPageTest.java

/**
 * @throws Exception if the test fails//from   ww w .j av  a  2 s.c o  m
 */
@Test
public void serialization() throws Exception {
    // The document.all and form.elements calls are important because they trigger the creation
    // of HTMLCollections, which have caused serialization problems in the past (see bug 1951047).

    final String content = "<html><body>\n" + "<div id='myId'>Hello there!</div>\n" + "<script>"
            + "  var x = document.all;" + "  window.onload=function(){alert('foo')};"

            // this tests 3103703
            // we don't store the jobs are pending at the moment of serialization
            + "  var aktiv = window.setInterval('foo()', 1000);\n" + "  var i = 0;\n" + "  function foo() {\n"
            + "    i = i + 1;\n" + "    if (i >= 10)\n" + "      window.clearInterval(aktiv);\n" + "  }"
            + "</script>\n" + "<form name='f' id='f'></form>\n"
            + "<script>var y = document.getElementById('f').elements;</script>\n" + "</body></html>";

    // waiting for the alerts creates some more js objects associated with the page
    // this tests 3103703
    final List<String> expectedAlerts = new LinkedList<>();
    expectedAlerts.add("foo");

    final HtmlPage page1 = loadPage(content, expectedAlerts);
    final byte[] bytes = SerializationUtils.serialize(page1);

    final HtmlPage page2 = (HtmlPage) SerializationUtils.deserialize(bytes);

    final Iterator<HtmlElement> iterator1 = page1.getHtmlElementDescendants().iterator();
    final Iterator<HtmlElement> iterator2 = page2.getHtmlElementDescendants().iterator();
    while (iterator1.hasNext()) {
        assertTrue(iterator2.hasNext());
        final HtmlElement element1 = iterator1.next();
        final HtmlElement element2 = iterator2.next();
        assertEquals(element1.getNodeName(), element2.getNodeName());
    }
    assertFalse(iterator2.hasNext());
    assertEquals("Hello there!", page2.getHtmlElementById("myId").getFirstChild().getNodeValue());
}

From source file:network.assist.Serialization.java

/**
 * Convert object to byte array/*w ww.  jav a  2 s  .  c om*/
 * @param obj
 * @return converted byte array
 */
public static byte[] serialize(Object obj) {
    return SerializationUtils.serialize((Serializable) obj);
}

From source file:network.UDPServer.java

public void sendMessage(Message message, InetAddress remoteAddress, int remotePort) {

    byte tempBuffer[] = SerializationUtils.serialize(message);
    final DatagramPacket sendPacket = new DatagramPacket(tempBuffer, tempBuffer.length, remoteAddress,
            remotePort);//from ww w . j  a  v  a  2  s  . c om

    executorService.execute(new Runnable() {
        public void run() {
            try {
                //System.out.println("Send UDP message!");
                socket.send(sendPacket);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:org.apache.beam.runners.flink.FlinkPipelineOptionsTest.java

/** Tests that PipelineOptions are present after serialization. */
@Test/*  w  ww . ja va2s .  c  o  m*/
public void parDoBaseClassPipelineOptionsSerializationTest() throws Exception {

    TupleTag<String> mainTag = new TupleTag<>("main-output");

    Coder<WindowedValue<String>> coder = WindowedValue.getValueOnlyCoder(StringUtf8Coder.of());
    DoFnOperator<String, String> doFnOperator = new DoFnOperator<>(new TestDoFn(), "stepName", coder, null,
            Collections.emptyMap(), mainTag, Collections.emptyList(),
            new DoFnOperator.MultiOutputOutputManagerFactory<>(mainTag, coder),
            WindowingStrategy.globalDefault(), new HashMap<>(), Collections.emptyList(), options,
            null, /* key coder */
            null /* key selector */, DoFnSchemaInformation.create());

    final byte[] serialized = SerializationUtils.serialize(doFnOperator);

    @SuppressWarnings("unchecked")
    DoFnOperator<Object, Object> deserialized = SerializationUtils.deserialize(serialized);

    TypeInformation<WindowedValue<Object>> typeInformation = TypeInformation
            .of(new TypeHint<WindowedValue<Object>>() {
            });

    OneInputStreamOperatorTestHarness<WindowedValue<Object>, WindowedValue<Object>> testHarness = new OneInputStreamOperatorTestHarness<>(
            deserialized, typeInformation.createSerializer(new ExecutionConfig()));
    testHarness.open();

    // execute once to access options
    testHarness.processElement(new StreamRecord<>(
            WindowedValue.of(new Object(), Instant.now(), GlobalWindow.INSTANCE, PaneInfo.NO_FIRING)));

    testHarness.close();
}

From source file:org.apache.beam.runners.flink.PipelineOptionsTest.java

/**
 * Tests that PipelineOptions are present after serialization.
 *///w  w w.  ja  va 2  s  .  com
@Test
public void parDoBaseClassPipelineOptionsSerializationTest() throws Exception {

    DoFnOperator<String, String, String> doFnOperator = new DoFnOperator<>(new TestDoFn(), "stepName",
            WindowedValue.getValueOnlyCoder(StringUtf8Coder.of()), new TupleTag<String>("main-output"),
            Collections.<TupleTag<?>>emptyList(), new DoFnOperator.DefaultOutputManagerFactory<String>(),
            WindowingStrategy.globalDefault(), new HashMap<Integer, PCollectionView<?>>(),
            Collections.<PCollectionView<?>>emptyList(), options, null);

    final byte[] serialized = SerializationUtils.serialize(doFnOperator);

    @SuppressWarnings("unchecked")
    DoFnOperator<Object, Object, Object> deserialized = (DoFnOperator<Object, Object, Object>) SerializationUtils
            .deserialize(serialized);

    TypeInformation<WindowedValue<Object>> typeInformation = TypeInformation
            .of(new TypeHint<WindowedValue<Object>>() {
            });

    OneInputStreamOperatorTestHarness<WindowedValue<Object>, Object> testHarness = new OneInputStreamOperatorTestHarness<>(
            deserialized, typeInformation.createSerializer(new ExecutionConfig()));

    testHarness.open();

    // execute once to access options
    testHarness.processElement(new StreamRecord<>(
            WindowedValue.of(new Object(), Instant.now(), GlobalWindow.INSTANCE, PaneInfo.NO_FIRING)));

    testHarness.close();

}

From source file:org.apache.beam.sdk.io.hadoop.SerializableConfigurationTest.java

@Test
public void testSerializationDeserialization() throws Exception {
    Configuration conf = new Configuration();
    conf.set("hadoop.silly.test", "test-value");
    byte[] object = SerializationUtils.serialize(new SerializableConfiguration(conf));
    SerializableConfiguration serConf = SerializationUtils.deserialize(object);
    assertNotNull(serConf);//w  w w. j ava 2  s  . c  o m
    assertEquals(serConf.get().get("hadoop.silly.test"), "test-value");
}