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

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

Introduction

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

Prototype

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

Source Link

Document

Writes a Field .

Usage

From source file:com.astamuse.asta4d.data.InjectUtil.java

/**
 * Set the value of all the fields marked by {@link ContextData} of the given instance.
 * /*from   w w  w  .  j a v  a2  s.  c om*/
 * @param instance
 * @throws DataOperationException
 */
public final static void injectToInstance(Object instance) throws DataOperationException {

    InstanceWireTarget target = getInstanceTarget(instance);

    for (FieldInfo fi : target.setFieldList) {
        try {
            ContextDataHolder valueHolder = null;
            if (fi.isContextDataHolder) {
                valueHolder = (ContextDataHolder) FieldUtils.readField(fi.field, instance);
            }
            if (valueHolder == null) {
                valueHolder = fi.createDataHolderInstance();
            }
            Class searchType = valueHolder.getTypeCls();
            if (searchType == null) {
                throw new DataOperationException(fi.field.getName()
                        + " should be initialized at first or we can not retrieve the type you want since it is a type of CotnextDataHolder. "
                        + "You can also define an extended class to return the type class, in this case, you do not need to initialized it by your self");
            }
            ContextDataHolder foundData = findValueForTarget(fi, searchType);

            handleTypeUnMatch(instance, fi, foundData);

            if (fi.isContextDataHolder) {
                transferDataHolder(foundData, valueHolder);
                FieldUtils.writeField(fi.field, instance, valueHolder, true);
            } else {
                FieldUtils.writeField(fi.field, instance, foundData.getValue(), true);
            }
        } catch (IllegalAccessException | IllegalArgumentException | InstantiationException e) {
            throw new DataOperationException("Exception when inject value to " + fi.field.toString(), e);
        }

    }

    for (MethodInfo mi : target.setMethodList) {
        try {
            ContextDataHolder valueHolder = mi.createDataHolderInstance();
            Class searchType = valueHolder.getTypeCls();
            if (searchType == null) {
                throw new DataOperationException(mi.method.getName() + " cannot initialize an instance of "
                        + valueHolder.getClass().getName()
                        + ". You should define an extended class to return the type class");
            }
            ContextDataHolder foundData = findValueForTarget(mi, searchType);
            handleTypeUnMatch(instance, mi, foundData);
            if (mi.isContextDataHolder) {
                transferDataHolder(foundData, valueHolder);
                mi.method.invoke(instance, valueHolder);
            } else {
                mi.method.invoke(instance, foundData.getValue());
            }
        } catch (IllegalAccessException | IllegalArgumentException | InstantiationException
                | InvocationTargetException e) {
            throw new DataOperationException("Exception when inject value to " + mi.method.toString(), e);
        }
    }

}

From source file:com.epam.jdi.uitests.mobile.appium.elements.complex.table.EntityTable.java

