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.flexive.ejb.beans.configuration.GenericConfigurationImpl.java

/**
 * {@inheritDoc}/*from   www  . ja v a2  s.com*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public <T extends Serializable> void put(Parameter<T> parameter, String key, T value)
        throws FxApplicationException {

    if (!parameter.isValid(value)) {
        throw new FxUpdateException("ex.configuration.parameter.value", parameter, value);
    }

    // put into DB config table
    Connection conn = null;
    PreparedStatement stmt = null;
    ParameterData<T> data = parameter.getData();
    String oldValue = null;
    try {
        conn = getConnection();
        stmt = getSelectStatement(conn, data.getPath().getValue(), key);
        ResultSet rs = stmt.executeQuery();
        boolean valueExists = rs.next();
        if (valueExists) {
            oldValue = rs.getString(1);
            if (!StringUtils.isEmpty(oldValue) && oldValue.equals(String.valueOf(value)))
                return; //no changes
        }
        stmt.close();

        try {
            writeParameter(conn, parameter, key, value, data, valueExists);
        } catch (SQLException e) {
            if (!valueExists && StorageManager.isUniqueConstraintViolation(e)) {
                // tried to insert record, but record exists - workaround for strange
                // bug on MySQL, where an ALTER TABLE on the configuration table messes up
                // subsequent SELECTs (DB schema version 1353)
                writeParameter(conn, parameter, key, value, data, true);
            } else {
                throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage());
            }
        }

        // update cache?
        String cachePath = getCachePath(data.getPath().getValue());
        if (cachePath != null) {
            putCache(cachePath, key,
                    value != null ? (Serializable) SerializationUtils.clone(value) : new NullParameter(), true);
        }
        StringBuilder sbHistory = new StringBuilder(1000);
        sbHistory.append("<parameter type=\"").append(parameter.getScope().name()).append("\">\n");
        sbHistory.append("  <path><![CDATA[").append(parameter.getPath()).append("]]></path>\n");
        sbHistory.append("  <key><![CDATA[").append(key).append("]]></key>\n");
        if (oldValue != null)
            sbHistory.append("  <oldValue><![CDATA[").append(oldValue).append("]]></oldValue>\n");
        sbHistory.append("  <value><![CDATA[").append(String.valueOf(value)).append("]]></value>\n");
        sbHistory.append("</parameter>\n");
        EJBLookup.getHistoryTrackerEngine().trackData(sbHistory.toString(), "history.parameter.set",
                parameter.getScope().name(), parameter.getPath(), key);
    } catch (SQLException se) {
        FxUpdateException ue = new FxUpdateException(LOG, se, "ex.db.sqlError", se.getMessage());
        LOG.error(ue, se);
        throw ue;
    } finally {
        Database.closeObjects(GenericConfigurationImpl.class, conn, stmt);
    }
}

From source file:com.mirth.connect.server.controllers.DefaultChannelController.java

@Override
public synchronized void setChannelEnabled(Set<String> channelIds, ServerEventContext context, boolean enabled)
        throws ControllerException {
    /*/*from   w  ww  . ja va2  s  .  c o  m*/
     * Methods that update the channel must be synchronized to ensure the channel cache and
     * database never contain different versions of a channel.
     */
    ControllerException firstCause = null;
    List<Channel> cachedChannels = getChannels(channelIds);

    for (Channel cachedChannel : cachedChannels) {
        // If the channel is not invalid, and its enabled flag isn't already the same as what was passed in
        if (!(cachedChannel instanceof InvalidChannel) && cachedChannel.isEnabled() != enabled) {
            Channel channel = (Channel) SerializationUtils.clone(cachedChannel);
            channel.setEnabled(enabled);
            channel.setRevision(channel.getRevision() + 1);

            try {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("id", channel.getId());
                params.put("name", channel.getName());
                params.put("revision", channel.getRevision());
                params.put("channel", channel);

                // Update the new channel in the database
                logger.debug("updating channel");
                SqlConfig.getSqlSessionManager().update("Channel.updateChannel", params);

                // invoke the channel plugins
                for (ChannelPlugin channelPlugin : extensionController.getChannelPlugins().values()) {
                    channelPlugin.save(channel, context);
                }
            } catch (Exception e) {
                if (firstCause == null) {
                    firstCause = new ControllerException(e);
                }
            }
        }
    }

    if (firstCause != null) {
        throw firstCause;
    }
}

From source file:com.fortify.processrunner.cli.CLIOptionDefinition.java

public CLIOptionDefinition deepCopy() {
    return (CLIOptionDefinition) SerializationUtils.clone(this);
}

From source file:com.mirth.connect.server.controllers.DefaultChannelController.java

