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:org.geomajas.plugin.deskmanager.service.common.GeodeskConfigurationServiceImpl.java

private ClientLayerInfo createLayer(ClientLayer geodeskLayer, ClientLayer blueprintLayer) {
    ClientLayerInfo serverCli = null;/*from  ww w  . jav a  2s  .c  o  m*/
    ClientLayerInfo targetCli = null;
    Layer<?> serverLayer = null;

    if (geodeskLayer != null && geodeskLayer.getLayerModel() != null) {
        try {
            serverCli = (ClientLayerInfo) SerializationUtils.clone((ClientLayerInfo) applicationContext
                    .getBean(geodeskLayer.getLayerModel().getClientLayerId()));
            boolean isVectorLayer = serverCli instanceof ClientVectorLayerInfo;
            serverLayer = (Layer<?>) applicationContext.getBean(serverCli.getServerLayerId());

            // Override layerInfo from server layer
            serverCli
                    .setLayerInfo((LayerInfo) SerializationUtils.clone((LayerInfo) serverLayer.getLayerInfo()));
            if (isVectorLayer) {
                ClientVectorLayerInfo cvli = (ClientVectorLayerInfo) serverCli;
                cvli.setFeatureInfo(((VectorLayerInfo) cvli.getLayerInfo()).getFeatureInfo());
            }
            targetCli = serverCli;

            // Override with clientLayerInfo if it is set
            if (geodeskLayer.getClientLayerInfo() != null) {
                targetCli = geodeskLayer.getClientLayerInfo();

                // Set layerInfo and max extent from server configuration.
                targetCli.setLayerInfo(serverLayer.getLayerInfo());
                targetCli.setMaxExtent(serverCli.getMaxExtent());

                // Register the style if a vectorlayer.
                if (isVectorLayer) {
                    for (NamedStyleInfo nsi : ((VectorLayerInfo) targetCli.getLayerInfo())
                            .getNamedStyleInfos()) {
                        log.debug("Registering style for layer: " + targetCli.getLabel());
                        nsi.setName(styleService.registerStyle(targetCli.getServerLayerId(), nsi));
                    }
                }
            }

            // Finally set the widget configuration as a see trough.
            // Widget configurations set in the configuration
            Map<String, ClientWidgetInfo> clientWidgetInfos = new HashMap<String, ClientWidgetInfo>();
            clientWidgetInfos.putAll(serverCli.getWidgetInfo());
            // Widget info set on the layer
            if (geodeskLayer != null && geodeskLayer.getLayerModel() != null) {
                clientWidgetInfos.putAll(geodeskLayer.getLayerModel().getWidgetInfo());
            }
            // Widget info set on the blueprint
            if (blueprintLayer != null) {
                clientWidgetInfos.putAll(blueprintLayer.getWidgetInfo());
            }
            // Widget info set on the geodesk layer
            if (geodeskLayer != null) {
                clientWidgetInfos.putAll(geodeskLayer.getWidgetInfo());
            }
            targetCli.setWidgetInfo(clientWidgetInfos);

            return targetCli;

        } catch (NoSuchBeanDefinitionException e) {
            // Ignore, error message later
        }
    }

    return null;
}

From source file:org.geoserver.catalog.impl.ModificationProxyCloner.java

/**
 * Best effort object cloning utility, tries different lightweight strategies, then falls back
 * on copy by XStream serialization (we use that one as we have a number of hooks to avoid deep
 * copying the catalog, and re-attaching to it, in there)
 * /*from  w w w .  j  a va2s . c  om*/
 * @param source
 * @return
 */
static <T> T clone(T source) {
    // null?
    if (source == null) {
        return null;
    }

    // already a modification proxy?
    if (ModificationProxy.handler(source) != null) {
        return source;
    }

    // is it a catalog info?
    if (source instanceof CatalogInfo) {
        // mumble... shouldn't we wrap this one in a modification proxy object?
        return (T) ModificationProxy.create(source, getDeepestCatalogInfoInterface((CatalogInfo) source));
    }

    // if a known immutable?
    if (source instanceof String || source instanceof Byte || source instanceof Short
            || source instanceof Integer || source instanceof Float || source instanceof Double
            || source instanceof BigInteger || source instanceof BigDecimal) {
        return (T) source;
    }

    // is it cloneable?
    try {
        if (source instanceof Cloneable) {
            // methodutils does not seem to work against "clone()"...
            // return (T) MethodUtils.invokeExactMethod(source, "clone", null, null);
            Method method = source.getClass().getDeclaredMethod("clone");
            if (Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0) {
                return (T) method.invoke(source);
            }
        }
    } catch (Exception e) {
        LOGGER.log(Level.FINE,
                "Source object is cloneable, yet it does not have a public no argument method 'clone'", e);
    }

    // does it have a copy constructor?
    Constructor copyConstructor = ConstructorUtils.getAccessibleConstructor(source.getClass(),
            source.getClass());
    if (copyConstructor != null) {
        try {
            return (T) copyConstructor.newInstance(source);
        } catch (Exception e) {
            LOGGER.log(Level.FINE, "Source has a copy constructor, but it failed, skipping to XStream", e);
        }
    }

    if (source instanceof Serializable) {
        return (T) SerializationUtils.clone((Serializable) source);
    } else {
        XStreamPersister persister = XSTREAM_PERSISTER_FACTORY.createXMLPersister();
        XStream xs = persister.getXStream();
        String xml = xs.toXML(source);
        T copy = (T) xs.fromXML(xml);
        return copy;
    }
}

