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.gradle.caching.internal.DefaultBuildCacheHasher.java

@Override
public DefaultBuildCacheHasher putObject(Object value) {
    if (value == null) {
        this.putString("$NULL");
        return this;
    }//from   w w  w . j  a v  a2  s. c om

    if (value.getClass().isArray()) {
        this.putString("Array");
        for (int idx = 0, len = Array.getLength(value); idx < len; idx++) {
            this.putInt(idx);
            this.putObject(Array.get(value, idx));
        }
        return this;
    }

    if (value instanceof Iterable) {
        this.putString("Iterable");
        int idx = 0;
        for (Object elem : (Iterable<?>) value) {
            this.putInt(idx);
            this.putObject(elem);
            idx++;
        }
        return this;
    }

    if (value instanceof Map) {
        this.putString("Map");
        int idx = 0;
        for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            this.putInt(idx);
            this.putObject(entry.getKey());
            this.putObject(entry.getValue());
            idx++;
        }
        return this;
    }

    if (value instanceof Boolean) {
        this.putBoolean((Boolean) value);
    } else if (value instanceof Long) {
        this.putLong((Long) value);
    } else if (value instanceof Integer) {
        this.putInt((Integer) value);
    } else if (value instanceof Short) {
        this.putInt((Short) value);
    } else if (value instanceof Byte) {
        this.putInt((Byte) value);
    } else if (value instanceof Double) {
        this.putDouble((Double) value);
    } else if (value instanceof Float) {
        this.putDouble((Float) value);
    } else if (value instanceof BigInteger) {
        this.putBytes(((BigInteger) value).toByteArray());
    } else if (value instanceof CharSequence) {
        this.putString((CharSequence) value);
    } else if (value instanceof Enum) {
        this.putString(value.getClass().getName());
        this.putString(((Enum) value).name());
    } else {
        byte[] bytes = SerializationUtils.serialize((Serializable) value);
        this.putBytes(bytes);
    }
    return this;
}

From source file:org.gradle.caching.internal.DefaultBuildCacheKeyBuilder.java

public BuildCacheKeyBuilder appendToCacheKey(Object value) {

    if (value == null) {
        this.putString("$NULL");
        return this;
    }//from  w  w w .j  av  a2s .  c  om

    if (value.getClass().isArray()) {
        this.putString("Array");
        for (int idx = 0, len = Array.getLength(value); idx < len; idx++) {
            this.putInt(idx);
            this.appendToCacheKey(Array.get(value, idx));
        }
        return this;
    }

    if (value instanceof Iterable) {
        this.putString("Iterable");
        int idx = 0;
        for (Object elem : (Iterable<?>) value) {
            this.putInt(idx);
            this.appendToCacheKey(elem);
            idx++;
        }
        return this;
    }

    if (value instanceof Map) {
        this.putString("Map");
        int idx = 0;
        for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            this.putInt(idx);
            this.appendToCacheKey(entry.getKey());
            this.appendToCacheKey(entry.getValue());
            idx++;
        }
        return this;
    }

    if (value instanceof Boolean) {
        this.putBoolean((Boolean) value);
    } else if (value instanceof Long) {
        this.putLong((Long) value);
    } else if (value instanceof Integer) {
        this.putInt((Integer) value);
    } else if (value instanceof Short) {
        this.putInt((Short) value);
    } else if (value instanceof Byte) {
        this.putInt((Byte) value);
    } else if (value instanceof Double) {
        this.putDouble((Double) value);
    } else if (value instanceof Float) {
        this.putDouble((Float) value);
    } else if (value instanceof BigInteger) {
        this.putBytes(((BigInteger) value).toByteArray());
    } else if (value instanceof CharSequence) {
        this.putString((CharSequence) value);
    } else if (value instanceof Enum) {
        this.putString(value.getClass().getName());
        this.putString(((Enum) value).name());
    } else {
        byte[] bytes = SerializationUtils.serialize((Serializable) value);
        this.putBytes(bytes);
    }
    return this;
}

From source file:org.hydracache.client.partition.PartitionAwareClient.java

/**
 * @param key//from w  w  w  . ja v a2s.c om
 * @param data
 * @return
 * @throws IOException
 */
