Example usage for org.apache.commons.lang SerializationUtils clone

List of usage examples for org.apache.commons.lang SerializationUtils clone

Introduction

In this page you can find the example usage for org.apache.commons.lang SerializationUtils clone.

Prototype

public static Object clone(Serializable object) 

Source Link

Document

Deep clone an Object using serialization.

This is many times slower than writing clone methods by hand on all objects in your object graph.

Usage

From source file:com.gemstone.gemfire.test.junit.rules.serializable.SerializableTemporaryFolderTest.java

@Test
public void canBeSerialized() throws Exception {
    File parentFolder = this.temporaryFolder.getRoot();

    SerializableTemporaryFolder instance = new SerializableTemporaryFolder(parentFolder);
    instance.create();/*from ww w  . ja  va 2s.c om*/

    SerializableTemporaryFolder cloned = (SerializableTemporaryFolder) SerializationUtils.clone(instance);

    assertThat(readField(TemporaryFolder.class, cloned, FIELD_PARENT_FOLDER)).isEqualTo(parentFolder);
    assertThat(readField(TemporaryFolder.class, cloned, FIELD_FOLDER)).isEqualTo(cloned.getRoot());
}

From source file:com.googlecode.concurrentlinkedhashmap.IsReserializable.java

@SuppressWarnings("unchecked")
private T reserialize(T object) {
    return (T) SerializationUtils.clone((Serializable) object);
}

From source file:com.google.code.simplestuff.bean.SimpleBeanTest.java

@Before
public void setUp() throws Exception {

    testObjectOne = new ParentClass();
    testObjectOne.setBooleanField(true);
    testObjectOne.setBooleanPrimitiveField(true);
    testObjectOne.setStringField("Test String");
    testObjectOne.setStringArrayField(new String[] { "One", "Two", "Three" });
    testObjectOne.setDateField(new Date());
    testObjectOne.setChilds(new HashSet<ChildClass>());
    testObjectOne.getChilds().add(new ChildClass("Child One String field", testObjectOne));
    testObjectOne.getChilds().add(new ChildClass("Child Two String field", testObjectOne));

    ArrayList<ParentEnum> enums = new ArrayList<ParentEnum>();
    enums.add(ParentEnum.ONE);/* w ww  .j a va 2 s .  c  o  m*/
    enums.add(ParentEnum.THREE);
    testObjectOne.setEnums(enums);

    testObjectTwo = (ParentClass) SerializationUtils.clone(testObjectOne);
}

From source file:com.gemstone.gemfire.security.GemFireSecurityExceptionTest.java

@Test
public void serializes() throws Exception {
    GemFireSecurityException instance = new GemFireSecurityException(this.message);

    GemFireSecurityException cloned = (GemFireSecurityException) SerializationUtils.clone(instance);

    assertThat(cloned).hasMessage(this.message);
}

From source file:com.evolveum.midpoint.prism.util.CloneUtil.java

public static <T> T clone(T orig) {
    if (orig == null) {
        return null;
    }/*from w ww. ja  va2 s .  c  om*/
    Class<? extends Object> origClass = orig.getClass();
    if (ClassUtils.isPrimitiveOrWrapper(origClass)) {
        return orig;
    }
    if (origClass.isArray()) {
        return cloneArray(orig);
    }
    if (orig instanceof PolyString) {
        // PolyString is immutable
        return orig;
    }
    if (orig instanceof String) {
        // ...and so is String
        return orig;
    }
    if (orig instanceof QName) {
        // the same here
        return orig;
    }
    if (origClass.isEnum()) {
        return orig;
    }
    //        if (orig.getClass().equals(QName.class)) {
    //            QName origQN = (QName) orig;
    //            return (T) new QName(origQN.getNamespaceURI(), origQN.getLocalPart(), origQN.getPrefix());
    //        }
    if (orig instanceof RawType) {
        return (T) ((RawType) orig).clone();
    }
    if (orig instanceof Item<?, ?>) {
        return (T) ((Item<?, ?>) orig).clone();
    }
    if (orig instanceof PrismValue) {
        return (T) ((PrismValue) orig).clone();
    }
    if (orig instanceof ObjectDelta<?>) {
        return (T) ((ObjectDelta<?>) orig).clone();
    }
    if (orig instanceof ObjectDeltaType) {
        return (T) ((ObjectDeltaType) orig).clone();
    }
    if (orig instanceof ItemDelta<?, ?>) {
        return (T) ((ItemDelta<?, ?>) orig).clone();
    }
    if (orig instanceof Definition) {
        return (T) ((Definition) orig).clone();
    }
    /*
     * In some environments we cannot clone XMLGregorianCalendar because of this:
     * Error when cloning class org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl, will try serialization instead.
       * java.lang.IllegalAccessException: Class com.evolveum.midpoint.prism.util.CloneUtil can not access a member of
       * class org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl with modifiers "public"
     */
    if (orig instanceof XMLGregorianCalendar) {
        return (T) XmlTypeConverter.createXMLGregorianCalendar((XMLGregorianCalendar) orig);
    }
    if (orig instanceof Cloneable) {
        T clone = javaLangClone(orig);
        if (clone != null) {
            return clone;
        }
    }
    if (orig instanceof Serializable) {
        // Brute force
        if (PERFORMANCE_ADVISOR.isDebugEnabled()) {
            PERFORMANCE_ADVISOR.debug("Cloning a Serializable ({}). It could harm performance.",
                    orig.getClass());
        }
        return (T) SerializationUtils.clone((Serializable) orig);
    }
    throw new IllegalArgumentException("Cannot clone " + orig + " (" + origClass + ")");
}