From source file:org.geoserver.cluster.integration.IntegrationTestsUtils.java

/**
 * Equalizes two GeoServer instances, the first instance will be used as reference.
 *///from ww  w .j a v  a2s.c  o  m
public static void equalize(GeoServerInstance instanceA, GeoServerInstance instanceB) {
    // get the differences between the two instances
    List<InfoDiff> differences = differences(instanceA, instanceB);
    // equalize each difference
    for (InfoDiff difference : differences) {
        Info infoA = difference.getInfoA();
        Info infoB = difference.getInfoB();
        if (infoA == null) {
            // this info doesn't exists in the reference instance, so it needs to be removed
            remove(instanceB.getGeoServer(), instanceB.getCatalog(), infoB);
        } else if (infoB == null) {
            // this info exists only in the reference instance so it needs to be added
            add(instanceB.getGeoServer(), instanceB.getCatalog(), (Info) SerializationUtils.clone(infoA));
        } else {
            // this info exists in both instances but is different
            save(instanceB.getGeoServer(), instanceB.getCatalog(), ModificationProxy.unwrap(infoA),
                    ModificationProxy.unwrap(infoB));
        }
    }
}

From source file:org.geoserver.cluster.integration.IntegrationTestsUtils.java

/**
 * Updates the second info values using the first info values. Values are cloned when possible.
 *//*from w  ww .  j ava 2s. c  o m*/
private static <U> U updateInfoImpl(Info infoA, Info infoB, Class<U> type) {
    // make sure that we are dealing with infos that are compatible
    if (!type.isAssignableFrom(infoA.getClass()) || !type.isAssignableFrom(infoB.getClass())) {
        throw new RuntimeException(String.format(
                "Info objects should be of type '%s', but are of types '%s' and '%s'.", type.getSimpleName(),
                infoA.getClass().getSimpleName(), infoB.getClass().getSimpleName()));
    }
    // create a modification proxy for the second info
    U proxy = ModificationProxy.create(type.cast(infoB), type);
    // get infos properties
    ClassProperties properties = OwsUtils.getClassProperties(type);
    // update every property of the second info using first info value
    for (String propertyName : properties.properties()) {
        try {
            // get first info value for the current property
            Object propertyValue = OwsUtils.get(infoA, propertyName);
            if (propertyValue instanceof Info) {
                // we are dealing with an info object, check that both properties are compatible
                Object otherPropertyValue = OwsUtils.get(infoB, propertyName);
                if (otherPropertyValue instanceof Info) {
                    // recursively update this info
                    propertyValue = updateInfoImpl((Info) propertyValue, (Info) otherPropertyValue,
                            getInfoInterface(propertyValue.getClass()));
                }
            }
            // if the property value is not a info clone it if possible
            if (propertyValue instanceof Serializable && !(propertyValue instanceof Proxy)) {
                propertyValue = SerializationUtils.clone((Serializable) propertyValue);
            }
            // update second info value
            OwsUtils.set(proxy, propertyName, propertyValue);
        } catch (IllegalArgumentException exception) {
            // ignore non existing property
            LOGGER.log(Level.FINE, String.format("Error setting property '%s'.", propertyName), exception);
        }
    }
    // return modification proxy of second info
    return proxy;
}

From source file:org.geoserver.security.config.BaseSecurityNamedServiceConfig.java

@Override
public SecurityConfig clone(boolean allowEnvParametrization) {

    final GeoServerEnvironment gsEnvironment = GeoServerExtensions.bean(GeoServerEnvironment.class);

    BaseSecurityNamedServiceConfig target = (BaseSecurityNamedServiceConfig) SerializationUtils.clone(this);

    if (target != null) {
        if (allowEnvParametrization && gsEnvironment != null
                && GeoServerEnvironment.ALLOW_ENV_PARAMETRIZATION) {
            target.setName((String) gsEnvironment.resolveValue(name));
        }//from   www  .  j a v  a 2  s  .  com
    }

    return target;
}