private Buffer serializeData(String key, Serializable data) throws IOException {
    DataMessage dataMessage = new DataMessage();
    dataMessage.setBlob(SerializationUtils.serialize(data));
    Version version = versionMap.get(key);

    if (version == null)
        version = versionFactory.createNull();

    dataMessage.setVersion(version);

    Buffer buffer = Buffer.allocate();
    protocolEncoder.encode(dataMessage, buffer.asDataOutpuStream());
    return buffer;
}

From source file:org.jasig.cas.adaptors.ldap.services.DefaultLdapServiceMapper.java

@Override
public LdapEntry mapFromRegisteredService(final String dn, final RegisteredService svc) {

    if (svc.getId() == RegisteredService.INITIAL_IDENTIFIER_VALUE) {
        ((AbstractRegisteredService) svc).setId(System.nanoTime());
    }//from  w w w .ja  v  a 2  s  . c o  m
    final String newDn = getDnForRegisteredService(dn, svc);
    LOGGER.debug("Creating entry {}", newDn);

    final Collection<LdapAttribute> attrs = new ArrayList<LdapAttribute>();
    attrs.add(new LdapAttribute(this.idAttribute, String.valueOf(svc.getId())));
    attrs.add(new LdapAttribute(this.serviceIdAttribute, svc.getServiceId()));
    attrs.add(new LdapAttribute(this.serviceNameAttribute, svc.getName()));
    attrs.add(new LdapAttribute(this.serviceDescriptionAttribute, svc.getDescription()));
    attrs.add(new LdapAttribute(this.serviceEnabledAttribute, Boolean.toString(svc.isEnabled()).toUpperCase()));
    attrs.add(new LdapAttribute(this.serviceAnonymousAccessAttribute,
            Boolean.toString(svc.isAnonymousAccess()).toUpperCase()));
    attrs.add(new LdapAttribute(this.serviceSsoEnabledAttribute,
            Boolean.toString(svc.isSsoEnabled()).toUpperCase()));
    attrs.add(new LdapAttribute(this.evaluationOrderAttribute, String.valueOf(svc.getEvaluationOrder())));
    attrs.add(new LdapAttribute(this.serviceThemeAttribute, svc.getTheme()));
    attrs.add(new LdapAttribute(this.usernameAttribute, svc.getUsernameAttribute()));

    if (svc.getProxyPolicy() != null) {
        final byte[] data = SerializationUtils.serialize(svc.getProxyPolicy());
        final LdapAttribute attr = new LdapAttribute(this.serviceProxyPolicyAttribute, data);
        attrs.add(attr);
    }
    if (svc.getAttributeReleasePolicy() != null) {
        final byte[] data = SerializationUtils.serialize(svc.getAttributeReleasePolicy());
        final LdapAttribute attr = new LdapAttribute(this.attributeReleasePolicyAttribute, data);
        attrs.add(attr);
    }

    if (svc.getRequiredHandlers().size() > 0) {
        attrs.add(new LdapAttribute(this.requiredHandlersAttribute,
                svc.getRequiredHandlers().toArray(new String[] {})));
    }

    attrs.add(new LdapAttribute(LdapUtils.OBJECTCLASS_ATTRIBUTE, this.objectClass));

    return new LdapEntry(newDn, attrs);
}

From source file:org.jasypt.properties.EncryptablePropertiesTest.java

public void testEncryptablePropertiesSerialization() throws Exception {

    final BasicTextEncryptor enc01 = new BasicTextEncryptor();
    enc01.setPassword("jasypt");

    final String msg01 = "Message one";
    final String msgEnc01 = "ENC(eZpONwIfFb5muu5Dc8ABsTPu/0OP95p4)";

    final String msg02 = "Message two";
    final String msgEnc02 = "ENC(LKyQ65EYz3+ekDPpnLjLGyPK07Gt+UZH)";

    final EncryptableProperties prop01 = new EncryptableProperties(enc01);
    prop01.setProperty("p1", msgEnc01);
    prop01.setProperty("p2", msgEnc02);

    Assert.assertEquals(prop01.getProperty("p1"), msg01);
    Assert.assertEquals(prop01.getProperty("p2"), msg02);

    final byte[] ser01 = SerializationUtils.serialize(prop01);

    final EncryptableProperties prop02 = (EncryptableProperties) SerializationUtils.deserialize(ser01);

    Assert.assertEquals(prop02.getProperty("p1"), msg01);
    Assert.assertEquals(prop02.getProperty("p2"), msg02);

    Assert.assertNotSame(prop01, prop02);

}

