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:com.epam.ta.reportportal.core.project.impl.UpdateProjectHandler.java

@Override
public OperationCompletionRS updateProjectEmailConfig(String projectName, String user,
        UpdateProjectEmailRQ updateProjectEmailRQ) {
    Project project = projectRepository.findOne(projectName);
    Project beforeUpdate = SerializationUtils.clone(project);
    expect(project, notNull()).verify(PROJECT_NOT_FOUND, projectName);

    if (null != updateProjectEmailRQ.getConfiguration()) {
        ProjectEmailConfig config = updateProjectEmailRQ.getConfiguration();
        if (null != config.getFrom()) {
            expect(isEmailValid(config.getFrom()), equalTo(true)).verify(BAD_REQUEST_ERROR,
                    formattedSupplier("Provided FROM value '{}' is invalid", config.getFrom()));
            project.getConfiguration().getEmailConfig().setFrom(config.getFrom());
        }/*  ww w . j  a v  a 2 s .  c  o m*/

        List<EmailSenderCase> cases = config.getEmailCases();
        if (BooleanUtils.isNotFalse(config.getEmailEnabled())) {
            expect(cases, Preconditions.NOT_EMPTY_COLLECTION).verify(BAD_REQUEST_ERROR,
                    "At least one rule should be present.");
            cases.forEach(sendCase -> {
                expect(findByName(sendCase.getSendCase()).isPresent(), equalTo(true)).verify(BAD_REQUEST_ERROR,
                        sendCase.getSendCase());
                expect(sendCase.getRecipients(), notNull()).verify(BAD_REQUEST_ERROR,
                        "Recipients list should not be null");
                expect(sendCase.getRecipients().isEmpty(), equalTo(false)).verify(BAD_REQUEST_ERROR,
                        formattedSupplier("Empty recipients list for email case '{}' ", sendCase));
                sendCase.setRecipients(sendCase.getRecipients().stream().map(it -> {
                    validateRecipient(project, it);
                    return it.trim();
                }).distinct().collect(toList()));

                if (null != sendCase.getLaunchNames()) {
                    sendCase.setLaunchNames(sendCase.getLaunchNames().stream().map(name -> {
                        validateLaunchName(name);
                        return name.trim();
                    }).distinct().collect(toList()));
                }

                if (null != sendCase.getTags()) {
                    sendCase.setTags(sendCase.getTags().stream().map(tag -> {
                        expect(isNullOrEmpty(tag), equalTo(false)).verify(BAD_REQUEST_ERROR,
                                "Tags values cannot be empty. Please specify it or not include in request.");
                        return tag.trim();
                    }).distinct().collect(toList()));
                }
            });

            /* If project email settings */
            List<EmailSenderCase> withoutDuplicateCases = cases.stream().distinct().collect(toList());
            if (cases.size() != withoutDuplicateCases.size())
                fail().withError(BAD_REQUEST_ERROR, "Project email settings contain duplicate cases");

            project.getConfiguration().getEmailConfig().setEmailCases(cases);
        }

        /* If enable parameter is FALSE, previous settings be dropped */
        if (!config.getEmailEnabled())
            setDefaultEmailCofiguration(project);
        else
            project.getConfiguration().getEmailConfig().setEmailEnabled(true);
    } else {
        /* Something wrong with input RQ but we don't care about */
    }

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

    publisher.publishEvent(new EmailConfigUpdatedEvent(beforeUpdate, updateProjectEmailRQ, user));
    return new OperationCompletionRS(
            "EMail configuration of project with name = '" + projectName + "' is successfully updated.");
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseDispatcherTests.java

private void runTest(DatabaseDispatcherProperties properties, List<String> tables) throws Exception {
    final int numMessages = 3;

    initTables();/* w w  w.  j a  v a 2 s  .  c  o m*/

    Channel channel = new Channel();
    channel.setId(TEST_CHANNEL_ID);
    channel.setName("test channel");
    ChannelController.getInstance().putDeployedChannelInCache(channel);

    DonkeyDao dao = new PassthruDaoFactory().getDao();

    DestinationConnector databaseDispatcher = new TestDatabaseDispatcher(TEST_CHANNEL_ID, 1, properties);
    databaseDispatcher.onDeploy();
    databaseDispatcher.start();

    long messageIdSequence = 1;

    List<Map<String, String>> messages = new ArrayList<Map<String, String>>();

    Map<String, String> map = new HashMap<String, String>();
    map.put("mypatientid", "1");
    map.put("firstname", "Joe");
    map.put("lastname", "Rodriguez");
    map.put("gender", "M");
    map.put("dateofbirth", "1935-01-18");
    messages.add(map);

    map = new HashMap<String, String>();
    map.put("mypatientid", "2");
    map.put("firstname", "Hubert");
    map.put("lastname", "Farnsworth");
    map.put("gender", "M");
    map.put("dateofbirth", "1935-01-18");
    messages.add(map);

    map = new HashMap<String, String>();
    map.put("mypatientid", "3");
    map.put("firstname", "Amy");
    map.put("lastname", "Wong");
    map.put("gender", "F");
    map.put("dateofbirth", "1935-01-18");
    messages.add(map);

    for (int i = 0; i < numMessages; 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.getChannelMap().putAll(messages.get(i));
        message.setStatus(Status.TRANSFORMED);

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

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

    Statement statement = connection.createStatement();

    for (String table : tables) {
        ResultSet result = statement
                .executeQuery("SELECT mypatientid, firstname, lastname, gender, dateofbirth::varchar FROM "
                        + table + " ORDER BY mypatientid");
        int i = 0;

        while (result.next()) {
            map = messages.get(i++);
            assertEquals(map.get("mypatientid"), result.getString(1));
            assertEquals(map.get("firstname"), result.getString(2));
            assertEquals(map.get("lastname"), result.getString(3));
            assertEquals(map.get("gender"), result.getString(4));
            assertEquals(map.get("dateofbirth"), result.getString(5));
        }

        result.close();
        assertEquals(messages.size(), i);
    }

    statement.close();
}

From source file:com.mirth.connect.connectors.jdbc.test.DatabaseDispatcherTests.java

private void runTest(DatabaseDispatcherProperties properties, List<String> tables) throws Exception {
    final int numMessages = 3;

    initTables();/*  w  w w . ja v a 2  s  .c  om*/

    Channel channel = new Channel();
    channel.setId(TEST_CHANNEL_ID);
    channel.setName("test channel");
    ChannelController.getInstance().putDeployedChannelInCache(channel);

    DonkeyDao dao = new PassthruDaoFactory().getDao();

    DestinationConnector databaseDispatcher = new TestDatabaseDispatcher(TEST_CHANNEL_ID, TEST_SERVER_ID, 1,
            properties);
    databaseDispatcher.onDeploy();
    databaseDispatcher.start();

    long messageIdSequence = 1;

    List<Map<String, String>> messages = new ArrayList<Map<String, String>>();

    Map<String, String> map = new HashMap<String, String>();
    map.put("mypatientid", "1");
    map.put("firstname", "Joe");
    map.put("lastname", "Rodriguez");
    map.put("gender", "M");
    map.put("dateofbirth", "1935-01-18");
    messages.add(map);

    map = new HashMap<String, String>();
    map.put("mypatientid", "2");
    map.put("firstname", "Hubert");
    map.put("lastname", "Farnsworth");
    map.put("gender", "M");
    map.put("dateofbirth", "1935-01-18");
    messages.add(map);

    map = new HashMap<String, String>();
    map.put("mypatientid", "3");
    map.put("firstname", "Amy");
    map.put("lastname", "Wong");
    map.put("gender", "F");
    map.put("dateofbirth", "1935-01-18");
    messages.add(map);

    for (int i = 0; i < numMessages; 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.getChannelMap().putAll(messages.get(i));
        message.setStatus(Status.TRANSFORMED);

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

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

    Statement statement = connection.createStatement();

    for (String table : tables) {
        ResultSet result = statement
                .executeQuery("SELECT mypatientid, firstname, lastname, gender, dateofbirth::varchar FROM "
                        + table + " ORDER BY mypatientid");
        int i = 0;

        while (result.next()) {
            map = messages.get(i++);
            assertEquals(map.get("mypatientid"), result.getString(1));
            assertEquals(map.get("firstname"), result.getString(2));
            assertEquals(map.get("lastname"), result.getString(3));
            assertEquals(map.get("gender"), result.getString(4));
            assertEquals(map.get("dateofbirth"), result.getString(5));
        }

        result.close();
        assertEquals(messages.size(), i);
    }

    statement.close();
}

From source file:com.epam.ta.reportportal.core.item.UpdateTestItemHandlerImpl.java

@Override
public List<OperationCompletionRS> addExternalIssues(String projectName, AddExternalIssueRQ rq,
        String userName) {//from w  ww. ja  v  a2 s. c  om
    List<String> errors = new ArrayList<>();
    ExternalSystem extSystem = externalSystemRepository.findOne(rq.getExternalSystemId());
    expect(extSystem, notNull()).verify(EXTERNAL_SYSTEM_NOT_FOUND, rq.getExternalSystemId());

    Iterable<TestItem> testItems = testItemRepository.findAll(rq.getTestItemIds());
    List<TestItem> before = SerializationUtils.clone(Lists.newArrayList(testItems));
    StreamSupport.stream(testItems.spliterator(), false).forEach(testItem -> {
        try {
            verifyTestItem(testItem, testItem.getId());
            Set<TestItemIssue.ExternalSystemIssue> tiIssues = rq.getIssues().stream()
                    .filter(issue -> !issue.getTicketId().trim().isEmpty())
                    .map(TestItemUtils.externalIssueDtoConverter(rq.getExternalSystemId(), userName))
                    .collect(toSet());
            if (null == testItem.getIssue().getExternalSystemIssues()) {
                testItem.getIssue().setExternalSystemIssues(tiIssues);
            } else {
                tiIssues.addAll(testItem.getIssue().getExternalSystemIssues());
                testItem.getIssue().setExternalSystemIssues(tiIssues);
            }
        } catch (BusinessRuleViolationException e) {
            errors.add(e.getMessage());
        }
    });

    expect(!errors.isEmpty(), equalTo(FALSE)).verify(FAILED_TEST_ITEM_ISSUE_TYPE_DEFINITION, errors.toString());

    testItemRepository.save(testItems);
    eventPublisher.publishEvent(
            new TicketAttachedEvent(before, Lists.newArrayList(testItems), userName, projectName));
    return StreamSupport.stream(testItems.spliterator(), false).map(testItem -> new OperationCompletionRS(
            "TestItem with ID = '" + testItem.getId() + "' successfully updated.")).collect(toList());
}

From source file:com.github.dozermapper.core.functional_tests.MapperTest.java

@Test
public void testMappingNoDestSpecified() {
    // Map//  w w  w  . j  av a2 s  .  c om
    House src = testDataFactory.getHouse();
    HomeDescription dest = mapper.map(src, HomeDescription.class);
    House src2 = mapper.map(dest, House.class);
    HomeDescription dest2 = mapper.map(src2, HomeDescription.class);

    long[] prim = { 1, 2, 3, 1, 2, 3 };
    // cumulative relationship
    dest.setPrim(prim);
    assertEquals(dest, dest2);

    // By reference
    src = testDataFactory.getHouse();
    House houseClone = SerializationUtils.clone(src);
    dest = mapper.map(src, HomeDescription.class);
    mapper.map(dest, House.class);
    assertEquals(houseClone, src);
}

From source file:com.mirth.connect.plugins.dashboardstatus.DashboardConnectorEventListener.java

public synchronized LinkedList<String[]> getChannelLog(Object object, String sessionId) {
    String channelName;//w w w  .ja v a 2 s  .c o  m
    LinkedList<String[]> channelLog;

    if (object == null) {
        /*
         * object is null - no channel is selected. return the latest entire log entries of all
         * channels combined. ONLY new entries.
         */
        channelName = "No Channel Selected";
        channelLog = entireConnectorInfoLogs;
    } else {
        // object is not null - a channel is selected. return the latest
        // (LOG_SIZE) of that particular channel.
        channelName = object.toString();
        // return only the newly added log entries for the client with
        // matching sessionId.
        channelLog = connectorInfoLogs.get(channelName);

        if (channelLog == null) {
            channelLog = new LinkedList<String[]>();
            connectorInfoLogs.put(channelName, channelLog);
        }
    }

    Map<String, Long> lastDisplayedLogIdByChannel;

    if (lastDisplayedLogIndexBySessionId.containsKey(sessionId)) {
        // client exist with the sessionId.
        lastDisplayedLogIdByChannel = lastDisplayedLogIndexBySessionId.get(sessionId);

        if (lastDisplayedLogIdByChannel.containsKey(channelName)) {
            // existing channel on an already open client.
            // -> only display new log entries.
            long lastDisplayedLogId = lastDisplayedLogIdByChannel.get(channelName);
            LinkedList<String[]> newChannelLogEntries = new LinkedList<String[]>();

            // FYI, channelLog.size() will never be larger than LOG_SIZE
            // = 1000.
            for (String[] aChannelLog : channelLog) {
                if (lastDisplayedLogId < Long.parseLong(aChannelLog[0])) {
                    newChannelLogEntries.addLast(aChannelLog);
                }
            }

            if (newChannelLogEntries.size() > 0) {
                /*
                 * put the lastDisplayedLogId into the HashMap. index 0 is the most recent
                 * entry, and index0 of that entry contains the logId.
                 */
                lastDisplayedLogIdByChannel.put(channelName, Long.parseLong(newChannelLogEntries.get(0)[0]));
                lastDisplayedLogIndexBySessionId.put(sessionId, lastDisplayedLogIdByChannel);
            }

            try {
                return SerializationUtils.clone(newChannelLogEntries);
            } catch (SerializationException e) {
                logger.error(e);
            }
        } else {
            /*
             * new channel viewing on an already open client. -> all log entries are new.
             * display them all. put the lastDisplayedLogId into the HashMap. index0 is the most
             * recent entry, and index0 of that entry object contains the logId.
             */
            if (channelLog.size() > 0) {
                lastDisplayedLogIdByChannel.put(channelName, Long.parseLong(channelLog.get(0)[0]));
                lastDisplayedLogIndexBySessionId.put(sessionId, lastDisplayedLogIdByChannel);
            }

            try {
                return SerializationUtils.clone(channelLog);
            } catch (SerializationException e) {
                logger.error(e);
            }
        }

    } else {
        // brand new client.
        // thus also new channel viewing.
        // -> all log entries are new. display them all.
        lastDisplayedLogIdByChannel = new HashMap<String, Long>();

        if (channelLog.size() > 0) {
            lastDisplayedLogIdByChannel.put(channelName, Long.parseLong(channelLog.get(0)[0]));
        } else {
            // no log exist at all. put the currentLogId-1, which is the
            // very latest logId.
            lastDisplayedLogIdByChannel.put(channelName, logId - 1);
        }

        lastDisplayedLogIndexBySessionId.put(sessionId, lastDisplayedLogIdByChannel);

        try {
            return SerializationUtils.clone(channelLog);
        } catch (SerializationException e) {
            logger.error(e);
        }
    }

    return null;
}

From source file:com.github.dozermapper.core.functional_tests.MapperTest.java

@Test
public void testGeneralMappingPassByReference() {
    // Map/* w ww  .  j ava  2s .co  m*/
    TestObject to = testDataFactory.getInputGeneralMappingTestObject();
    TestObject toClone = SerializationUtils.clone(to);
    TestObjectPrime prime = mapper.map(to, TestObjectPrime.class);
    mapper.map(prime, to);
    // more objects should be added to the clone from the ArrayList
    TheFirstSubClass fsc = new TheFirstSubClass();
    fsc.setS("s");
    toClone.getHintList().add(fsc);
    toClone.getHintList().add(fsc);
    toClone.getEqualNamedList().add("1value");
    toClone.getEqualNamedList().add("2value");
    int[] pa = { 0, 1, 2, 3, 4, 0, 1, 2, 3, 4 };
    int[] intArray = { 1, 1, 1, 1 };
    Integer[] integerArray = { new Integer(1), new Integer(1), new Integer(1), new Integer(1) };
    toClone.setAnArray(intArray);
    toClone.setArrayForLists(integerArray);
    toClone.setPrimArray(pa);
    toClone.setBlankDate(null);
    toClone.setBlankStringToLong(null);
    // since we copy by reference the attribute copyByReference we need to null it out. The clone method above creates
    // two versions of it...
    // which is incorrect
    to.setCopyByReference(null);
    toClone.setCopyByReference(null);
    to.setCopyByReferenceDeep(null);
    toClone.setCopyByReferenceDeep(null);
    to.setGlobalCopyByReference(null);
    toClone.setGlobalCopyByReference(null);
    // null out string array because we get NPE since a NULL value in the String []
    to.setStringArrayWithNullValue(null);
    toClone.setStringArrayWithNullValue(null);
    toClone.setExcludeMeOneWay("excludeMeOneWay");
    assertEquals(toClone, to);
}

From source file:com.vaushell.superpipes.nodes.A_Node.java

/**
 * Receive a message and stack it.//from www  .ja  va2 s.co m
 *
 * @param message Message
 * @throws java.lang.Exception
 */
public void receiveMessage(final Message message) throws Exception {
    if (message == null) {
        throw new IllegalArgumentException();
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getNodeID() + "] receiveMessage : message=" + Message.formatSimple(message));
    }

    Message result = SerializationUtils.clone(message);
    for (final A_Transform transform : transformsIN) {
        result = transform.transform(result);
        if (result == null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "[" + getNodeID() + "] receive but discard message=" + Message.formatSimple(message));
            }

            return;
        } else {
            result = SerializationUtils.clone(result);
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[" + getNodeID() + "] receive and stack message=" + Message.formatSimple(message));
    }

    synchronized (internalStack) {
        internalStack.addFirst(result);

        internalStack.notifyAll();
    }
}

From source file:com.feilong.core.bean.BeanUtilTest.java

@Test
public void cloneBean2() {
    OrderLine orderLine = new OrderLine();
    orderLine.setCount(8);//from  w w  w  .j a va 2  s .  c  o  m
    orderLine.setSalePrice(toBigDecimal(599));

    List<OrderLine> list = toList(orderLine);

    //*******************************************************************

    List<OrderLine> list1 = list;
    List<OrderLine> copyList = new ArrayList<>();

    for (OrderLine orderLineTemp : list) {
        copyList.add(BeanUtil.cloneBean(orderLineTemp));
    }
    //PropertyUtil.copyProperties(copyList, list);
    //************************************************************

    // List<OrderLine> cloneList = BeanUtil.cloneBean(list);

    //************************************************************

    String format = JsonUtil.format(list, ConvertUtil.toArray("MSRP"), 0, 0);
    LOGGER.debug("the param format:{}", format);

    List<OrderLine> serializelist = (List<OrderLine>) SerializationUtils.clone((Serializable) list);

    //******************************************************************
    for (OrderLine perOrderLine : list) {
        perOrderLine.setSalePrice(toBigDecimal(200));
    }
    //******************************************************************
    List<OrderLine> jsonList = JsonUtil.toList(format, OrderLine.class);

    assertEquals(toBigDecimal(200), list1.get(0).getSalePrice());
    //assertEquals(toBigDecimal(599), cloneList.get(0).getSalePrice());
    assertEquals(toBigDecimal(599), serializelist.get(0).getSalePrice());
    assertEquals(toBigDecimal(599), jsonList.get(0).getSalePrice());
    assertEquals(toBigDecimal(599), copyList.get(0).getSalePrice());
}

From source file:eu.crisis_economics.abm.model.ModelUtils.java

/**
  * See {@link #applyWithCloning(Object, String, Object...)}.<br><br> This method supplements 
  * {@link #applyWithCloning(Object, String, Object...)} with the boolean argument
  * {@code doCloneArguments}.//w  ww .  ja v  a2 s .  co  m
  * 
  * @param doCloneArguments
  *        If <code>true</code>, all {@link Serializable} {@code arguments} will
  *        be cloned anew for each use. Otherwise, if <code>false</code>, the objects
  *        listed in {@code arguments} will not be cloned and may potentially be 
  *        reused for several {@link Method} invocations.
  */
public static List<Object> apply(final Object on, final boolean doCloneArguments, final String setterName,
        final Object... arguments) {
    final Class<?>[] argTypes = new Class<?>[arguments.length];
    for (int i = 0; i < arguments.length; ++i)
        argTypes[i] = arguments[i].getClass();
    final List<Pair<Method, Object>> targets = search(on, setterName, argTypes);
    final List<Object> result = new ArrayList<Object>();
    for (final Pair<Method, Object> target : targets)
        try {
            final Object[] argumentsToUse = new Object[arguments.length];
            for (int i = 0; i < arguments.length; ++i)
                if (arguments[i] instanceof Serializable && doCloneArguments)
                    argumentsToUse[i] = SerializationUtils.clone((Serializable) arguments[i]);
                else
                    argumentsToUse[i] = arguments[i];
            result.add(target.getFirst().invoke(target.getSecond(), argumentsToUse));
            if (VERBOSE_MODE)
                System.out.printf("Applying %s(%s) to %s\n", target.getFirst().getName(),
                        arguments.length == 0 ? "void"
                                : arguments.length == 1 ? arguments[0].toString() : Arrays.toString(arguments),
                        target.getFirst().getDeclaringClass().getSimpleName());
        } catch (final IllegalArgumentException e) {
            throw new IllegalStateException();
        } catch (final IllegalAccessException e) {
            throw new IllegalStateException();
        } catch (final InvocationTargetException e) {
            throw new IllegalStateException();
        }
    return result;
}