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

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

Introduction

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

Prototype

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

Source Link

Document

Set the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:org.ms123.common.importing.XmlImporter.java

private Object traverseModuleTree(Object parentBean, Stack<Element> parentElementStack, String path,
        Map<String, Object> moduleMap) throws Exception {
    String entityName = (String) moduleMap.get(ENTITY);
    System.out.println("===> traverseModuleTree.parentElementStack:" + parentElementStack + "\t\t|path:" + path
            + "\t\t|parent:" + parentBean);
    Map<String, String> wiring = getWiringForPath(path);
    System.out.println("wiring:" + path + "/" + wiring);
    if (wiring == null) {
        Map<String, String> w = getWiringForPathFromBinding(path);
        if (w == null) {
            return null;
        }/*from w  ww .j  a v  a 2  s . c o m*/
        wiring = w;
    }
    String targetType = wiring.get("targetType");
    System.out.println("targetType:" + targetType);
    Object newBean = null;
    if ("list".equals(targetType)) {
        List<Map> children = (List) moduleMap.get("children");
        System.out.println("\tchildren:" + children);
        if (children.size() > 0) {
            Map<String, Object> listType = children.get(0);
            List<Map> lchildren = (List) listType.get("children");
            Map<String, String> typeMapping = getWiringForPath(path + "." + listType.get("name"));
            List<Element> childElementList = getChildElements(parentElementStack, wiring);
            System.out.println("childElementList:" + childElementList);
            if (childElementList.size() > 0) {
                Set<Object> beanList = new HashSet();
                List<Map> bindings = getBindingsForPath(path + "." + listType.get("name"));
                System.out.println("\tbindings:" + bindings);
                for (Element childElement : childElementList) {
                    parentElementStack.push(childElement);
                    Map<String, Object> tmpMap = new HashMap();
                    for (Map<String, String> binding : bindings) {
                        String value = getSourceValue(parentElementStack, binding);
                        tmpMap.put(getLastSegment(binding.get("target")), value);
                    }
                    evaluteFormulas((String) listType.get(ENTITY), tmpMap);
                    Object bean = createBean((String) listType.get(ENTITY));
                    m_objUtils.makeComplex(tmpMap, bean);
                    beanList.add(bean);
                    if (lchildren != null) {
                        for (Map child : lchildren) {
                            traverseModuleTree(bean, parentElementStack,
                                    path + "." + listType.get("name") + "." + child.get("name"), child);
                        }
                    }
                    parentElementStack.pop();
                }
                PropertyUtils.setProperty(parentBean, (String) moduleMap.get("name"), beanList);
            }
        }
    } else {
        List<Map> bindings = getBindingsForPath(path);
        Map<String, Object> tmpMap = new HashMap();
        for (Map<String, String> binding : bindings) {
            String value = getSourceValue(parentElementStack, binding);
            tmpMap.put(getLastSegment(binding.get("target")), value);
        }
        evaluteFormulas((String) moduleMap.get(ENTITY), tmpMap);
        newBean = createBean((String) moduleMap.get(ENTITY));
        m_objUtils.makeComplex(tmpMap, newBean);
        if (parentBean != null) {
            PropertyUtils.setProperty(parentBean, (String) moduleMap.get("name"), newBean);
        }
        List<Map> children = (List) moduleMap.get("children");
        if (children != null) {
            for (Map child : children) {
                traverseModuleTree(newBean, parentElementStack, path + "." + child.get("name"), child);
            }
        }
    }
    return newBean;
}

From source file:org.ms123.common.team.BaseTeamServiceImpl.java

private List<String> getChildTeamids(StoreDesc sdesc, String teamid) throws Exception {
    List<String> ret = new ArrayList();
    String filter = "teamid == '" + teamid + "'";
    Class clazz = m_nucleusService.getClass(sdesc, m_inflector.getClassName("teamintern"));
    PersistenceManager pm = m_nucleusService.getPersistenceManagerFactory(sdesc).getPersistenceManager();
    Extent e = pm.getExtent(clazz, true);
    Query q = pm.newQuery(e, filter);
    try {//from  w  ww  .  j a  va2s .  com
        Collection coll = (Collection) q.execute();
        Iterator iter = coll.iterator();
        if (iter.hasNext()) {
            Object obj = iter.next();
            Set children = (Set) PropertyUtils.getProperty(obj, "children");
            PropertyUtils.setProperty(obj, "children", new HashSet());

            System.out.println("children:" + children);
            for (Object c : children) {
                String id = (String) PropertyUtils.getProperty(c, "teamid");
                System.out.println("\tid:" + id);
                ret.add(id);
            }
        }
    } finally {
        q.closeAll();
        pm.close();
    }
    return ret;
}