From source file:org.jlibrary.core.http.client.HTTPDelegate.java

/**
 * Excecutes a void request// w  ww.  jav a2s . c  om
 * 
 * @param methodName Name of the method to execute
 * @param params Method params
 * @param returnClass Class for the return object. If the class is InputStream this method will return 
 * the HTTP request input stream
 * @param inputStream Stream for reading contents that will be sent
 * 
 * @throws Exception If there is any problem running the request
 */
public Object doRequest(String methodName, Object[] params, Class returnClass, InputStream inputStream)
        throws Exception {

    try {
        logger.debug(servletURL.toString());
        logger.debug("opening connection");
        URLConnection conn = servletURL.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "text/plain");

        //write request and params:
        OutputStream stream = conn.getOutputStream();
        // write streaming header if necessary
        if (inputStream != null) {
            stream.write(ByteUtils.intToByteArray("stream-input".getBytes().length));
            stream.write("stream-input".getBytes());
            stream.flush();
        }
        if (returnClass == InputStream.class) {
            stream.write(ByteUtils.intToByteArray("stream-output".getBytes().length));
            stream.write("stream-output".getBytes());
            stream.flush();
        }

        // Write method
        stream.write(ByteUtils.intToByteArray(methodName.getBytes().length));
        stream.write(methodName.getBytes());
        //stream.flush();
        // Write parameters
        stream.write(ByteUtils.intToByteArray(params.length));
        for (int i = 0; i < params.length; i++) {
            byte[] content = SerializationUtils.serialize((Serializable) params[i]);
            stream.write(ByteUtils.intToByteArray(content.length));
            stream.write(content);
            stream.flush();
        }

        if (inputStream != null) {
            IOUtils.copy(inputStream, stream);
        }

        //stream.flush();
        //stream.close();

        //read response:
        InputStream input = conn.getInputStream();
        if (returnClass == InputStream.class) {
            // Contents will be read from outside
            return input;
        }
        ObjectInputStream objInput = new ObjectInputStream(input);
        Object o = objInput.readObject();
        if (o == null) {
            return null;
        }
        stream.close();
        if (o instanceof Exception) {
            throw (Exception) o;
        } else {
            if (returnClass == null) {
                return null;
            }
            // try to cast
            try {
                returnClass.cast(o);
            } catch (ClassCastException cce) {
                String msg = "Unexpected response from execution servlet: " + o;
                logger.error(msg);
                throw new Exception(msg);
            }
        }
        return o;
    } catch (ClassNotFoundException e) {
        throw new Exception(e);
    } catch (ClassCastException e) {
        throw new Exception(e);
    } catch (IOException e) {
        throw new Exception(e);
    }
}

From source file:org.jvnet.hudson.plugins.collapsingconsolesections.CollapsingSectionAnnotatorTest.java

@Test
@Bug(20304)//from   w  w w  . j a  v  a2s  .  com
public void testSerialization() {
    // Prepare data
    CollapsingSectionsConfiguration config = new CollapsingSectionsConfiguration(
            new CollapsingSectionNote[] { new CollapsingSectionNote("test", "test", "test", true) }, true);
    CollapsingSectionAnnotator annotator = new CollapsingSectionAnnotator(config);

    // Try to serialize
    SerializationUtils.serialize(annotator);
}

From source file:org.kiji.mapreduce.framework.KijiTableInputFormat.java

/**
 * Configures a Hadoop M/R job to read from a given table.
 *
 * @param job Job to configure.//from  w  w w .j  a  v  a  2  s.  c  o  m
 * @param tableURI URI of the table to read from.
 * @param dataRequest Data request.
 * @param startRow Minimum row key to process. May be left null to indicate
 *     that scanning should start at the beginning of the table.
 * @param endRow Maximum row key to process. May be left null to indicate that
 *     scanning should continue to the end of the table.
 * @param filter Filter to use for scanning. May be left null.
 * @throws IOException on I/O error.
 */
