Example usage for org.apache.commons.beanutils PropertyUtils setSimpleProperty

List of usage examples for org.apache.commons.beanutils PropertyUtils setSimpleProperty

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils setSimpleProperty.

Prototype

public static void setSimpleProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Set the value of the specified simple property of the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:org.bitsofinfo.util.address.usps.ais.store.hbase.HBaseStore.java

@Override
public USPSRecord getByIdentifier(String identifier) throws StoreException {

    Class<? extends USPSRecord> clazz = null;
    try {// www  . jav a 2s. c o m
        clazz = uspsIdGenerator.getRecordType(identifier);
    } catch (Exception e) {
        throw new StoreException("Error translating identifier into a target table type: " + identifier, e);
    }

    HTable table = getTable(clazz);
    if (table == null) {
        throw new StoreException("No target table exists for searching by identifier of " + identifier, null);
    }

    // lets create a get for the KV lookup
    Get g = new Get(Bytes.toBytes(identifier));

    Result result = null;
    try {
        // exec the get
        result = table.get(g);
    } catch (Exception e) {
        throw new StoreException("There was an unexpected error fetching by identifier: " + identifier, e);
    }

    // not found??
    if (result == null) {
        return null;
    }

    // create a dummy record
    USPSRecord record = null;
    try {
        record = clazz.newInstance();
    } catch (Exception e) {
        throw new StoreException("Error constructing target object for class: " + clazz.getName(), e);
    }

    // get all columns
    Field[] columns = getFields(clazz);

    // family as bytes
    byte[] datacols = Bytes.toBytes(DATA_COL_FAMILY);

    // map to the properties
    for (Field column : columns) {
        byte[] bc = Bytes.toBytes(column.getName());
        byte[] colVal = result.getValue(datacols, bc);
        if (colVal != null) {
            try {
                Object trueValue;

                // convert the copyright into the object
                if (column.getType() == Copyright.class) {
                    record.setCopyright(getCopyright(new String(colVal)));

                } else {
                    trueValue = ConvertUtils.convert(new String(colVal), column.getType());
                    PropertyUtils.setSimpleProperty(record, column.getName(), trueValue);
                }

            } catch (Exception e) {
                throw new StoreException("Error setting property for column: " + column.getName()
                        + " with value " + new String(colVal), e);
            }
        }
    }

    try {
        table.close();
    } catch (Exception e) {
        throw new StoreException(
                "Error closing table, when reading by identifier from target table: " + identifier, e);
    }

    return record;
}

From source file:org.carewebframework.ui.zk.ZKUtil.java

/**
 * Recurses over all children of specified component that implement the Disable interface or a
 * "disabled" property and enables or disables them.
 * //from  w w w.  j  ava2s .c  o m
 * @param parent Parent whose children's disable status is to be modified.
 * @param disable The disable status for the children.
 */
public static void disableChildren(Component parent, boolean disable) {
    List<Component> children = parent.getChildren();

    for (int i = children.size() - 1; i >= 0; i--) {
        Component comp = children.get(i);

        if (comp instanceof Disable) {
            ((Disable) comp).setDisabled(disable);
        } else {
            try {
                PropertyUtils.setSimpleProperty(comp, "disabled", disable);
            } catch (Exception e) {
            }
        }

        disableChildren(comp, disable);
    }
}

From source file:org.couch4j.http.DatabaseImpl.java

public DatabaseImpl(CouchDbClient couchDb, HttpConnectionManager ht, String databaseName) {
    this.couchDb = couchDb;
    this.client = ht;
    this.name = databaseName;

    this.urlResolver = new UrlBuilder(couchDb, databaseName);
    changesService = new DatabaseChangeNotificationService(ht.getHttpClient(), urlResolver, this);

    // Check if the database exists, create if not
    try {//from  w w  w  .j a  va2 s  .c  om
        if (logger.isDebugEnabled()) {
            logger.debug("Check for database named {}", databaseName);
        }
        ht.jsonGet(urlResolver.baseUrl());
    } catch (DocumentNotFoundException dnfe) {
        if (logger.isDebugEnabled()) {
            logger.debug("Database not found. Create new database '{}'", databaseName);
        }
        ht.jsonPut(urlResolver.baseUrl());
    }

    config = new JsonConfig();
    config.setPropertySetStrategy(new PropertySetStrategy() {
        @Override
        public void setProperty(Object bean, String key, Object value) throws JSONException {
            try {
                Field field = bean.getClass().getField(key);
                if (field != null)
                    field.set(bean, value);
            } catch (Exception e) {
                try {
                    PropertyUtils.setSimpleProperty(bean, key, value);
                } catch (Exception ex) {
                    // Ignore - We simply ignore attributes in the
                    // CouchDB document that are not available in the
                    // class.
                }
            }
        }
    });

    this.asyncDatabase = new AsyncDatabaseImpl(this);
}