From source file:org.ms123.common.workflow.TaskBaseExecutor.java

protected void setValue(DelegateExecution execution, String processvar, Object value) throws Exception {
    if (processvar.indexOf(".") == -1) {
        //log("\tProcessvar.setValue:" + processvar + " = " + value);
        execution.setVariable(processvar, value);
    }/* w w  w  .ja va2 s  . com*/
    String[] parts = processvar.split("\\.");
    Object o = execution.getVariable(parts[0]);
    //log("\tProcessvar.setValue1:" + processvar + "(" + o + "/" + parts[0] + "/" + value);
    if (o == null) {
        o = new HashMap();
        execution.setVariable(parts[0], o);
    }
    for (int i = 1; i < parts.length; i++) {
        String part = parts[i];
        if (i < (parts.length - 1)) {
            Object o1 = PropertyUtils.getProperty(o, part);
            if (o1 == null) {
                o1 = new HashMap();
                PropertyUtils.setProperty(o, part, o1);
            }
            o = o1;
        } else {
            //log("\tProcessvar.setValue2:" + processvar + "(" + o + "/" + part + "/" + value);
            PropertyUtils.setProperty(o, part, value);
        }
    }
}

From source file:org.mule.module.netsuite.api.paging.SavedRecordSearchIterable.java

private SearchRecord createAdvancedSearch() {
    SearchRecord search = recordType.newAdvancedSearchInstance();
    try {/*from   ww  w. j a v a2  s .  c  o  m*/
        PropertyUtils.setProperty(search, "savedSearchId", savedSearchId);
    } catch (Exception e) {
        throw new UnhandledException(e);
    }
    return search;
}

From source file:org.nekorp.workflow.desktop.servicio.imp.EditorMonitorImp.java

@Override
public void undo() {
    try {/*w w  w.  j a  v a 2 s  .co  m*/
        EditorLog log = getFirstValid();
        if (log == null) {
            EditorMonitorImp.LOGGER.debug("se solicita undo pero no hay nada valido para undo");
            return;
        }
        //paso las reglas asi que se quitara del queue para procesarse
        this.logEdiciones.remove(log);
        EditorLog redo = new EditorLog();
        redo.setTarget(log.getTarget());
        redo.setProperty(log.getProperty());
        redo.setOldValue(PropertyUtils.getProperty(redo.getTarget(), redo.getProperty()));
        this.redoLog.addFirst(redo);
        PropertyUtils.setProperty(log.getTarget(), log.getProperty(), log.getOldValue());
        //en teoria lo anterior deberia ser suficiente para que se actualize la vista,
        //pero existe el problema de que en el objeto log
        //no se tiene el proxy al objeto, asi que no se activan los aspectos con los updates
        //una solucion era conseguir los proxys a los objetos pero es mas simple lanzar el processModelUpdate
        //del binding manadager
        //se complica cuando otras cosas ademas del update manager observan el modelo
        //asi como este objeto no es notificado
        notificaCalculator(log);
        bindingManager.processModelUpdate(log.getTarget(), log.getProperty(), log.getOldValue());
        if (this.logEdiciones.isEmpty()) {
            this.model.setEditado(this.sinRetorno);
        }
        this.model.setClienteEditado(tieneEdicionCliente() || this.sinRetornoCliente);
        EditorMonitorImp.LOGGER.debug("se proceso undo target:" + log.getTarget() + " property:"
                + log.getProperty() + " old:" + log.getOldValue());
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        EditorMonitorImp.LOGGER.error("No se logro hacer undo", ex);
    } finally {
        this.model.setTieneRedo(this.hasRedo());
        this.model.setTieneUndo(this.hasUndo());
    }
}

From source file:org.nekorp.workflow.desktop.servicio.imp.EditorMonitorImp.java