public static void configureJob(Job job, KijiURI tableURI, KijiDataRequest dataRequest, EntityId startRow,
        EntityId endRow, KijiRowFilter filter) throws IOException {
    Preconditions.checkNotNull(job, "job must not be null");
    Preconditions.checkNotNull(tableURI, "tableURI must not be null");
    Preconditions.checkNotNull(dataRequest, "dataRequest must not be null");

    final Configuration conf = job.getConfiguration();

    // TODO: Check for jars config:
    // GenericTableMapReduceUtil.initTableInput(hbaseTableName, scan, job);

    // Write all the required values to the job's configuration object.
    final String serializedRequest = Base64.encodeBase64String(SerializationUtils.serialize(dataRequest));
    conf.set(KijiConfKeys.KIJI_INPUT_DATA_REQUEST, serializedRequest);
    conf.set(KijiConfKeys.KIJI_INPUT_TABLE_URI, tableURI.toString());
    if (null != startRow) {
        conf.set(KijiConfKeys.KIJI_START_ROW_KEY, Base64.encodeBase64String(startRow.getHBaseRowKey()));
    }
    if (null != endRow) {
        conf.set(KijiConfKeys.KIJI_LIMIT_ROW_KEY, Base64.encodeBase64String(endRow.getHBaseRowKey()));
    }
    if (null != filter) {
        conf.set(KijiConfKeys.KIJI_ROW_FILTER, filter.toJson().toString());
    }
}

From source file:org.kiji.mapreduce.input.KijiTableMapReduceJobInput.java

/** {@inheritDoc} */
@Override/*  www. jav  a  2 s .  c o  m*/
public void configure(Job job) throws IOException {
    // Configure the input format class.
    super.configure(job);

    // Get the name of the HBase table that stores the Kiji table data.
    String hbaseTableName = KijiManagedHBaseTableName
            .getKijiTableName(mInputTable.getKiji().getName(), mInputTable.getName()).toString();

    // Create the HBase scan configured to read the appropriate input from the Kiji table.
    Scan configuredScan = createConfiguredScan(mInputTable.getLayout());

    // Configure the table input using HBase.
    GenericTableMapReduceUtil.initTableInput(hbaseTableName, configuredScan, job);

    final Configuration conf = job.getConfiguration();

    final String serializedRequest = Base64.encodeBase64String(SerializationUtils.serialize(mDataRequest));
    conf.set(KijiConfKeys.INPUT_DATA_REQUEST, serializedRequest);

    final Kiji kiji = mInputTable.getKiji();
    // TODO(KIJI-144): Move this to KijiTable.getTableURI()
    conf.set(KijiConfKeys.INPUT_TABLE_URI,
            String.format(
                    "kiji://%s:%s/%s/%s", kiji.getConf().get(HConstants.ZOOKEEPER_QUORUM), kiji.getConf()
                            .getInt(HConstants.ZOOKEEPER_CLIENT_PORT, HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT),
                    kiji.getName(), mInputTable.getName()));
}

From source file:org.kiji.mapreduce.KijiTableInputFormat.java

/**
 * Configures a Hadoop M/R job to read from a given table.
 *
 * @param job Job to configure.//from w  ww .  j  a  va  2s. c  o m
 * @param tableURI URI of the table to read from.
 * @param dataRequest Data request.
 * @param startRow Minimum row key to process.
 * @param endRow Maximum row Key to process.
 * @throws IOException on I/O error.
 */
public static void configureJob(Job job, KijiURI tableURI, KijiDataRequest dataRequest, String startRow,
        String endRow) throws IOException {

    final Configuration conf = job.getConfiguration();
    final Kiji kiji = Kiji.open(tableURI, conf);
    final KijiTable table = kiji.openTable(tableURI.getTable());
    IOUtils.closeQuietly(table);
    IOUtils.closeQuietly(kiji);

    // TODO: Check for jars config:
    // GenericTableMapReduceUtil.initTableInput(hbaseTableName, scan, job);

    // TODO: Obey specified start/end rows.

    // Write all the required values to the job's configuration object.
    job.setInputFormatClass(KijiTableInputFormat.class);
    final String serializedRequest = Base64.encodeBase64String(SerializationUtils.serialize(dataRequest));
    conf.set(KijiConfKeys.INPUT_DATA_REQUEST, serializedRequest);
    conf.set(KijiConfKeys.INPUT_TABLE_URI, tableURI.toString());
}