From source file:org.dcm4che3.conf.api.generic.ReflectiveConfig.java

/**
 * Walk through the <b>from</b> object and for each field annotated with
 * /*from   w  w  w . ja  va 2  s  . c  o  m*/
 * @ConfigField, copy the value by using getter/setter to the <b>to</b>
 *               object.
 * 
 * @param from
 * @param to
 */
public static <T> void reconfigure(T from, T to) {

    // look through all fields of the config class, not including
    // superclass fields
    for (Field field : from.getClass().getDeclaredFields()) {

        // if field is not annotated, skip it
        ConfigField fieldAnno = (ConfigField) field.getAnnotation(ConfigField.class);
        if (fieldAnno == null)
            continue;

        try {

            PropertyUtils.setSimpleProperty(to, field.getName(),
                    PropertyUtils.getSimpleProperty(from, field.getName()));

        } catch (Exception e) {
            throw new RuntimeException("Unable to reconfigure a device!", e);
        }

    }

}

From source file:org.dcm4che3.conf.core.adapters.ExtensionTypeAdaptor.java

@Override
public Map<Class<?>, Object> fromConfigNode(Map<String, Object> configNode,
        AnnotatedConfigurableProperty property, BeanVitalizer vitalizer, Object parent)
        throws ConfigurationException {

    // figure out base extension class
    Class<Object> extensionBaseClass = null;
    try {//w w w.  ja  v a 2 s  .com
        extensionBaseClass = (Class<Object>) property.getTypeForGenericsParameter(1);
    } catch (ClassCastException e) {
        throw new ConfigurationException(
                "Incorrectly annotated extensions field, parameter 1 must be an extension class", e);
    }

    Map<Class<?>, Object> extensionsMap = new HashMap<Class<?>, Object>();

    for (Map.Entry<String, Object> entry : configNode.entrySet()) {
        try {

            // figure out current extension class
            List<Class<?>> extensionClasses = vitalizer.getContext(ConfigurationManager.class)
                    .getExtensionClassesByBaseClass(extensionBaseClass);
            Class<?> extensionClass = Extensions.getExtensionClassBySimpleName(entry.getKey(),
                    extensionClasses);

            // create empty extension bean
            Object extension = vitalizer.newInstance(extensionClass);

            // set parent so this field is accessible for use in extension bean's setters
            SetParentIntoField setParentIntoField = extensionBaseClass.getAnnotation(SetParentIntoField.class);
            if (setParentIntoField != null)
                try {
                    PropertyUtils.setSimpleProperty(extension, setParentIntoField.value(), parent);
                } catch (Exception e) {
                    throw new ConfigurationException(
                            "Could not 'inject' parent object into field specified by 'SetParentIntoField' annotation. Field '"
                                    + setParentIntoField.value() + "'",
                            e);
                }

            // proceed with deserialization
            new ReflectiveAdapter(extension).fromConfigNode((Map<String, Object>) entry.getValue(),
                    new AnnotatedConfigurableProperty(extensionClass), vitalizer, parent);

            extensionsMap.put(extensionClass, extension);

        } catch (ClassNotFoundException e) {
            // noop
            log.debug("Extension class {} not found", entry.getKey());
        }
    }

    return extensionsMap;
}

From source file:org.dcm4che3.conf.core.adapters.ReflectiveAdapter.java