From source file:io.cloudslang.lang.runtime.steps.AsyncLoopSteps.java

public void addBranches(
        @Param(ScoreLangConstants.ASYNC_LOOP_STATEMENT_KEY) AsyncLoopStatement asyncLoopStatement,
        @Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv,
        @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices,
        @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName,
        @Param(ExecutionParametersConsts.RUNNING_EXECUTION_PLAN_ID) Long RUNNING_EXECUTION_PLAN_ID,
        @Param(ScoreLangConstants.NEXT_STEP_ID_KEY) Long nextStepId,
        @Param(ScoreLangConstants.BRANCH_BEGIN_STEP_ID_KEY) Long branchBeginStep,
        @Param(ScoreLangConstants.REF_ID) String refId) {

    try {/*from   ww w.  java2 s .  c  o  m*/
        Context flowContext = runEnv.getStack().popContext();

        List<Serializable> splitData = asyncLoopBinding.bindAsyncLoopList(asyncLoopStatement, flowContext,
                nodeName);

        fireEvent(executionRuntimeServices, ScoreLangConstants.EVENT_ASYNC_LOOP_EXPRESSION_END,
                "async loop expression bound", runEnv.getExecutionPath().getCurrentPathPeekForward(),
                Pair.of(LanguageEventData.BOUND_ASYNC_LOOP_EXPRESSION, (Serializable) splitData),
                Pair.of(LanguageEventData.levelName.TASK_NAME.name(), nodeName));

        runEnv.putNextStepPosition(nextStepId);

        for (Serializable splitItem : splitData) {
            RunEnvironment branchRuntimeEnvironment = (RunEnvironment) SerializationUtils.clone(runEnv);
            Context branchContext = (Context) SerializationUtils.clone(flowContext);
            branchContext.putVariable(asyncLoopStatement.getVarName(), splitItem);

            updateCallArgumentsAndPushContextToStack(branchRuntimeEnvironment, branchContext,
                    new HashMap<String, Serializable>());

            createBranch(branchRuntimeEnvironment, executionRuntimeServices, RUNNING_EXECUTION_PLAN_ID, refId,
                    nextStepId, branchBeginStep);

            fireEvent(executionRuntimeServices, ScoreLangConstants.EVENT_BRANCH_START,
                    "async loop branch created", runEnv.getExecutionPath().getCurrentPathPeekForward(),
                    Pair.of(ScoreLangConstants.REF_ID, refId),
                    Pair.of(RuntimeConstants.SPLIT_ITEM_KEY, splitItem),
                    Pair.of(LanguageEventData.levelName.TASK_NAME.name(), nodeName));
        }

        updateCallArgumentsAndPushContextToStack(runEnv, flowContext, new HashMap<String, Serializable>());

        // forward after the branches are created because begin task method also calls forward
        runEnv.getExecutionPath().forward();
    } catch (RuntimeException e) {
        logger.error("There was an error running the add branches execution step of: \'" + nodeName
                + "\'. Error is: " + e.getMessage());
        throw new RuntimeException("Error running: " + nodeName + ": " + e.getMessage(), e);
    }

}

From source file:com.gemstone.gemfire.test.junit.rules.serializable.SerializableTimeoutTest.java

@Test
public void canBeSerialized() throws Exception {
    long timeout = 2;
    TimeUnit timeUnit = TimeUnit.SECONDS;
    boolean lookingForStuckThread = true;

    SerializableTimeout instance = SerializableTimeout.builder().withTimeout(timeout, timeUnit)
            .withLookingForStuckThread(lookingForStuckThread).build();

    assertThat(readField(Timeout.class, instance, FIELD_TIMEOUT)).isEqualTo(timeout);
    assertThat(readField(Timeout.class, instance, FIELD_TIME_UNIT)).isEqualTo(timeUnit);
    assertThat(readField(Timeout.class, instance, FIELD_LOOK_FOR_STUCK_THREAD))
            .isEqualTo(lookingForStuckThread);

    SerializableTimeout cloned = (SerializableTimeout) SerializationUtils.clone(instance);

    assertThat(readField(Timeout.class, cloned, FIELD_TIMEOUT)).isEqualTo(timeout);
    assertThat(readField(Timeout.class, cloned, FIELD_TIME_UNIT)).isEqualTo(timeUnit);
    assertThat(readField(Timeout.class, cloned, FIELD_LOOK_FOR_STUCK_THREAD)).isEqualTo(lookingForStuckThread);
}

From source file:com.gemstone.gemfire.security.GemFireSecurityExceptionTest.java

@Test
public void serializesWithThrowable() throws Exception {
    Throwable cause = new Exception(this.causeMessage);
    GemFireSecurityException instance = new GemFireSecurityException(this.message, cause);

    GemFireSecurityException cloned = (GemFireSecurityException) SerializationUtils.clone(instance);

    assertThat(cloned).hasMessage(this.message).hasCause(cause);
    assertThat(cloned.getCause()).hasMessage(this.causeMessage);
}

From source file:com.autentia.tnt.businessobject.Department.java

public void initChanges() {
    this.changes = (Department) SerializationUtils.clone(this);
}

From source file:com.gemstone.gemfire.security.NotAuthorizedExceptionTest.java

@Test
public void serializes() throws Exception {
    NotAuthorizedException instance = new NotAuthorizedException(this.message);

    NotAuthorizedException cloned = (NotAuthorizedException) SerializationUtils.clone(instance);

    assertThat(cloned).hasMessage(this.message);
}