Example usage for org.apache.commons.lang.reflect FieldUtils writeField

List of usage examples for org.apache.commons.lang.reflect FieldUtils writeField

Introduction

In this page you can find the example usage for org.apache.commons.lang.reflect FieldUtils writeField.

Prototype

public static void writeField(Object target, String fieldName, Object value) throws IllegalAccessException 

Source Link

Document

Write a public field.

Usage

From source file:com.adobe.acs.commons.mcp.impl.processes.renovator.MovingPage.java

@Override
public void move(ReplicatorQueue replicatorQueue, ResourceResolver rr)
        throws IllegalAccessException, MovingException {
    // For starters, create a page manager with a modified replicator queue
    PageManager manager = pageManagerFactory.getPageManager(rr);
    Field replicatorField = FieldUtils.getDeclaredField(manager.getClass(), "replicator", true);
    FieldUtils.writeField(replicatorField, manager, replicatorQueue);

    // Some simple transformations
    String contentPath = getSourcePath() + "/" + JcrConstants.JCR_CONTENT;
    String destinationParent = StringUtils.substringBeforeLast(getDestinationPath(), "/");

    // Attempt move operation
    try {/*  ww w . ja  v  a  2 s. c  om*/
        Actions.retry(10, 500, res -> {
            waitUntilResourceFound(res, destinationParent);
            moveOrClonePage(rr, manager, contentPath, destinationParent, res);
            movePageChildren(rr, res);
        }).accept(rr);
    } catch (Exception e) {
        throw new MovingException(getSourcePath(), e);
    }
}

From source file:com.neusoft.mid.clwapi.tools.JacksonUtils.java

/**
 * @param obj//from  w  w  w  . ja v  a  2 s.  c  o  m
 * @param f
 * @throws IllegalAccessException
 * @throws JacksonEncoderException
 */
private static Object jsonCoder(Object obj, Field f) throws IllegalAccessException, JacksonEncoderException {
    Object o = FieldUtils.readField(f, obj);
    if (o instanceof String) {
        FieldUtils.writeField(f, obj, jsonCoder((String) o, true));
    } else if (o instanceof Collection<?>) {
        logger.debug("Field [" + f.getName() + "] is " + o.getClass());
        Collection<?> c = (Collection<?>) o;
        Iterator<?> it = c.iterator();
        while (it.hasNext()) {
            jsonEncoder(it.next());
        }
    } else if (o instanceof Map<?, ?>) {
        logger.debug("Field [" + f.getName() + "] is " + o.getClass());
        Set<?> entries = ((Map<?, ?>) o).entrySet();
        Iterator<?> it = entries.iterator();
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it.next();
            logger.debug("Key is [" + entry.getKey() + "]");
            entry.setValue(jsonEncoder(entry.getValue()));
        }
    } else if (o instanceof Integer || o instanceof Byte || o instanceof Boolean || o instanceof Long
            || o instanceof Double || o instanceof Character || o instanceof Short || o instanceof Float
            || o instanceof Number) {
        return obj;
    } else {
        throw new JacksonEncoderException("??" + f.getClass());
    }
    return obj;
}

From source file:com.adobe.acs.commons.mcp.impl.processes.PageRelocator.java

@SuppressWarnings("squid:S00112")
private void movePage(ResourceResolver rr, String sourcePage) throws Exception {
    PageManager manager = pageManagerFactory.getPageManager(rr);
    Field replicatorField = FieldUtils.getDeclaredField(manager.getClass(), "replicator", true);
    FieldUtils.writeField(replicatorField, manager, replicatorQueue);
    String destination = convertSourceToDestination(sourcePage);
    String destinationParent = destination.substring(0, destination.lastIndexOf('/'));
    note(sourcePage, Report.target, destination);
    String beforeName = "";
    final long start = System.currentTimeMillis();

    String contentPath = sourcePage + "/jcr:content";
    List<String> refs = new ArrayList<>();
    List<String> publishRefs = new ArrayList<>();

    if (maxReferences != 0 && resourceExists(rr, contentPath)) {
        ReferenceSearch refSearch = new ReferenceSearch();
        refSearch.setExact(true);//from  w ww .  ja va2 s. c  o  m
        refSearch.setHollow(true);
        refSearch.setMaxReferencesPerPage(maxReferences);
        refSearch.setSearchRoot(referenceSearchRoot);
        refSearch.search(rr, sourcePath).values().stream().peek(p -> refs.add(p.getPagePath()))
                .filter(p -> isActivated(rr, p.getPagePath())).map(ReferenceSearch.Info::getPagePath)
                .collect(Collectors.toCollection(() -> publishRefs));
    }
    note(sourcePage, Report.all_references, refs.size());
    note(sourcePage, Report.published_references, publishRefs.size());

    if (!dryRun) {
        Actions.retry(10, 500, res -> {
            waitUntilResourceFound(res, destinationParent);
            Resource source = rr.getResource(sourcePage);
            if (resourceExists(res, contentPath)) {
                manager.move(source, destination, beforeName, true, true, listToStringArray(refs),
                        listToStringArray(publishRefs));
            } else {
                Map<String, Object> props = new HashMap<>();
                Resource parent = res.getResource(destinationParent);
                res.create(parent, source.getName(), source.getValueMap());
            }
            res.commit();
            res.refresh();

            source = rr.getResource(sourcePage);
            if (source != null && source.hasChildren()) {
                for (Resource child : source.getChildren()) {
                    res.move(child.getPath(), destination);
                }
                res.commit();
            }
        }).accept(rr);
    }
    long end = System.currentTimeMillis();
    note(sourcePage, Report.move_time, end - start);

}