private void setEntityField(E entity, Field[] fields, String fieldName, String value) {
    Optional<Field> opt = Arrays.stream(fields).filter(f -> f.getName().equalsIgnoreCase(fieldName))
            .findFirst();//from w w  w .  j a va 2  s. co m

    if (!opt.isPresent()) {
        return;
    }

    Field field = opt.get();

    try {
        FieldUtils.writeField(field, entity, ReflectionUtils.convertStringToType(value, field), true);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.anrisoftware.globalpom.reflection.beans.BeanAccessImpl.java

private void setValueToField(Object value, Field field, Object bean) {
    try {//from   www. jav a 2 s.  com
        FieldUtils.writeField(field, bean, value, true);
    } catch (IllegalAccessException e) {
        throw log.illegalAccessError(e, fieldName, bean);
    }
}

From source file:com.hurence.logisland.util.kura.Metrics.java

public static <T> T readFrom(final T object, final Map<String, Object> metrics) {
    Objects.requireNonNull(object);

    for (final Field field : FieldUtils.getFieldsListWithAnnotation(object.getClass(), Metric.class)) {
        final Metric m = field.getAnnotation(Metric.class);
        final boolean optional = field.isAnnotationPresent(Optional.class);

        final Object value = metrics.get(m.value());
        if (value == null && !optional) {
            throw new IllegalArgumentException(
                    String.format("Field '%s' is missing metric '%s'", field.getName(), m.value()));
        }/*from w  w w  . j av a 2s  .  c o  m*/

        if (value == null) {
            // not set but optional
            continue;
        }

        try {
            FieldUtils.writeField(field, object, value, true);
        } catch (final IllegalArgumentException e) {
            // provide a better message
            throw new IllegalArgumentException(String.format("Failed to assign '%s' (%s) to field '%s'", value,
                    value.getClass().getName(), field.getName()), e);
        } catch (final IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    for (final Method method : MethodUtils.getMethodsListWithAnnotation(object.getClass(), Metric.class)) {
        final Metric m = method.getAnnotation(Metric.class);
        final boolean optional = method.isAnnotationPresent(Optional.class);

        final Object value = metrics.get(m.value());
        if (value == null && !optional) {
            throw new IllegalArgumentException(
                    String.format("Method '%s' is missing metric '%s'", method.getName(), m.value()));
        }

        if (value == null) {
            // not set but optional
            continue;
        }

        try {
            method.invoke(object, value);
        } catch (final IllegalArgumentException e) {
            // provide a better message
            throw new IllegalArgumentException(String.format("Failed to call '%s' (%s) with method '%s'", value,
                    value.getClass().getName(), method.getName()), e);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    return object;
}

From source file:com.mh.commons.utils.Reflections.java

/**
 * ?? trim() //from   w  ww  . j a va  2 s. co m
 * ?? trim();  ??
 * @param obj
 * @param escapeList ??trim()
 * @return
 */
public static Object trim(Object obj, List<String> escapeList) {
    if (obj == null)
        return null;
    try {
        Field[] fields = obj.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                if (field.getModifiers() < 15 && field.getType().toString().equals("class java.lang.String")) {
                    Object val = FieldUtils.readField(field, obj, true);
                    if (val != null) {
                        if (escapeList != null && escapeList.indexOf(field.getName()) != -1)
                            continue;
                        FieldUtils.writeField(field, obj, val.toString().trim(), true);
                    }
                }
            }
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return obj;
}

From source file:io.fares.bind.xjc.plugins.substitution.SubstitutionPlugin.java

@Override
public boolean run(Outline outline, Options opt, ErrorHandler errorHandler) throws SAXException {

    for (ClassOutline classOutline : outline.getClasses()) {
        // now in part 2 of the transformation we need to traverse the generated field declarations
        // find our plugin customization and swap @XmlElement for @XmlElementRef
        for (FieldOutline fieldOutline : classOutline.getDeclaredFields()) {

            // REVIEW AV: This does not feel quite right. You create a CElementPropertyInfo property
            // but then hack it to use another annotation. This is not good since your generated code does
            // not represent your model anymore. This may cause problem to other tools/plugins.
            CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();

            // check field property customization
            boolean hasHeadRef = Customisation.hasCustomizationsInProperty(propertyInfo,
                    SUBSTITUTION_HEAD_REF_NAME);
            // FIXME should not need to do this here but customization gets mixed up when we replace the Ref with
            //       Element field in the model transformation.
            hasHeadRef = Customisation.hasCustomizationsInProperty(propertyInfo, SUBSTITUTION_HEAD_NAME)
                    || hasHeadRef;//  w w  w .j  a  v  a  2s  . co  m

            // check if the referenced type is the subsctitution head
            // FIXME currently only able to add the customization on the complexType and not the element
            boolean hasHead = false;

            for (CTypeInfo typeInfo : propertyInfo.ref()) {
                hasHead = hasHead || Customisation.hasCustomizationsInType(typeInfo, SUBSTITUTION_HEAD_NAME);
            }

            if (hasHeadRef || hasHead) {

                // can be changed to containsKey and getKey
                for (JFieldVar field : classOutline.ref.fields().values()) {

                    if (propertyInfo.getName(false).equals(field.name())) {

                        JFieldVar jFieldVar = classOutline.ref.fields().get(propertyInfo.getName(false));

                        for (JAnnotationUse annotation : jFieldVar.annotations()) {
                            JClass acl = annotation.getAnnotationClass();
                            if (XmlElement.class.getName().equals(acl.fullName())) {
                                try {
                                    // swap XmlElement for XmlElementRef
                                    FieldUtils.writeField(annotation, "clazz",
                                            outline.getCodeModel().ref(XmlElementRef.class), true);
                                    // TODO inspect params to make sure we don't transfer [nillable|defaultValue]
                                } catch (IllegalAccessException e) {
                                    errorHandler.error(new SAXParseException(
                                            "The substitution plugin is prevented from modifying an inaccessible field in the XJC model (generation time only). Please ensure your security manager is configured correctly.",
                                            propertyInfo.getLocator(), e));
                                    return false;
                                } catch (IllegalArgumentException e) {
                                    errorHandler.error(new SAXParseException(
                                            "The substitution plugin encountered an internal error extracting the generated field details.",
                                            propertyInfo.getLocator(), e));
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return true;
}

From source file:com.taobao.android.builder.tasks.manager.MtlBaseTaskAction.java

protected void setFieldValueByReflection(Task task, String fieldName, Object value) {
    Field field = FieldUtils.getField(task.getClass(), fieldName, true);
    if (null == field) {
        throw new StopExecutionException(
                "The field with name:" + fieldName + " does not existed in class:" + task.getClass().getName());
    }//ww w .j av  a 2 s .c o  m
    try {
        FieldUtils.writeField(field, task, value, true);
    } catch (IllegalAccessException e) {
        throw new StopExecutionException(e.getMessage());
    }
}

From source file:com.taobao.android.builder.tasks.bundle.MergeAwbResourceConfigAction.java

@Override
public void execute(CachedMergeResources mergeResourcesTask) {
    VariantScope scope = variantContext.getScope();
    final BaseVariantData<? extends BaseVariantOutputData> variantData = scope.getVariantData();
    final AndroidConfig extension = scope.getGlobalScope().getExtension();
    //final VariantConfiguration variantConfig = variantData.getVariantConfiguration();

    mergeResourcesTask.setMinSdk(variantData.getVariantConfiguration().getMinSdkVersion().getApiLevel());

    mergeResourcesTask.setAndroidBuilder(scope.getGlobalScope().getAndroidBuilder());
    mergeResourcesTask.setVariantName(scope.getVariantConfiguration().getFullName());
    GlobalScope globalScope = scope.getGlobalScope();
    mergeResourcesTask.setIncrementalFolder(scope.getIncrementalDir(getName()));

    try {//from  w w  w.  j  a  v  a2  s .  c  o m
        FieldUtils.writeField(mergeResourcesTask, "variantScope", scope, true);
    } catch (IllegalAccessException e) {
        throw new GradleException("exception", e);
    }

    // Libraries use this task twice, once for compilation (with dependencies),
    // where blame is useful, and once for packaging where it is not.
    if (includeDependencies) {
        mergeResourcesTask.setBlameLogFolder(scope.getResourceBlameLogDir());
    } else {
        //            if (variantContext instanceof AppVariantContext) {
        //                mergeResourcesTask.setBlameLogFolder(((AppVariantContext) variantContext).getAwbBlameLogFolder(awbBundle));
        //            }
    }

    //mergeResourcesTask.setProcess9Patch(process9Patch);
    mergeResourcesTask.setCrunchPng(extension.getAaptOptions().getCruncherEnabled());

    VectorDrawablesOptions vectorDrawablesOptions = variantData.getVariantConfiguration().getMergedFlavor()
            .getVectorDrawables();

    Set<String> generatedDensities = vectorDrawablesOptions.getGeneratedDensities();

    mergeResourcesTask
            .setGeneratedDensities(Objects.firstNonNull(generatedDensities, Collections.<String>emptySet()));

    mergeResourcesTask.setDisableVectorDrawables(vectorDrawablesOptions.getUseSupportLibrary()
            || mergeResourcesTask.getGeneratedDensities().isEmpty());
    //mergeResourcesTask.setUseNewCruncher(extension.getAaptOptions().getUseNewCruncher());
    final boolean validateEnabled = AndroidGradleOptions
            .isResourceValidationEnabled(scope.getGlobalScope().getProject());
    mergeResourcesTask.setValidateEnabled(validateEnabled);
    ConventionMappingHelper.map(mergeResourcesTask, "inputResourceSets", new Callable<List<ResourceSet>>() {

        @Override
        public List<ResourceSet> call() throws Exception {
            List<ResourceSet> resourceSets = Lists.newArrayList();
            List<? extends AndroidLibrary> bundleDeps = awbBundle.getAndroidLibraries();
            // the list of dependency must be reversed to use the right overlay order.
            for (int n = bundleDeps.size() - 1; n >= 0; n--) {
                AndroidLibrary dependency = bundleDeps.get(n);

                File resFolder = dependency.getResFolder();
                if (resFolder.isDirectory()) {
                    ResourceSet resourceSet = new ResourceSet(dependency.getFolder().getName(), true);
                    resourceSet.addSource(resFolder);
                    resourceSets.add(resourceSet);
                }
            }

            File awbResourceFolder = awbBundle.getAndroidLibrary().getResFolder();
            if (awbResourceFolder.isDirectory()) {
                ResourceSet resourceSet = new ResourceSet(awbBundle.getAndroidLibrary().getFolder().getName(),
                        true);
                resourceSet.addSource(awbResourceFolder);
                resourceSets.add(resourceSet);
            }

            return resourceSets;
        }
    });

    mergeResourcesTask.setOutputDir(variantContext.getMergeResources(awbBundle));
    mergeResourcesTask.setGeneratedPngsOutputDir(variantContext.getPngsOutputDir(awbBundle));

    mergeResourcesTask.setAwbBundle(awbBundle);
    //        if (variantContext instanceof AppVariantContext) {
    //            AppVariantContext appVariantContext = (AppVariantContext) variantContext;
    //            appVariantContext.getAwbMergeResourceTasks().put(awbBundle.getName(), mergeResourcesTask);
    //        }
}

From source file:com.taobao.android.builder.tasks.app.merge.bundle.MergeAwbResourceConfigAction.java

@Override
public void execute(CachedMergeResources mergeResourcesTask) {
    VariantScope scope = variantContext.getScope();
    final BaseVariantData<? extends BaseVariantOutputData> variantData = scope.getVariantData();
    final AndroidConfig extension = scope.getGlobalScope().getExtension();
    //final VariantConfiguration variantConfig = variantData.getVariantConfiguration();

    mergeResourcesTask.setMinSdk(variantData.getVariantConfiguration().getMinSdkVersion().getApiLevel());

    mergeResourcesTask.setAndroidBuilder(scope.getGlobalScope().getAndroidBuilder());
    mergeResourcesTask.setVariantName(scope.getVariantConfiguration().getFullName());
    GlobalScope globalScope = scope.getGlobalScope();
    mergeResourcesTask.setIncrementalFolder(scope.getIncrementalDir(getName()));

    try {/*from  ww w.j  a  v a 2 s .  c  o m*/
        FieldUtils.writeField(mergeResourcesTask, "variantScope", scope, true);
    } catch (IllegalAccessException e) {
        throw new GradleException("exception", e);
    }

    // Libraries use this task twice, once for compilation (with dependencies),
    // where blame is useful, and once for packaging where it is not.
    if (includeDependencies) {
        mergeResourcesTask.setBlameLogFolder(scope.getResourceBlameLogDir());
    } else {
        //            if (variantContext instanceof AppVariantContext) {
        //                mergeResourcesTask.setBlameLogFolder(((AppVariantContext) variantContext).getAwbBlameLogFolder(awbBundle));
        //            }
    }

    //mergeResourcesTask.setProcess9Patch(process9Patch);
    mergeResourcesTask.setCrunchPng(extension.getAaptOptions().getCruncherEnabled());
    mergeResourcesTask.setProcessResources(true);

    VectorDrawablesOptions vectorDrawablesOptions = variantData.getVariantConfiguration().getMergedFlavor()
            .getVectorDrawables();

    Set<String> generatedDensities = vectorDrawablesOptions.getGeneratedDensities();

    mergeResourcesTask
            .setGeneratedDensities(Objects.firstNonNull(generatedDensities, Collections.<String>emptySet()));

    mergeResourcesTask.setDisableVectorDrawables(vectorDrawablesOptions.getUseSupportLibrary()
            || mergeResourcesTask.getGeneratedDensities().isEmpty());
    //mergeResourcesTask.setUseNewCruncher(extension.getAaptOptions().getUseNewCruncher());
    final boolean validateEnabled = AndroidGradleOptions
            .isResourceValidationEnabled(scope.getGlobalScope().getProject());
    mergeResourcesTask.setValidateEnabled(validateEnabled);
    ConventionMappingHelper.map(mergeResourcesTask, "inputResourceSets", new Callable<List<ResourceSet>>() {

        @Override
        public List<ResourceSet> call() throws Exception {
            List<ResourceSet> resourceSets = Lists.newArrayList();
            List<? extends AndroidLibrary> bundleDeps = awbBundle.getAndroidLibraries();
            // the list of dependency must be reversed to use the right overlay order.
            for (int n = bundleDeps.size() - 1; n >= 0; n--) {
                AndroidLibrary dependency = bundleDeps.get(n);

                File resFolder = dependency.getResFolder();
                if (resFolder.isDirectory()) {
                    ResourceSet resourceSet = new ResourceSet(dependency.getFolder().getName(), true);
                    resourceSet.addSource(resFolder);
                    resourceSets.add(resourceSet);
                }
            }

            File awbResourceFolder = awbBundle.getAndroidLibrary().getResFolder();
            if (awbResourceFolder.isDirectory()) {
                ResourceSet resourceSet = new ResourceSet(awbBundle.getAndroidLibrary().getFolder().getName(),
                        true);
                resourceSet.addSource(awbResourceFolder);
                resourceSets.add(resourceSet);
            }

            return resourceSets;
        }
    });

    mergeResourcesTask.setOutputDir(variantContext.getMergeResources(awbBundle));
    mergeResourcesTask.setGeneratedPngsOutputDir(variantContext.getPngsOutputDir(awbBundle));

    mergeResourcesTask.setAwbBundle(awbBundle);
    //        if (variantContext instanceof AppVariantContext) {
    //            AppVariantContext appVariantContext = (AppVariantContext) variantContext;
    //            appVariantContext.getAwbMergeResourceTasks().put(awbBundle.getName(), mergeResourcesTask);
    //        }
}

From source file:chibi.gemmaanalysis.cli.deprecated.ProbeMapperCli.java

/**
 * @param blatResultInputStream/* ww w. j  a  va  2  s.c  o  m*/
 * @param output
 * @return
 * @throws IOException
 * @throws SQLException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 */
public Map<String, Collection<BlatAssociation>> runOnBlatResults(InputStream blatResultInputStream,
        Writer output) throws IOException, SQLException {

    GoldenPathSequenceAnalysis goldenPathAnalysis = new GoldenPathSequenceAnalysis(this.databaseName);

    BlatResultParser brp = new BlatResultParser();
    brp.parse(blatResultInputStream);

    writeHeader(output);

    Collection<BlatResult> blatResults = brp.getResults();

    // Fill in the taxon.
    assert this.taxon != null;
    for (BlatResult blatResult : blatResults) {
        blatResult.getQuerySequence().setTaxon(taxon);
        try {
            FieldUtils.writeField(blatResult.getTargetChromosome(), "taxon", taxon, true);
            FieldUtils.writeField(blatResult.getTargetAlignedRegion().getChromosome(), "taxon", taxon, true);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    Map<String, Collection<BlatAssociation>> allRes = probeMapper.processBlatResults(goldenPathAnalysis,
            blatResults, this.config);

    printBlatAssociations(output, allRes);

    blatResultInputStream.close();
    output.close();
    return allRes;
}