@Override
public T fromConfigNode(Map<String, Object> configNode, AnnotatedConfigurableProperty property,
        BeanVitalizer vitalizer, Object parent) throws ConfigurationException {

    if (configNode == null)
        return null;
    Class<T> clazz = (Class<T>) property.getType();

    if (!Map.class.isAssignableFrom(configNode.getClass()))
        throw new ConfigurationException(
                "Provided configuration node is not a map (type " + clazz.getName() + ")");

    T confObj;/*  w w w  .  j  a va  2s . c o m*/
    // create instance or use provided when it was created for us
    if (providedConfObj != null)
        confObj = providedConfObj;
    else
        confObj = getRelevantConfigurableInstance(configNode, vitalizer, clazz);

    // iterate and populate annotated fields
    for (AnnotatedConfigurableProperty fieldProperty : ConfigIterators.getAllConfigurableFields(clazz))
        try {
            Object fieldValue = DefaultConfigTypeAdapters.delegateGetChildFromConfigNode(configNode,
                    fieldProperty, vitalizer, confObj);
            PropertyUtils.setSimpleProperty(confObj, fieldProperty.getName(), fieldValue);
        } catch (Exception e) {
            throw new ConfigurationException(
                    "Error while reading configuration property '" + fieldProperty.getAnnotatedName()
                            + "' (field " + fieldProperty.getName() + ") in class " + clazz.getSimpleName(),
                    e);
        }

    // iterate over setters
    for (ConfigIterators.AnnotatedSetter setter : ConfigIterators.getAllConfigurableSetters(clazz)) {
        try {
            // populate parameters for the setter
            Object[] args = new Object[setter.getParameters().size()];
            int i = 0;
            for (AnnotatedConfigurableProperty paramProperty : setter.getParameters())
                args[i++] = DefaultConfigTypeAdapters.delegateGetChildFromConfigNode(configNode, paramProperty,
                        vitalizer, confObj);

            // invoke setter
            setter.getMethod().invoke(confObj, args);
        } catch (Exception e) {
            throw new ConfigurationException("Error while trying to initialize the object with method '"
                    + setter.getMethod().getName() + "'", e);
        }
    }

    return confObj;
}

From source file:org.dcm4che3.conf.core.api.internal.ConfigReflection.java

public static void setProperty(Object object, String propertyName, Object value)
        throws ReflectionAccessException {
    try {/*  w w w . ja  v a 2s  .c  o  m*/
        PropertyUtils.setSimpleProperty(object, propertyName, value);
    } catch (IllegalAccessException e) {
        throw new ReflectionAccessException(
                "Could not set property " + propertyName + " in class " + object.getClass().toString(), e);
    } catch (InvocationTargetException e) {
        throw new ReflectionAccessException(
                "Could not set property " + propertyName + " in class " + object.getClass().toString(), e);
    } catch (NoSuchMethodException e) {
        throw new ReflectionAccessException(
                "Could not set property " + propertyName + " in class " + object.getClass().toString(), e);
    }
}

From source file:org.dcm4che3.conf.core.util.ConfigIterators.java

public static void reconfigure(Object source, Object target, Class configurableClass) {
    for (AnnotatedConfigurableProperty property : getAllConfigurableFields(configurableClass)) {
        try {//from w  w w .  j  a  va  2 s  .com
            PropertyUtils.setSimpleProperty(target, property.getName(),
                    PropertyUtils.getSimpleProperty(source, property.getName()));
        } catch (Exception e) {
            throw new RuntimeException("Unable to reconfigure instance of class " + property.getRawClass(), e);
        }
    }
}

From source file:org.dllearner.scripts.NestedCrossValidation.java

