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.kiji.schema.mapreduce.KijiTableInputFormat.java

/**
 * Configures a Hadoop M/R job to read from a given table.
 *
 * @param job Job to configure./*from   w w  w  . jav a  2 s.c om*/
 * @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();
    // As a precaution, be sure the table exists and can be opened.
    final Kiji kiji = Kiji.Factory.open(tableURI, conf);
    final KijiTable table = kiji.openTable(tableURI.getTable());
    ResourceUtils.releaseOrLog(table);
    ResourceUtils.releaseOrLog(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());
}

From source file:org.kiji.scoring.batch.ScoreFunctionJobBuilder.java

/** {@inheritDoc} */
@Override//www.j av  a2s . c o  m
protected void configureJob(final Job job) throws IOException {
    if (null == mScoreFunctionClass) {
        throw new JobConfigurationException("Must specify a ScoreFunction class.");
    }
    if (null == mClientDataRequest) {
        mClientDataRequest = DEFAULT_CLIENT_REQUEST;
    }
    if (null == mAttachedColumn) {
        throw new JobConfigurationException("Must specified an AttachedColumn.");
    }
    if (null == mParameters) {
        mParameters = DEFAULT_PARAMETERS;
    }

    final Configuration conf = job.getConfiguration();
    conf.setClass(SCORE_FUNCTION_CLASS_CONF_KEY, mScoreFunctionClass, ScoreFunction.class);
    if (!getInputTableURI().equals(mJobOutput.getOutputTableURI())) {
        throw new JobConfigurationException(
                String.format("Output table must be the same as the input" + "table. Got input: %s output: %s",
                        getInputTableURI(), mJobOutput.getOutputTableURI()));
    }
    conf.set(SCORE_FUNCTION_ATTACHED_COLUMN_CONF_KEY, mAttachedColumn.getName());
    conf.set(SCORE_FUNCTION_PARAMETERS_CONF_KEY, GSON.toJson(mParameters, Map.class));
    conf.set(SCORE_FUNCTION_CLIENT_DATA_REQUEST_CONF_KEY,
            Base64.encodeBase64String(SerializationUtils.serialize(mClientDataRequest)));
    mMapper = new ScoreFunctionMapper();
    mReducer = new IdentityReducer<Object, Object>();
    job.setJobName("Kiji ScoreFunction: " + mScoreFunctionClass.getSimpleName());
    mScoreFunction = ReflectionUtils.newInstance(mScoreFunctionClass, conf);
    final FreshenerContext context = InternalFreshenerContext.create(mClientDataRequest, mAttachedColumn,
            mParameters, Maps.<String, String>newHashMap(),
            KeyValueStoreReaderFactory.create(getRequiredStores()));
    mScoreFunctionDataRequest = mScoreFunction.getDataRequest(context);

    super.configureJob(job);
}

From source file:org.kiji.scoring.lib.server.ScoringServerScoreFunction.java

/**
 * Build the URL from which to retrieve a score by appending the necessary parameters to the base
 * model URL.//from w  w w  . j a  va 2  s.co  m
 *
 * @param modelBaseURL URL of the scoring servlet for this model.
 * @param eid the entity to score.
 * @param clientRequest client's data request which triggered the run of this ScoreFunction.
 * @param params an optional map of per-request parameters to be passed to the server.
 *
 * @return the URL from which to retrieve a score.
 * @throws MalformedURLException in case the URL cannot be created.
 */
