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

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

Introduction

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

Prototype

public static <T extends Serializable> T clone(final T 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:autohearthstone.Player.java

public void performActions() {
    if (!lost && !opponent.lost) {
        generateAllActions();//from  www .  j  av a  2s  .c  om
        if (actions.size() > 0) {
            // hier wordt gekozen welke acite re gedaan word
            /// optie 1, doe gewoon de eerste
            ///////actions.get(0).Perform();
            /// optie 2, ga board values uitrekenen.
            int boardValue = CalculateBoard();
            int opponentBoardValue = opponent.CalculateBoard();

            int currentScore = boardValue - opponentBoardValue;
            if (GameOutputOn) {
                System.out
                        .println("Current board score for " + getName() + " " + Integer.toString(currentScore));
            }
            Action bestAction = new DoNothing(this);
            int highestScore = currentScore;
            int index = 0;

            for (Action action : actions) {
                Player clonedPlayer = SerializationUtils.clone(this);
                clonedPlayer.performSpecificActionOnIndex(index);
                clonedPlayer.checkBoardState();
                clonedPlayer.opponent.checkBoardState();
                if (clonedPlayer.opponent.lost == true) {
                    bestAction = action;
                    highestScore = 99999999;
                }
                if (clonedPlayer.checkForLethal()) {
                    bestAction = action;
                    highestScore = 99999999;
                }

                int boardValueCloned = clonedPlayer.CalculateBoard();
                int opponentBoardValueCloned = clonedPlayer.opponent.CalculateBoard();
                int score = boardValueCloned - opponentBoardValueCloned;
                if (score > highestScore) {
                    highestScore = score;
                    bestAction = action;
                }

                index++;
            }

            if (GameOutputOn) {
                System.out.println(this.getName() + " performs action " + bestAction.toString() + "to go from "
                        + Integer.toString(currentScore) + " to " + Integer.toString(highestScore));
            }
            bestAction.Perform();

            checkBoardState();
            opponent.checkBoardState();
            actions.clear();
            performActions();
        } else {
            pass();
        }
    }

}

From source file:com.openthinks.webscheduler.model.security.User.java

@Override
public User clone() {
    return SerializationUtils.clone(this);
}

From source file:com.epam.ta.reportportal.core.project.impl.UpdateProjectHandler.java

@Override
public OperationCompletionRS updateProject(String projectName, UpdateProjectRQ updateProjectRQ,
        String principalName) {//from  w w w  . j  a v  a2  s . c  o  m
    Project project = projectRepository.findOne(projectName);
    Project before = SerializationUtils.clone(project);
    expect(project, notNull()).verify(PROJECT_NOT_FOUND, projectName);
    if (null != updateProjectRQ.getUserRoles()) {
        expect(updateProjectRQ.getUserRoles().get(principalName), isNull())
                .verify(UNABLE_TO_UPDATE_YOURSELF_ROLE, principalName);
    }

    if (null != updateProjectRQ.getCustomer())
        project.setCustomer(updateProjectRQ.getCustomer().trim());
    project.setAddInfo(updateProjectRQ.getAddInfo());

    User principal = userRepository.findOne(principalName);

    if (null != updateProjectRQ.getUserRoles()) {
        for (Entry<String, String> user : updateProjectRQ.getUserRoles().entrySet()) {
            /*
             * Validate user exists
             */
            expect(project.getUsers(), containsKey(user.getKey())).verify(USER_NOT_FOUND, user.getKey(),
                    formattedSupplier("User '{}' not found in '{}' project", user.getKey(), projectName));
            Optional<ProjectRole> role = ProjectRole.forName(user.getValue());
            /*
             * Validate role exists
             */
            expect(role, IS_PRESENT).verify(ROLE_NOT_FOUND, user.getValue());
            ProjectRole projectRole = role.get();
            if (UserRole.ADMINISTRATOR != principal.getRole()) {
                int principalRoleLevel = project.getUsers().get(principalName).getProjectRole().getRoleLevel();
                int userRoleLevel = project.getUsers().get(user.getKey()).getProjectRole().getRoleLevel();
                /*
                 * Validate principal role level is high enough
                 */
                if (principalRoleLevel >= userRoleLevel) {
                    expect(projectRole.getRoleLevel(), isLevelEnough(principalRoleLevel)).verify(ACCESS_DENIED);
                } else {
                    expect(userRoleLevel, isLevelEnough(principalRoleLevel)).verify(ACCESS_DENIED);
                }
            }
            project.getUsers().get(user.getKey()).setProjectRole(role.get());
        }
    }

    if (null != updateProjectRQ.getConfiguration()) {
        ProjectConfiguration modelConfig = updateProjectRQ.getConfiguration();
        if (null != modelConfig.getKeepLogs()) {
            expect(KeepLogsDelay.findByName(modelConfig.getKeepLogs()), notNull()).verify(BAD_REQUEST_ERROR);
            project.getConfiguration().setKeepLogs(modelConfig.getKeepLogs());
        }

        if (null != modelConfig.getInterruptJobTime()) {
            expect(InterruptionJobDelay.findByName(modelConfig.getInterruptJobTime()), notNull())
                    .verify(BAD_REQUEST_ERROR);
            project.getConfiguration().setInterruptJobTime(modelConfig.getInterruptJobTime());
        }

        if (null != modelConfig.getKeepScreenshots()) {
            expect(KeepScreenshotsDelay.findByName(modelConfig.getKeepScreenshots()), notNull())
                    .verify(BAD_REQUEST_ERROR);
            project.getConfiguration().setKeepScreenshots(modelConfig.getKeepScreenshots());
        }

        if (null != modelConfig.getProjectSpecific()) {
            expect(ProjectSpecific.findByName(modelConfig.getProjectSpecific()).isPresent(), equalTo(true))
                    .verify(BAD_REQUEST_ERROR);
            project.getConfiguration()
                    .setProjectSpecific(ProjectSpecific.findByName(modelConfig.getProjectSpecific()).get());
        }

        if (null != modelConfig.getIsAAEnabled()) {
            project.getConfiguration().setIsAutoAnalyzerEnabled(modelConfig.getIsAAEnabled());
        }

        if (null != modelConfig.getStatisticCalculationStrategy()) {
            project.getConfiguration()
                    .setStatisticsCalculationStrategy(fromString(modelConfig.getStatisticCalculationStrategy())
                            .orElseThrow(() -> new ReportPortalException(ErrorType.BAD_REQUEST_ERROR,
                                    "Incorrect statistics calculation type: "
                                            + modelConfig.getStatisticCalculationStrategy())));
        }
    }

    try {
        projectRepository.save(project);
    } catch (Exception e) {
        throw new ReportPortalException("Error during updating Project", e);
    }

    publisher.publishEvent(new ProjectUpdatedEvent(before, project, principalName, updateProjectRQ));
    return new OperationCompletionRS("Project with name = '" + projectName + "' is successfully updated.");
}

From source file:com.xing.api.JsonSerializationTest.java

@Test
public void user() throws Exception {
    JsonAdapter<XingUser> adapter = api.converter.adapter(XingUser.class);
    String json = file("user.json");

    // Test that the user object reflects the json.
    XingUser user = adapter.fromJson(json);

    // General info.
    assertThat(user.id()).isEqualTo("123456_abcdef");
    assertThat(user.academicTitle()).isNull();
    assertThat(user.firstName()).isEqualTo("Max");
    assertThat(user.lastName()).isEqualTo("Mustermann");
    assertThat(user.displayName()).isEqualTo("Max Mustermann");
    assertThat(user.pageName()).isEqualTo("Max_Mustermann");
    assertThat(user.permalink()).isEqualTo("https://www.xing.com/profile/Max_Mustermann");
    assertThat(user.employmentStatus()).isEqualTo(EmploymentStatus.EMPLOYEE);
    assertThat(user.gender()).isEqualTo(Gender.MALE);
    assertThat(user.birthDate()).isEqualTo(new SafeCalendar(1963, Calendar.AUGUST, 12));
    assertThat(user.activeEmail()).isEqualTo("max.mustermann@xing.com");
    assertThat(user.timeZone()).isEqualTo(new TimeZone("Europe/Copenhagen", 2.0f));
    assertThat(user.premiumServices()).containsExactly(PremiumService.SEARCH, PremiumService.PRIVATE_MESSAGES);
    assertThat(user.badges()).containsExactly(Badge.PREMIUM, Badge.MODERATOR);
    assertThat(user.wants()).containsExactly("einen neuen Job", "android");
    assertThat(user.haves()).containsExactly("viele tolle Skills");
    assertThat(user.interests()).containsExactly("Flitzebogen schieen and so on");
    assertThat(user.organizations()).containsExactly("ACM", "GI");
    assertThat(user.languages()).containsExactly(MapEntry.entry(Language.DE, LanguageSkill.NATIVE),
            MapEntry.entry(Language.EN, LanguageSkill.FLUENT), MapEntry.entry(Language.FR, null),
            MapEntry.entry(Language.ZH, LanguageSkill.BASIC));

    // Addresses.
    assertPrivateAddress(user);/*from  www .  j  a v a 2  s .c  o  m*/
    assertBusinessAddress(user);

    // Web profiles.
    assertThat(user.webProfiles().keySet()).containsExactly(WebProfile.QYPE, WebProfile.GOOGLE_PLUS,
            WebProfile.OTHER, WebProfile.HOMEPAGE);
    assertThat(user.webProfiles().get(WebProfile.QYPE)).containsExactly("http://qype.de/users/foo");
    assertThat(user.webProfiles().get(WebProfile.GOOGLE_PLUS)).containsExactly("http://plus.google.com/foo");
    assertThat(user.webProfiles().get(WebProfile.OTHER)).containsExactly("http://blog.example.org");
    assertThat(user.webProfiles().get(WebProfile.HOMEPAGE)).containsExactly("http://example.org",
            "http://other-example.org");

    // Messaging accounts.
    assertThat(user.messagingAccounts()).containsExactly(MapEntry.entry(MessagingAccount.SKYPE, "1122334455"),
            MapEntry.entry(MessagingAccount.GOOGLE_TALK, "max.mustermann"));

    // Professional experience.
    assertPrimaryCompany(user);
    assertCompanies(user);
    assertThat(user.professionalExperience().awards())
            .containsExactly(new Award("Awesome Dude Of The Year", new SafeCalendar(2007), null));

    // Education background.
    assertThat(user.educationBackground().degree()).isEqualTo("MSc CE/CS");
    assertSchools(user);
    assertThat(user.educationBackground().qualifications()).containsExactly("TOEFLS", "PADI AOWD");

    // Photos.
    assertPhotoUrls(user);

    // Check that the object with all it's set fields is serializable.
    // NOTE: This is NOT fool proof and may be unreliable if a field is not java.util.Serializable
    // and is null.
    XingUser clone = SerializationUtils.clone(user);
    assertThat(clone).isEqualTo(user);
    assertThat(clone.hashCode()).isEqualTo(user.hashCode());
    assertThat(clone.toString()).isEqualTo(user.toString());
}

From source file:gov.nih.nci.firebird.selenium2.tests.profile.credentials.SpecialtyCredentialsTest.java

@Test
public void testAddSpecialty() {
    checkRequiredFields();//from  w  w  w  .  j a va 2  s.com
    BoardCertifiedSpecialty specialty2 = (BoardCertifiedSpecialty) SerializationUtils.clone(specialty);
    changeSpecialtyType(specialty2);
    saveAndVerifyNewSpecialty(credentialsTab.getSpecialtySection(), specialty);
    saveAndVerifyNewSpecialty(credentialsTab.getSpecialtySection(), specialty2);
    checkDuplicateIsInvalid();
}

From source file:it.uniroma2.sag.kelp.data.example.Example.java

/**
 * @return A copu of the current object with a different identifier, i.e.
 *         the <code>exampleId</code>
 *//*from   www .j a  va  2s. c  o  m*/
public Example duplicate() {
    Example res = SerializationUtils.clone(this);
    res.exampleId = this.generateUniqueIdentifier();
    return res;
}

From source file:com.mirth.connect.connectors.jms.JmsDispatcherTests.java

private void runTest(JmsDispatcherProperties connectorProperties, final int numMessagesToSend,
        final int numMessagesExpected) throws Exception {
    DonkeyDao dao = new PassthruDaoFactory().getDao();
    long messageIdSequence = 1;
    Destination destination;/* ww w.j a va  2 s  .com*/

    if (connectorProperties.isUseJndi()) {
        destination = (Destination) initialContext.lookup(connectorProperties.getDestinationName());
    } else {
        if (connectorProperties.isTopic()) {
            destination = session.createTopic(connectorProperties.getDestinationName());
        } else {
            destination = session.createQueue(connectorProperties.getDestinationName());
        }
    }

    MessageConsumer consumer = session.createConsumer(destination);

    DestinationConnector connector = new TestJmsDispatcher(TEST_CHANNEL_ID, 1, connectorProperties);
    connector.onDeploy();
    connector.start();

    for (int i = 0; i < numMessagesToSend; i++) {
        ConnectorMessage message = new ConnectorMessage();
        message.setMessageId(messageIdSequence++);
        message.setChannelId(TEST_CHANNEL_ID);
        message.setChainId(1);
        message.setServerId(TEST_SERVER_ID);

        MessageContent rawContent = new MessageContent(message.getChannelId(), message.getMessageId(),
                message.getMetaDataId(), ContentType.RAW, TEST_HL7_MESSAGE, "HL7", false);
        MessageContent encodedContent = SerializationUtils.clone(rawContent);
        encodedContent.setContentType(ContentType.ENCODED);

        message.setRaw(rawContent);
        message.setEncoded(encodedContent);
        message.setStatus(Status.TRANSFORMED);

        connector.process(dao, message, Status.RECEIVED);
    }

    connector.stop();
    connector.onUndeploy();
    dao.close();

    Message message = null;
    int numMessagesReceived = 0;

    while (null != (message = consumer.receiveNoWait())) {
        assertTrue((message instanceof TextMessage));
        assertEquals(TEST_HL7_MESSAGE, ((TextMessage) message).getText());
        numMessagesReceived++;
    }

    assertEquals(numMessagesExpected, numMessagesReceived);
    consumer.close();
}

From source file:alluxio.Configuration.java

/**
 * @return the deep copy of the internal {@link Properties} of this {@link Configuration} instance
 *//*from   w  ww .j a  v  a2 s .co  m*/
public Properties getInternalProperties() {
    return SerializationUtils.clone(mProperties);
}

From source file:com.mirth.connect.connectors.jms.test.JmsDispatcherTests.java

private void runTest(JmsDispatcherProperties connectorProperties, final int numMessagesToSend,
        final int numMessagesExpected) throws Exception {
    DonkeyDao dao = new PassthruDaoFactory().getDao();
    long messageIdSequence = 1;
    Destination destination;//  w  w  w. j a  v a  2s . co m

    if (connectorProperties.isUseJndi()) {
        destination = (Destination) initialContext.lookup(connectorProperties.getDestinationName());
    } else {
        if (connectorProperties.isTopic()) {
            destination = session.createTopic(connectorProperties.getDestinationName());
        } else {
            destination = session.createQueue(connectorProperties.getDestinationName());
        }
    }

    MessageConsumer consumer = session.createConsumer(destination);

    DestinationConnector connector = new TestJmsDispatcher(TEST_CHANNEL_ID, TEST_SERVER_ID, 1,
            connectorProperties);
    connector.onDeploy();
    connector.start();

    for (int i = 0; i < numMessagesToSend; i++) {
        ConnectorMessage message = new ConnectorMessage();
        message.setMessageId(messageIdSequence++);
        message.setChannelId(TEST_CHANNEL_ID);
        message.setChainId(1);
        message.setServerId(TEST_SERVER_ID);

        MessageContent rawContent = new MessageContent(message.getChannelId(), message.getMessageId(),
                message.getMetaDataId(), ContentType.RAW, TEST_HL7_MESSAGE, "HL7", false);
        MessageContent encodedContent = SerializationUtils.clone(rawContent);
        encodedContent.setContentType(ContentType.ENCODED);

        message.setRaw(rawContent);
        message.setEncoded(encodedContent);
        message.setStatus(Status.TRANSFORMED);

        connector.process(dao, message, Status.RECEIVED);
    }

    connector.stop();
    connector.onUndeploy();
    dao.close();

    Message message = null;
    int numMessagesReceived = 0;

    while (null != (message = consumer.receiveNoWait())) {
        assertTrue((message instanceof TextMessage));
        assertEquals(TEST_HL7_MESSAGE, ((TextMessage) message).getText());
        numMessagesReceived++;
    }

    assertEquals(numMessagesExpected, numMessagesReceived);
    consumer.close();
}

From source file:eu.stratosphere.api.common.typeutils.SerializerTestBase.java

@Test
public void testSerializabilityAndEquals() {
    try {/*ww  w.ja  v a  2 s  . c o m*/
        TypeSerializer<T> ser1 = getSerializer();
        TypeSerializer<T> ser2;
        try {
            ser2 = SerializationUtils.clone(ser1);
        } catch (SerializationException e) {
            fail("The serializer is not serializable.");
            return;
        }

        assertEquals("The copy of the serializer is not equal to the original one.", ser1, ser2);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        fail("Exception in test: " + e.getMessage());
    }
}