@Override
public synchronized void setChannelInitialState(Set<String> channelIds, ServerEventContext context,
        DeployedState initialState) throws ControllerException {
    /*//from  w ww.j a va  2s  .  c o  m
     * Methods that update the channel must be synchronized to ensure the channel cache and
     * database never contain different versions of a channel.
     */
    if (initialState != DeployedState.STARTED && initialState != DeployedState.PAUSED
            && initialState != DeployedState.STOPPED) {
        throw new ControllerException("Cannot set initial state to " + initialState);
    }

    ControllerException firstCause = null;
    List<Channel> cachedChannels = getChannels(channelIds);

    for (Channel cachedChannel : cachedChannels) {
        // If the channel is not invalid, and its enabled flag isn't already the same as what was passed in
        if (!(cachedChannel instanceof InvalidChannel)
                && cachedChannel.getProperties().getInitialState() != initialState) {
            Channel channel = (Channel) SerializationUtils.clone(cachedChannel);
            channel.getProperties().setInitialState(initialState);
            channel.setRevision(channel.getRevision() + 1);

            try {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("id", channel.getId());
                params.put("name", channel.getName());
                params.put("revision", channel.getRevision());
                params.put("channel", channel);

                // Update the new channel in the database
                logger.debug("updating channel");
                SqlConfig.getSqlSessionManager().update("Channel.updateChannel", params);

                // invoke the channel plugins
                for (ChannelPlugin channelPlugin : extensionController.getChannelPlugins().values()) {
                    channelPlugin.save(channel, context);
                }
            } catch (Exception e) {
                if (firstCause == null) {
                    firstCause = new ControllerException(e);
                }
            }
        }
    }

    if (firstCause != null) {
        throw firstCause;
    }
}

From source file:com.comphenix.protocol.events.PacketContainerTest.java

@Test
public void testSerialization() {
    PacketContainer chat = new PacketContainer(PacketType.Play.Client.CHAT);
    chat.getStrings().write(0, "Test");

    PacketContainer copy = (PacketContainer) SerializationUtils.clone(chat);

    assertEquals(PacketType.Play.Client.CHAT, copy.getType());
    assertEquals("Test", copy.getStrings().read(0));
}

From source file:eu.eexcess.federatedrecommender.evaluation.FederatedRecommenderEvaluationCore.java

/**
 * main function for the decomposer evaluation
 * @param id/*from  w ww  .  j  a v  a  2  s  . c o  m*/
 * @return
 */
private EvaluationResultLists getExpansionEvaluationResult(Integer id) {
    final EvaluationResultLists results = new EvaluationResultLists();
    final SecureUserProfileEvaluation evalProfil = evalManager.getNextQuery(id);

    ArrayList<PartnerBadge> sourceExpansionPartners = new ArrayList<PartnerBadge>();
    for (PartnerBadge partner : fRCore.getPartnerRegister().getPartners()) {
        if (partner.systemId.contains("ZBW"))
            sourceExpansionPartners.add(partner);
    }
    ArrayList<PartnerBadge> queryPartner = new ArrayList<PartnerBadge>();
    for (PartnerBadge partner : fRCore.getPartnerRegister().getPartners()) {
        if (partner.systemId.contains("Mendeley"))
            queryPartner.add(partner);
    }

    results.query = evalProfil.getContextKeywordConcatenation(); //TODO!
    results.queryDescription = evalProfil.description;
    evalProfil.picker = "FiFoPicker";

    final SecureUserProfileEvaluation wikipediaProfile = (SecureUserProfileEvaluation) SerializationUtils
            .clone(evalProfil);
    wikipediaProfile.partnerList = queryPartner;
    Future<Void> wikipedia = threadPool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            wikipediaProfile.decomposer = "wikipedia";
            results.results.add((EvaluationResultList) getEvaluationResults(wikipediaProfile));
            return null;
        }
    });
    final SecureUserProfileEvaluation noneProfile = (SecureUserProfileEvaluation) SerializationUtils
            .clone(evalProfil);
    //      noneProfile.partnerList=queryPartner;
    Future<Void> none = threadPool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            noneProfile.decomposer = "";
            results.results.add((EvaluationResultList) getEvaluationResults(noneProfile));
            return null;
        }
    });

    final SecureUserProfileEvaluation sourceProfile = (SecureUserProfileEvaluation) SerializationUtils
            .clone(evalProfil);
    sourceProfile.partnerList = queryPartner;
    Future<Void> source = threadPool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            sourceProfile.decomposer = "source";
            results.results.add((EvaluationResultList) getEvaluationResults(sourceProfile));
            return null;
        }
    });
    final SecureUserProfileEvaluation sourceProfile2 = (SecureUserProfileEvaluation) SerializationUtils
            .clone(evalProfil);
    sourceProfile2.partnerList = queryPartner;
    sourceProfile2.queryExpansionSourcePartner = sourceExpansionPartners;
    Future<Void> source2 = threadPool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            sourceProfile2.decomposer = "source";
            results.results.add((EvaluationResultList) getEvaluationResults(sourceProfile2));
            return null;
        }
    });
    //
    //
    try {
        source.get();
        source2.get();
        none.get();
        wikipedia.get();
    } catch (InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return results;
}