private static URL getScoringServerEndpoint(final String modelBaseURL, final EntityId eid,
        final KijiDataRequest clientRequest, final Map<String, String> params) throws MalformedURLException {
    final String base64Request = Base64.encodeBase64URLSafeString(SerializationUtils.serialize(clientRequest));
    final StringBuilder urlStringBuilder;
    try {
        urlStringBuilder = new StringBuilder(String.format("%s?eid=%s&request=%s", modelBaseURL,
                URLEncoder.encode(eid.toShellString(), Charsets.UTF_8.name()), base64Request));
        for (Map.Entry<String, String> entry : params.entrySet()) {
            urlStringBuilder.append(String.format("&fresh.%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"),
                    URLEncoder.encode(entry.getValue(), "UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return new URL(urlStringBuilder.toString());
}

From source file:org.lsc.beans.LscBean.java

public byte[] getDatasetsBytes() {
    return SerializationUtils.serialize((Serializable) datasets);
}

From source file:org.marketcetera.strategy.StrategyTestBase.java

/**
 * Verifies that the event created contains the expected information.
 *
 * @param inActualEvent a <code>LogEvent</code> value containing the event to verify
 * @param inExpectedLevel a <code>Priority</code> value containing the expected priority
 * @param inException a <code>Throwable</code> value containing the expected exception or <code>null</code> for none
 * @param inExpectedMessage an <code>I18NMessage</code> value containing the expected message
 * @param inExpectedParameters a <code>Serializable[]</code> value containing the expected parameters
 *//*from  w w w .java  2s  .  c o  m*/
public static void verifyEvent(LogEvent inActualEvent, LogEventLevel inExpectedLevel, Throwable inException,
        I18NMessage inExpectedMessage, Serializable... inExpectedParameters) throws Exception {
    assertEquals(inExpectedLevel, inActualEvent.getLevel());
    assertEquals(inException, inActualEvent.getException());
    String messageText = inExpectedMessage.getMessageProvider().getText(inExpectedMessage,
            (Object[]) inExpectedParameters);
    assertEquals(messageText, inActualEvent.getMessage());
    // serialize event

    LogEvent serializedEvent = (LogEvent) SerializationUtils
            .deserialize(SerializationUtils.serialize(inActualEvent));
    assertEquals(inExpectedLevel, serializedEvent.getLevel());
    if (inException == null) {
        assertNull(serializedEvent.getException());
    } else {
        assertEquals(inException.getMessage(), serializedEvent.getException().getMessage());
    }
    assertEquals(messageText, serializedEvent.getMessage());
}

From source file:org.marketcetera.util.log.I18NMessageProviderTest.java

@Test
public void deserialization() {
    byte[] serialized = SerializationUtils.serialize(new I18NMessageProvider("nonexistent_prv"));
    try {/*from w w w.j a v  a2s  .  c om*/
        SerializationUtils.deserialize(serialized);
        fail();
    } catch (SerializationException ex) {
        assertEquals(IOException.class, ex.getCause().getClass());
    }
}

From source file:org.marketcetera.util.test.SerializableAssert.java

/**
 * Asserts that the given object serializes correctly, i.e. the
 * deserialized version of the object is equal to the original
 * object. If the assertion does not hold, the {@link
 * AssertionError} thrown starts with the given message, which may
 * be null if no such custom message prefix is desired.
 *
 * @param message The message./* w  w  w .ja va2s  .co  m*/
 * @param o The object.
 */

public static void assertSerializable(String message, Serializable o) {
    String content = null;
    SerializationException cause = null;
    try {
        Object oNew = SerializationUtils.deserialize(SerializationUtils.serialize(o));
        if (ObjectUtils.equals(o, oNew)) {
            return;
        }
        content = "expected object is '" + o + //$NON-NLS-1$
                "' actual is '" + oNew + "'"; //$NON-NLS-1$ //$NON-NLS-2$
    } catch (SerializationException ex) {
        content = "de/serialization failed"; //$NON-NLS-1$
        cause = ex;
    }
    if (message != null) {
        content = message + " " + content; //$NON-NLS-1$
    }
    AssertionError error = new AssertionError(content);
    if (cause != null) {
        error.initCause(cause);
    }
    throw error;
}

From source file:org.marketcetera.util.ws.wrappers.SerWrapper.java

@Override
protected void toMarshalled() {
    try {/* ww w .  j  a v a 2  s  .  co  m*/
        setMarshalledOnly(SerializationUtils.serialize(getRaw()));
        setSerializationException(null);
    } catch (SerializationException ex) {
        setSerializationException(ex);
        Messages.SERIALIZATION_FAILED.warn(this, getSerializationException());
        setMarshalledOnly(null);
    }
}

From source file:org.marketcetera.util.ws.wrappers.WrapperTestBase.java

@SuppressWarnings("unchecked")
protected static <T extends Serializable> T roundTripJava(T object) {
    return (T) SerializationUtils.deserialize(SerializationUtils.serialize(object));
}

From source file:org.marketcetera.util.ws.wrappers.WrapperTestBase.java

protected <T extends Serializable> void serialization(SerWrapper<T> wrapper, SerWrapper<T> copy,
        SerWrapper<T> empty, SerWrapper<T> nullArg, String stringValue, T value, T unserializableValue,
        String category) throws Exception {
    dual(wrapper, copy, empty, nullArg, stringValue, value, SerializationUtils.serialize(value));
    assertNull(wrapper.getSerializationException());
    assertNull(wrapper.getDeserializationException());

    prepareSerWrapperFailure(category);/*from  ww w .j  a  v a  2 s. c  o m*/
    wrapper.setRaw(unserializableValue);
    assertSerWrapperSerFailure(wrapper, category);
    prepareSerWrapperFailure(category);
    wrapper.setMarshalled(ArrayUtils.EMPTY_BYTE_ARRAY);
    assertSerWrapperDeSerFailure(wrapper, category);
}