From source file:com.haulmont.cuba.core.sys.EntityManagerImpl.java

protected <T extends Entity> T internalMerge(T entity) {
    try {/* w  w  w .  j a  v  a 2s.  c o  m*/
        CubaUtil.setSoftDeletion(false);
        CubaUtil.setOriginalSoftDeletion(false);

        UUID uuid = null;
        if (entity.getId() instanceof IdProxy) {
            uuid = ((IdProxy) entity.getId()).getUuid();
        }

        T merged = delegate.merge(entity);

        if (entity.getId() instanceof IdProxy && uuid != null
                && !uuid.equals(((IdProxy) merged.getId()).getUuid())) {
            ((IdProxy) merged.getId()).setUuid(uuid);
        }

        // copy non-persistent attributes to the resulting merged instance
        for (MetaProperty property : metadata.getClassNN(entity.getClass()).getProperties()) {
            if (metadata.getTools().isNotPersistent(property) && !property.isReadOnly()) {
                // copy using reflection to avoid executing getter/setter code
                Field field = FieldUtils.getDeclaredField(entity.getClass(), property.getName(), true);
                if (field != null) {
                    try {
                        Object value = FieldUtils.readField(field, entity);
                        if (value != null) {
                            FieldUtils.writeField(field, merged, value);
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(
                                "Error copying non-persistent attribute value to merged instance", e);
                    }
                }
            }
        }

        return merged;
    } finally {
        CubaUtil.setSoftDeletion(softDeletion);
        CubaUtil.setOriginalSoftDeletion(softDeletion);
    }
}

From source file:org.pentaho.platform.dataaccess.datasource.ui.importing.AnalysisImportDialogControllerTest.java

@Test
public void testHandleParam() throws Exception {
    final StringBuilder dsInputName = new StringBuilder("DataSource");
    final StringBuilder dsInputValue = new StringBuilder("DS &quot;Test's&quot; & <Fun>");
    final String dsExpectedValue = "DS \"Test's\" & <Fun>";

    final StringBuilder dspInputName = new StringBuilder("DynamicSchemaProcessor");
    final StringBuilder dspInputValue = new StringBuilder("DSP's & &quot;Other&quot; <stuff>");
    final String dspExpectedValueDSP = "DSP's & \"Other\" <stuff>";

    AnalysisImportDialogController controller = new AnalysisImportDialogController();
    AnalysisImportDialogModel importDialogModel = new AnalysisImportDialogModel();

    importDialogModel.setAnalysisParameters(new ArrayList<>());
    importDialogModel.setParameterMode(true);

    Field modelField = FieldUtils.getDeclaredField(AnalysisImportDialogController.class, "importDialogModel",
            true);//from w w w.jav  a  2 s.co  m
    modelField.setAccessible(true);
    FieldUtils.writeField(modelField, controller, importDialogModel);

    controller.handleParam(dsInputName, dsInputValue);
    controller.handleParam(dspInputName, dspInputValue);

    ParameterDialogModel parameterFirst = controller.getDialogResult().getAnalysisParameters().get(0);
    ParameterDialogModel parameterSecond = controller.getDialogResult().getAnalysisParameters().get(1);

    assertEquals(parameterFirst.getValue(), dsExpectedValue);
    assertEquals(parameterSecond.getValue(), dspExpectedValueDSP);
    assertEquals(controller.getDialogResult().getParameters(),
            "DataSource=\"DS &quot;Test's&quot; & <Fun>\";DynamicSchemaProcessor=\"DSP's & &quot;Other&quot; <stuff>\"");
}