From source file:org.geoserver.security.config.SecurityManagerConfig.java

@Override
public SecurityConfig clone(boolean allowEnvParametrization) {

    final GeoServerEnvironment gsEnvironment = GeoServerExtensions.bean(GeoServerEnvironment.class);

    SecurityManagerConfig target = (SecurityManagerConfig) SerializationUtils.clone(this);

    if (target != null) {
        if (allowEnvParametrization && gsEnvironment != null
                && GeoServerEnvironment.ALLOW_ENV_PARAMETRIZATION) {
            target.setConfigPasswordEncrypterName(
                    (String) gsEnvironment.resolveValue(configPasswordEncrypterName));
            target.setRoleServiceName((String) gsEnvironment.resolveValue(roleServiceName));
        }//from   w  ww  .j a  v  a 2  s. com
    }

    return target;
}

From source file:org.geoserver.security.password.MasterPasswordConfig.java

@Override
public SecurityConfig clone(boolean allowEnvParametrization) {

    final GeoServerEnvironment gsEnvironment = GeoServerExtensions.bean(GeoServerEnvironment.class);

    MasterPasswordConfig target = (MasterPasswordConfig) SerializationUtils.clone(this);

    if (target != null) {
        if (allowEnvParametrization && gsEnvironment != null
                && GeoServerEnvironment.ALLOW_ENV_PARAMETRIZATION) {
            target.setProviderName((String) gsEnvironment.resolveValue(providerName));
        }/*from   www  .  j  ava  2  s  . c  o m*/
    }

    return target;
}

From source file:org.jahia.services.search.SearchCriteriaSerializationTest.java

/**
 * Tests the serialization/deserialization of the {@link SearchCriteria} object.
 *//*from w ww  .  j a v a 2  s  . com*/
@Test
public void testSerialization() {
    SerializationUtils.clone(new SearchCriteria());
}

From source file:org.jahia.taglibs.search.SuggestionsTag.java

@Override
public int doStartTag() throws JspException {
    int retVal = super.doStartTag();

    if (retVal == SKIP_BODY && !runQuery) {
        retVal = EVAL_BODY_INCLUDE;//from  ww  w . j a  va 2  s  .co m
    } else if (retVal == EVAL_BODY_INCLUDE) {
        final Object countVarValue = pageContext.getAttribute(getCountVar());
        int count = countVarValue == null ? 0 : (Integer) countVarValue;
        List<String> allSuggestions = suggestion.getAllSuggestions();
        int iterationCount = 1;
        while (count == 0 && iterationCount < allSuggestions.size()) {
            SearchCriteria criteria = (SearchCriteria) pageContext.getAttribute(getSearchCriteriaVar());
            SearchCriteria suggestedCriteria = (SearchCriteria) SerializationUtils.clone(criteria);
            suggestedCriteria.getTerms().get(0).setTerm(allSuggestions.get(iterationCount));

            count = searchAndSetAttributes(suggestedCriteria, getRenderContext());
            if (count > 0) {
                suggestion.setSuggestedQuery(allSuggestions.get(iterationCount));
            }

            iterationCount++;
        }
    }

    return retVal;
}

From source file:org.jahia.taglibs.search.SuggestionsTag.java

private SearchCriteria suggest(SearchCriteria criteria) {
    SearchCriteria suggestedCriteria = null;
    if (!criteria.getTerms().isEmpty() && !criteria.getTerms().get(0).isEmpty()) {
        suggestion = ServicesRegistry.getInstance().getSearchService().suggest(criteria, getRenderContext(),
                maxTermsToSuggest);/*from w w  w  .  j  a va 2s .  c o  m*/
        if (logger.isDebugEnabled()) {
            logger.debug("Suggestion for search query '" + criteria.getTerms().get(0).getTerm() + "' site '"
                    + getRenderContext().getSite().getSiteKey() + "' and locale "
                    + getRenderContext().getMainResourceLocale() + ": " + suggestion);
        }
        if (suggestion != null) {
            if (suggestionVar != null) {
                pageContext.setAttribute(suggestionVar, suggestion);
            }
            if (runQuery) {
                // we've found a suggestion
                suggestedCriteria = (SearchCriteria) SerializationUtils.clone(criteria);
                suggestedCriteria.getTerms().get(0).setTerm(suggestion.getSuggestedQuery());
            }
        }
    }

    return suggestedCriteria;
}