private void validate(File confFile, int outerFolds, int innerFolds, String parameter, double startValue,
        double endValue, double stepsize, boolean verbose) throws IOException, ComponentInitException {
    CLI start = new CLI(confFile);
    start.init();/*from  w  w  w  . j  a  va  2 s.com*/
    AbstractLearningProblem lp = start.getLearningProblem();
    if (!(lp instanceof PosNegLP)) {
        System.out.println("Positive only learning not supported yet.");
        System.exit(0);
    }

    // get examples and shuffle them
    LinkedList<Individual> posExamples = new LinkedList<Individual>(((PosNegLP) lp).getPositiveExamples());
    Collections.shuffle(posExamples, new Random(1));
    LinkedList<Individual> negExamples = new LinkedList<Individual>(((PosNegLP) lp).getNegativeExamples());
    Collections.shuffle(negExamples, new Random(2));

    AbstractReasonerComponent rc = start.getReasonerComponent();
    rc.init();
    String baseURI = rc.getBaseURI();

    List<TrainTestList> posLists = getFolds(posExamples, outerFolds);
    List<TrainTestList> negLists = getFolds(negExamples, outerFolds);

    // overall statistics
    Stat accOverall = new Stat();
    Stat fOverall = new Stat();
    Stat recallOverall = new Stat();
    Stat precisionOverall = new Stat();

    for (int currOuterFold = 0; currOuterFold < outerFolds; currOuterFold++) {

        logger.info("Outer fold " + currOuterFold);
        TrainTestList posList = posLists.get(currOuterFold);
        TrainTestList negList = negLists.get(currOuterFold);

        // measure relevant criterion (accuracy, F-measure) over different parameter values
        Map<Double, Stat> paraStats = new HashMap<Double, Stat>();

        for (double currParaValue = startValue; currParaValue <= endValue; currParaValue += stepsize) {

            logger.info("  Parameter value " + currParaValue + ":");
            // split train folds again (computation of inner folds for each parameter
            // value is redundant, but not a big problem)
            List<Individual> trainPosList = posList.getTrainList();
            List<TrainTestList> innerPosLists = getFolds(trainPosList, innerFolds);
            List<Individual> trainNegList = negList.getTrainList();
            List<TrainTestList> innerNegLists = getFolds(trainNegList, innerFolds);

            // measure relevant criterion for parameter (by default accuracy,
            // can also be F measure)
            Stat paraCriterionStat = new Stat();

            for (int currInnerFold = 0; currInnerFold < innerFolds; currInnerFold++) {

                logger.info("    Inner fold " + currInnerFold + ":");
                // get positive & negative examples for training run
                Set<Individual> posEx = new TreeSet<Individual>(
                        innerPosLists.get(currInnerFold).getTrainList());
                Set<Individual> negEx = new TreeSet<Individual>(
                        innerNegLists.get(currInnerFold).getTrainList());

                // read conf file and exchange options for pos/neg examples 
                // and parameter to optimise
                start = new CLI(confFile);
                start.init();
                AbstractLearningProblem lpIn = start.getLearningProblem();
                ((PosNegLP) lpIn).setPositiveExamples(posEx);
                ((PosNegLP) lpIn).setNegativeExamples(negEx);
                AbstractCELA laIn = start.getLearningAlgorithm();
                try {
                    PropertyUtils.setSimpleProperty(laIn, parameter, currParaValue);
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                    e.printStackTrace();
                }

                lpIn.init();
                laIn.init();
                laIn.start();

                // evaluate learned expression
                Description concept = laIn.getCurrentlyBestDescription();

                TreeSet<Individual> posTest = new TreeSet<Individual>(
                        innerPosLists.get(currInnerFold).getTestList());
                TreeSet<Individual> negTest = new TreeSet<Individual>(
                        innerNegLists.get(currInnerFold).getTestList());

                // true positive
                Set<Individual> posCorrect = rc.hasType(concept, posTest);
                // false negative
                Set<Individual> posError = Helper.difference(posTest, posCorrect);
                // false positive
                Set<Individual> negError = rc.hasType(concept, negTest);
                // true negative
                Set<Individual> negCorrect = Helper.difference(negTest, negError);

                //               double posErrorRate = 100*(posError.size()/posTest.size());
                //               double negErrorRate = 100*(negError.size()/posTest.size());

                double accuracy = 100 * ((double) (posCorrect.size() + negCorrect.size())
                        / (posTest.size() + negTest.size()));
                double precision = 100 * (double) posCorrect.size() / (posCorrect.size() + negError.size()) == 0
                        ? 0
                        : (posCorrect.size() + negError.size());
                double recall = 100 * (double) posCorrect.size() / (posCorrect.size() + posError.size()) == 0
                        ? 0
                        : (posCorrect.size() + posError.size());
                double fmeasure = 2 * (precision * recall) / (precision + recall) == 0 ? 0
                        : (precision + recall);

                paraCriterionStat.addNumber(accuracy);

                logger.info("      hypothesis: " + concept.toManchesterSyntaxString(baseURI, null));
                logger.info("      accuracy: " + df.format(accuracy) + "%");
                logger.info("      precision: " + df.format(precision) + "%");
                logger.info("      recall: " + df.format(recall) + "%");
                logger.info("      F measure: " + df.format(fmeasure) + "%");

                if (verbose) {
                    logger.info("      false positives (neg. examples classified as pos.): "
                            + formatIndividualSet(posError, baseURI));
                    logger.info("      false negatives (pos. examples classified as neg.): "
                            + formatIndividualSet(negError, baseURI));
                }
            }

            paraStats.put(currParaValue, paraCriterionStat);
            Stat globalParaStat = globalParaStats.get(currParaValue);
            if (globalParaStat == null) {
                globalParaStat = new Stat();
                globalParaStats.put(currParaValue, globalParaStat);
            }
            globalParaStat.add(paraCriterionStat);
        }

        // decide for the best parameter
        logger.info("    Summary over parameter values:");
        double bestPara = startValue;
        double bestValue = Double.NEGATIVE_INFINITY;
        for (Entry<Double, Stat> entry : paraStats.entrySet()) {
            double para = entry.getKey();
            Stat stat = entry.getValue();
            logger.info("      value " + para + ": " + stat.prettyPrint("%"));
            if (stat.getMean() > bestValue) {
                bestPara = para;
                bestValue = stat.getMean();
            }
        }
        logger.info("      selected " + bestPara + " as best parameter value (criterion value "
                + df.format(bestValue) + "%)");
        logger.info("    Learn on Outer fold:");

        // start a learning process with this parameter and evaluate it on the outer fold
        start = new CLI(confFile);
        start.init();
        AbstractLearningProblem lpOut = start.getLearningProblem();
        ((PosNegLP) lpOut)
                .setPositiveExamples(new TreeSet<Individual>(posLists.get(currOuterFold).getTrainList()));
        ((PosNegLP) lpOut)
                .setNegativeExamples(new TreeSet<Individual>(negLists.get(currOuterFold).getTrainList()));
        AbstractCELA laOut = start.getLearningAlgorithm();
        try {
            PropertyUtils.setSimpleProperty(laOut, parameter, bestPara);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }

        lpOut.init();
        laOut.init();
        laOut.start();

        // evaluate learned expression
        Description concept = laOut.getCurrentlyBestDescription();

        TreeSet<Individual> posTest = new TreeSet<Individual>(posLists.get(currOuterFold).getTestList());
        TreeSet<Individual> negTest = new TreeSet<Individual>(negLists.get(currOuterFold).getTestList());

        AbstractReasonerComponent rs = start.getReasonerComponent();
        // true positive
        Set<Individual> posCorrect = rs.hasType(concept, posTest);
        // false negative
        Set<Individual> posError = Helper.difference(posTest, posCorrect);
        // false positive
        Set<Individual> negError = rs.hasType(concept, negTest);
        // true negative
        Set<Individual> negCorrect = Helper.difference(negTest, negError);

        double accuracy = 100
                * ((double) (posCorrect.size() + negCorrect.size()) / (posTest.size() + negTest.size()));
        double precision = 100 * (double) posCorrect.size() / (posCorrect.size() + negError.size());
        double recall = 100 * (double) posCorrect.size() / (posCorrect.size() + posError.size());
        double fmeasure = 2 * (precision * recall) / (precision + recall);

        logger.info("      hypothesis: " + concept.toManchesterSyntaxString(baseURI, null));
        logger.info("      accuracy: " + df.format(accuracy) + "%");
        logger.info("      precision: " + df.format(precision) + "%");
        logger.info("      recall: " + df.format(recall) + "%");
        logger.info("      F measure: " + df.format(fmeasure) + "%");

        if (verbose) {
            logger.info("      false positives (neg. examples classified as pos.): "
                    + formatIndividualSet(posError, baseURI));
            logger.info("      false negatives (pos. examples classified as neg.): "
                    + formatIndividualSet(negError, baseURI));
        }

        // update overall statistics
        accOverall.addNumber(accuracy);
        fOverall.addNumber(fmeasure);
        recallOverall.addNumber(recall);
        precisionOverall.addNumber(precision);

        // free memory
        rs.releaseKB();
    }

    globalAcc.add(accOverall);
    globalF.add(fOverall);
    globalPrecision.add(precisionOverall);
    globalRecall.add(recallOverall);

    // overall statistics
    logger.info("*******************");
    logger.info("* Overall Results *");
    logger.info("*******************");
    logger.info("accuracy: " + accOverall.prettyPrint("%"));
    logger.info("F measure: " + fOverall.prettyPrint("%"));
    logger.info("precision: " + precisionOverall.prettyPrint("%"));
    logger.info("recall: " + recallOverall.prettyPrint("%"));
}

From source file:org.intermine.dwr.AjaxServices.java

/**
 * Update with the value given in input the field of the previous template
 * saved into the session//from w w  w. j  a v a 2 s . com
 * @param field the field to update
 * @param value the value
 */
public void updateTemplate(String field, String value) {
    HttpSession session = WebContextFactory.get().getSession();
    boolean isNewTemplate = (session.getAttribute(Constants.NEW_TEMPLATE) != null) ? true : false;
    TemplateQuery templateQuery = (TemplateQuery) SessionMethods.getQuery(session);
    if (!isNewTemplate && session.getAttribute(Constants.PREV_TEMPLATE_NAME) == null) {
        session.setAttribute(Constants.PREV_TEMPLATE_NAME, templateQuery.getName());
    }
    try {
        PropertyUtils.setSimpleProperty(templateQuery, field, value);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}