From source file:com.floreantpos.ui.views.payment.GroupSettleTicketDialog.java

public void settleTicket(PosTransaction posTransaction) {
    try {/*from   w ww.j  a  v  a  2 s  .  com*/
        List<PosTransaction> transactionList = new ArrayList<PosTransaction>();
        totalTenderAmount = paymentView.getTenderedAmount();

        for (Ticket ticket : tickets) {
            PosTransaction transaction = null;
            if (totalTenderAmount <= 0) {
                break;
            }

            transaction = (PosTransaction) SerializationUtils.clone(posTransaction);
            transaction.setGlobalId(GlobalIdGenerator.generate());
            transaction.setTicket(ticket);
            setTransactionAmounts(transaction);

            confirmLoyaltyDiscount(ticket);

            PosTransactionService transactionService = PosTransactionService.getInstance();
            transactionService.settleTicket(ticket, transaction);

            transactionList.add(transaction);
            printTicket(ticket, transaction);
        }

        //FIXME
        showTransactionCompleteMsg(totalDueAmount, totalTenderAmount, tickets, transactionList);

        setCanceled(false);
        dispose();

    } catch (UnknownHostException e) {
        POSMessageDialog.showError(Application.getPosWindow(), Messages.getString("SettleTicketDialog.12")); //$NON-NLS-1$
    } catch (Exception e) {
        POSMessageDialog.showError(this, POSConstants.ERROR_MESSAGE, e);
    }
}

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

public synchronized Object invoke(String method, Object object, String sessionId) {
    if (method.equals(METHOD_GET_STATES)) {
        return connectorStateMap;
    } else if (method.equals(METHOD_GET_CONNECTION_INFO_LOGS)) {
        String channelName;/*from  w  w w .j ava 2 s .  c om*/
        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 = STATE_NO_SELECTION;
            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);
            }
        }

        HashMap<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);
            }
        }

    } else if (method.equals(METHOD_CHANNELS_DEPLOYED)) {
        if (channelsDeployedFlagForEachClient.containsKey(sessionId)) {
            // sessionId found. no (re)deploy occurred.
            return false;
        } else {
            // no sessionId found, which means channels have just been
            // (re)deployed - clear out all clients' Dashboard Connector
            // Logs.
            channelsDeployedFlagForEachClient.put(sessionId, true);
            return true;
        }
    } else if (method.equals(METHOD_REMOVE_SESSIONID)) {
        // client shut down, or user logged out -> remove everything
        // involving this sessionId.
        if (lastDisplayedLogIndexBySessionId.containsKey(sessionId)) {
            lastDisplayedLogIndexBySessionId.remove(sessionId);
        }

        if (channelsDeployedFlagForEachClient.containsKey(sessionId)) {
            channelsDeployedFlagForEachClient.remove(sessionId);
        }

        return null;
    }

    return null;
}

From source file:ec.gob.ceaaces.controller.MallasController.java

/**
 * @param asignatura// w  w  w  .  j  a va2  s. c  o m
 *            the asignatura to set
 */
public void setAsignatura(AsignaturaDTO asignatura) {
    this.asignatura = (AsignaturaDTO) SerializationUtils.clone(asignatura);

    if (asignatura != null && asignatura.getId() != null) {
        for (int i = 0; i < tiposAsignatura.size(); i++) {
            if (tiposAsignatura.get(i).equals(asignatura.getTipoAsignatura())) {
                setOpcionRequisito(i + 1);
                break;
            }
        }
    }

}

From source file:com.mirth.connect.server.controllers.DefaultMessageObjectController.java

private void removeMessagesFromQueue(MessageObjectFilter filter) throws Exception {
    String uid = String.valueOf(System.currentTimeMillis());
    // clone the filter so that we don't modify the original
    MessageObjectFilter queueFilter = (MessageObjectFilter) SerializationUtils.clone(filter);
    queueFilter.setStatus(Status.QUEUED);
    int size = createMessagesTempTable(queueFilter, uid, true);
    int page = 0;
    int interval = 10;

    while ((page * interval) < size) {
        for (MessageObject message : getMessagesByPage(page, interval, size, uid, true)) {
            removeMessageFromQueue(message);
        }/*from  ww w .  j a  va  2  s  .  c  o  m*/

        page++;
    }

    removeFilterTable(uid);
}