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

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

Introduction

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

Prototype

public static Field getDeclaredField(Class cls, String fieldName, boolean forceAccess) 

Source Link

Document

Gets an accessible Field by name breaking scope if requested.

Usage

From source file:com.ctlts.wfaas.data.orchestrate.query.PropertyMetadata.java

public PropertyMetadata(Class<?> type, String name) {
    this.field = FieldUtils.getDeclaredField(type, name, true);
    this.descriptor = BeanUtils.getPropertyDescriptor(type, name);
}

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 {/*from  w  w w .  ja va 2 s  .  c  o  m*/
        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.taobao.android.builder.tasks.manager.transform.TransformManager.java

public static void replaceTransformTask(TransformTask transformTask, Transform newTransform) {

    Field transfromField = FieldUtils.getDeclaredField(TransformTask.class, "transform", true);
    if (null != transfromField) {
        try {// w  w  w .  j  av  a 2s. com
            transfromField.set(transformTask, newTransform);
        } catch (IllegalAccessException e) {
            throw new GradleException(e.getMessage(), e);
        }
    }
}

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 w  w .  ja v  a2s . c  om*/
        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  ww .j  ava 2  s  .  co 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:cn.teamlab.wg.framework.util.csv.CsvWriter.java

/**
 * Bean?CSV?//from   w w w  . java 2  s . c o  m
 * Bean@CsvPropAnno(index = ?)
 * @param objList
 * @return
 * @throws NoSuchMethodException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 */
public static String bean2Csv(List<?> objList) throws Exception {
    if (objList == null || objList.size() == 0) {
        return "";
    }
    TreeMap<Integer, CsvFieldBean> map = new TreeMap<Integer, CsvFieldBean>();
    Object bean0 = objList.get(0);
    Class<?> clazz = bean0.getClass();

    PropertyDescriptor[] arr = org.springframework.beans.BeanUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor p : arr) {
        String fieldName = p.getName();
        Field field = FieldUtils.getDeclaredField(clazz, fieldName, true);
        if (field == null) {
            continue;
        }

        boolean isAnno = field.isAnnotationPresent(CsvFieldAnno.class);
        if (isAnno) {
            CsvFieldAnno anno = field.getAnnotation(CsvFieldAnno.class);
            int idx = anno.index();
            map.put(idx, new CsvFieldBean(idx, anno.title(), fieldName));
        }
    }

    // CSVBuffer
    StringBuffer buff = new StringBuffer();

    // ???
    boolean withTitle = clazz.isAnnotationPresent(CsvTitleAnno.class);
    // ??csv
    if (withTitle) {
        StringBuffer titleBuff = new StringBuffer();
        for (int key : map.keySet()) {
            CsvFieldBean fieldBean = map.get(key);
            titleBuff.append(Letters.QUOTE).append(fieldBean.getTitle()).append(Letters.QUOTE);
            titleBuff.append(Letters.COMMA);
        }
        buff.append(StringUtils.chop(titleBuff.toString()));
        buff.append(Letters.LF);
        titleBuff.setLength(0);
    }

    for (Object o : objList) {
        StringBuffer tmpBuff = new StringBuffer();

        for (int key : map.keySet()) {
            CsvFieldBean fieldBean = map.get(key);

            Object val = BeanUtils.getProperty(o, fieldBean.getFieldName());
            if (val != null) {
                tmpBuff.append(Letters.QUOTE).append(val).append(Letters.QUOTE);
            } else {
                tmpBuff.append(StringUtils.EMPTY);
            }
            tmpBuff.append(Letters.COMMA);
        }

        buff.append(StringUtils.chop(tmpBuff.toString()));
        buff.append(Letters.LF);
        tmpBuff.setLength(0);
    }

    return buff.toString();
}

From source file:org.kuali.rice.krad.service.impl.KNSLegacyDataAdapterImpl.java

/**
 * @see ValueHolderFieldPair for information on why we need to do field sychronization related to weaving
 *//*from w ww  .ja  v a 2 s.com*/
private void searchValueHolderFieldPairs(Class<?> type, List<ValueHolderFieldPair> pairs) {
    if (type.equals(Object.class)) {
        return;
    }
    for (Field valueHolderField : type.getDeclaredFields()) {
        Matcher matcher = VALUE_HOLDER_FIELD_PATTERN.matcher(valueHolderField.getName());
        if (matcher.matches()) {
            valueHolderField.setAccessible(true);
            String fieldName = matcher.group(1);
            Field valueField = FieldUtils.getDeclaredField(type, fieldName, true);
            if (valueField != null) {
                pairs.add(new ValueHolderFieldPair(valueField, valueHolderField));
            }
        }
    }
    searchValueHolderFieldPairs(type.getSuperclass(), pairs);
}

From source file:org.openengsb.core.ekb.persistence.persist.edb.TestTransformationEngine.java

@Override
public Object performTransformation(ModelDescription sourceClass, ModelDescription targetClass, Object source,
        Object target) {//w  ww  . j  a va 2  s.c om
    TestModelRegistry registry = new TestModelRegistry();
    try {
        Class<?> clazz = registry.loadModel(sourceClass);
        for (Field field : clazz.getDeclaredFields()) {
            String fieldName = field.getName();
            if (fieldName.equals(ModelUtils.MODEL_TAIL_FIELD_NAME) || fieldName.contains("LOGGER")) {
                continue;
            }
            Object value = FieldUtils.readDeclaredField(source, fieldName, true);
            if (value != null) {
                if (FieldUtils.getDeclaredField(target.getClass(), fieldName, true) == null) {
                    continue;
                }
                FieldUtils.writeDeclaredField(target, fieldName, value, true);
            }
        }
        return target;
    } catch (Exception e) {
        throw new EKBException("Unable to perform test transformation", e);
    }
}

From source file:org.pentaho.di.ui.trans.steps.fileinput.text.TextFileInputDialogTest.java

private static Field getPropsField() {
    return FieldUtils.getDeclaredField(Props.class, "props", true);
}

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);/*w w  w . j  a v a2  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>\"");
}