@Override
public void redo() {
    try {/*from w  w w .ja va  2 s .co  m*/
        if (this.redoLog.isEmpty()) {
            return;
        }
        EditorLog log = this.redoLog.removeFirst();
        EditorLog undo = new EditorLog();
        undo.setTarget(log.getTarget());
        undo.setProperty(log.getProperty());
        undo.setOldValue(PropertyUtils.getProperty(undo.getTarget(), undo.getProperty()));
        this.addUndo(undo);
        PropertyUtils.setProperty(log.getTarget(), log.getProperty(), log.getOldValue());
        notificaCalculator(log);
        bindingManager.processModelUpdate(log.getTarget(), log.getProperty(), log.getOldValue());
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        EditorMonitorImp.LOGGER.error("No se logro hacer undo", ex);
    } finally {
        this.model.setTieneRedo(this.hasRedo());
        this.model.setTieneUndo(this.hasUndo());
    }
}

From source file:org.nekorp.workflow.desktop.view.resource.imp.CostoServicioTableModel.java

@Override
public void setValueAt(Object value, int row, int col) {
    //TODO esto es solo un parche
    //encontrar por que esta pidiendo actualizar una columna que ya no existe
    if (row >= this.datos.size()) {
        return;//from  w w  w  . ja  v a  2  s . c o m
    }
    try {
        if (col > 1) {
            RegistroCostoVB dato = this.datos.get(row);
            if (col == 2) {
                if (value != null) {
                    PropertyUtils.setProperty(dato, this.atributos.get(col), value);
                } else {
                    PropertyUtils.setProperty(dato, this.atributos.get(col), Integer.valueOf(0));
                }
            }
            if (col == 3 || col == 6) {
                PropertyUtils.setProperty(dato, this.atributos.get(col), MonedaVB.valueOf((String) value));
            }
            if (col == 4 || col == 9) {
                PropertyUtils.setProperty(dato, this.atributos.get(col), value);
            }
            fireTableCellUpdated(row, col);
            //columnas de utilidad 5 y subtotal 6
            //to weak code
            fireTableCellUpdated(row, 5);
            fireTableCellUpdated(row, 7);
            fireTableCellUpdated(row, 8);
            fireTableCellUpdated(row, 10);
        } else {
            RegistroCostoVB dato = this.datos.get(row);
            PropertyUtils.setProperty(dato, this.atributos.get(col), value);
            fireTableCellUpdated(row, col);
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        throw new IllegalArgumentException("Mal configurado el modelo de la tabla costos", ex);
    }
}

From source file:org.neovera.jdiablo.internal.BeanUtils.java

public static void setProperty(Object instance, String propertyName, Object value) {
    String p = propertyName;//from  ww  w  . j  av a  2 s .com
    if (p.startsWith("_")) {
        p = p.substring(1);
    }
    try {
        PropertyUtils.setProperty(instance, p, value);
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.netbeans.modeler.specification.model.document.property.ElementPropertySet.java

private void createPropertySetInternal(String groupId, final IBaseElementWidget baseElementWidget,
        final Object object, Element element, final Map<String, PropertyChangeListener> propertyChangeHandlers,
        final Map<String, PropertyVisibilityHandler> propertyVisiblityHandlers, boolean replaceProperty) {
    try {//from  w w w  . j  a v  a 2 s . c o m
        if (element != null) {
            for (final Attribute attribute : element.getAttributes()) {
                String attributeGroupId = groupId;
                if (attributeGroupId == null) {
                    attributeGroupId = attribute.getGroupId();
                }
                if (attribute.getClassType() == ITextElement.class) {
                    final String name = attribute.getName();
                    final ITextElement expression = (ITextElement) PropertyUtils.getProperty(object, name);//return must not be null//(TExpression) PropertyUtils.getProperty(object, id) == null ? new TExpression() : (TExpression) PropertyUtils.getProperty(object, id);
                    this.put(attributeGroupId,
                            new ElementCustomPropertySupport(this.getModelerFile(), expression, String.class,
                                    attribute.getId(), "content", attribute.getDisplayName(),
                                    attribute.getShortDescription(),
                                    (PropertyChangeListener<String>) (oldValue, value) -> {
                                        if (expression.getContent() == null
                                                || expression.getContent().isEmpty()) {
                                            try {
                                                PropertyUtils.setProperty(object, name, null);
                                            } catch (IllegalAccessException | InvocationTargetException
                                                    | NoSuchMethodException ex) {
                                                Exceptions.printStackTrace(ex);
                                            }
                                        }
                                        if (propertyChangeHandlers != null
                                                && propertyChangeHandlers.get(name) != null) {
                                            propertyChangeHandlers.get(name).changePerformed(oldValue, value);
                                        }
                                        if (attribute.isRefreshOnChange()) {
                                            baseElementWidget.refreshProperties();
                                        }
                                    },
                                    propertyVisiblityHandlers == null ? null
                                            : propertyVisiblityHandlers.get(attribute.getId())),
                            replaceProperty);

                } else if (Enumy.class.isAssignableFrom(attribute.getClassType())) {
                    EnumComboBoxResolver resolver = Lookup.getDefault().lookup(EnumComboBoxResolver.class);
                    this.put(attributeGroupId, resolver.getPropertySupport(modelerFile, attribute,
                            baseElementWidget, object, propertyChangeHandlers));
                } else if (Embedded.class.isAssignableFrom(attribute.getClassType())) {
                    if (attribute.getGroupId() != null) {
                        groupId = attribute.getGroupId();
                    }
                    //in embedded id is used as category
                    this.createPropertySet(groupId, attribute.getId(), baseElementWidget,
                            PropertyUtils.getSimpleProperty(object, attribute.getName()),
                            propertyChangeHandlers, propertyVisiblityHandlers, true, replaceProperty);
                } else {
                    if (attribute.isReadOnly()) {
                        String value = BeanUtils.getProperty(object, attribute.getName());
                        if (value == null) {
                            BeanUtils.setProperty(object, attribute.getName(), attribute.getValue());
                        }
                        this.put(attributeGroupId,
                                new ElementPropertySupport(object, attribute.getFieldGetter(), null, attribute),
                                replaceProperty);
                    } else {
                        PropertyVisibilityHandler propertyVisibilityHandler = propertyVisiblityHandlers == null
                                ? null
                                : propertyVisiblityHandlers.get(attribute.getId());

                        Serializable visibilityExpression = attribute.getVisibilityExpression();
                        if (propertyVisibilityHandler == null && visibilityExpression != null) {
                            propertyVisibilityHandler = createPropertyVisibilityHandler(modelerFile,
                                    baseElementWidget, object, visibilityExpression);
                        }
                        if (propertyChangeHandlers != null
                                && propertyChangeHandlers.get(attribute.getId()) == null
                                && attribute.getOnChangeEvent() != null
                                && !attribute.getOnChangeEvent().trim().isEmpty()) {
                            propertyChangeHandlers.put(attribute.getId(),
                                    createPropertyChangeHandler(modelerFile, baseElementWidget, object,
                                            attribute.getChangeListenerExpression()));
                        }
                        this.put(attributeGroupId, new ElementCustomPropertySupport(this.getModelerFile(),
                                object, attribute, (PropertyChangeListener<Object>) (oldValue, value) -> {
                                    try {
                                        if (value != null) {
                                            if (value instanceof String) {
                                                if (!((String) value).isEmpty()) {
                                                    BeanUtils.setProperty(object, attribute.getName(), value);
                                                } else {
                                                    BeanUtils.setProperty(object, attribute.getName(), null);
                                                }
                                            } else {
                                                BeanUtils.setProperty(object, attribute.getName(), value);
                                            }
                                        } else {
                                            BeanUtils.setProperty(object, attribute.getName(), null);
                                        }
                                    } catch (IllegalAccessException | InvocationTargetException ex) {
                                        Exceptions.printStackTrace(ex);
                                    }
                                    elementValueChanged(baseElementWidget, attribute, propertyChangeHandlers,
                                            oldValue, value);
                                }, propertyVisibilityHandler), replaceProperty);

                    }
                }
            }
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException
            | NoSuchFieldException ex) {
        Exceptions.printStackTrace(ex);
    }

}

From source file:org.nmrfx.processor.gui.spectra.DatasetAttributes.java

public void config(String name, Object value) {
    if (Platform.isFxApplicationThread()) {
        try {//from w  ww  . j a v  a 2 s  . com
            PropertyUtils.setSimpleProperty(this, name, value);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
            Logger.getLogger(DatasetAttributes.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        Platform.runLater(() -> {
            try {
                PropertyUtils.setProperty(this, name, value);
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
                Logger.getLogger(DatasetAttributes.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
    }
}