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

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

Introduction

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

Prototype

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

Source Link

Document

Sets the value of the (possibly nested) property of the specified name, for the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:com.rolex.explore.beanutils.service.BeanUtilsSpecificService.java

public void exploreBeanUtil() {

    SampleBean bean = new SampleBean();

    String property1 = "name";

    String property2 = "currentAddress.city";

    String property3 = "previousAddresses[0].city";

    String property4 = "previousAddresses[3].city";

    String property5 = "vehicleLicenseModel(R60)";

    Place place1 = new Place("Sentosa", "Singapore");
    Place place2 = new Place("Colombo", "Sri Lanka");
    List<Place> places = new ArrayList<Place>();
    places.add(place1);//from www  .  j a  v  a 2s  . c  o m
    places.add(place2);

    String property6 = "yearlyPlacesVisited(2000)";

    String property7 = "placesVisited";

    String property8 = "placesVisited[0]";

    TourismAward award = new TourismAward("World Award Committee", "USA");

    String property9 = "yearlyPlacesVisited(2000)[0].tourismAwards[0]";

    try {
        PropertyUtils.setSimpleProperty(bean, property1, "Rolex Rolex");
        String value1 = (String) PropertyUtils.getSimpleProperty(bean, property1);
        System.out.println("###Reverse1:   " + value1);

        PropertyUtils.setNestedProperty(bean, property2, "Hoffman Estates");
        String value2 = (String) PropertyUtils.getNestedProperty(bean, property2);
        System.out.println("###Reverse2:   " + value2);

        PropertyUtils.setNestedProperty(bean, property3, "Schaumburg");
        String value3 = (String) PropertyUtils.getNestedProperty(bean, property3);
        System.out.println("###Reverse3:   " + value3);

        PropertyUtils.setNestedProperty(bean, property4, "Des Plaines");
        String value4 = (String) PropertyUtils.getNestedProperty(bean, property4);
        System.out.println("###Reverse4:   " + value4);

        Address[] arrayValue1 = (Address[]) PropertyUtils.getSimpleProperty(bean, "previousAddresses");
        System.out.println("###ReverseArray:   " + Arrays.toString(arrayValue1));

        PropertyUtils.setMappedProperty(bean, property5, "Sonata");
        String value5 = (String) PropertyUtils.getMappedProperty(bean, property5);
        System.out.println("###Reverse5:   " + value5);

        PropertyUtils.setMappedProperty(bean, property6, places);
        List<Place> value6 = (List<Place>) PropertyUtils.getMappedProperty(bean, property6);
        System.out.println("###Reverse6:   " + value6.get(0));

        PropertyUtils.setSimpleProperty(bean, property7, places);
        List<Place> value7 = (List<Place>) PropertyUtils.getSimpleProperty(bean, property7);
        System.out.println("###Reverse7:   " + value7.get(0));

        PropertyUtils.setIndexedProperty(bean, property8, place2);
        Place value8 = (Place) PropertyUtils.getIndexedProperty(bean, property8);
        System.out.println("###Reverse8:   " + value8);

        PropertyUtils.setNestedProperty(bean, property9, award);
        TourismAward value9 = (TourismAward) PropertyUtils.getNestedProperty(bean, property9);
        System.out.println("###Reverse8:   " + value8);

    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.ctrip.infosec.rule.converter.Ip2ProvinceCityConverter.java

@Override
public void convert(PreActionEnums preAction, Map fieldMapping, RiskFact fact, String resultWrapper,
        boolean isAsync) throws Exception {
    PreActionParam[] fields = preAction.getFields();
    String ipFieldName = (String) fieldMapping.get(fields[0].getParamName());
    String ipFieldValue = valueAsString(fact.eventBody, ipFieldName);

    // prefix default value
    if (Strings.isNullOrEmpty(resultWrapper)) {
        resultWrapper = ipFieldName + "_IpArea";
    }/*from   w  w w .j a v a  2 s  .  c  om*/
    // 
    if (fact.eventBody.containsKey(resultWrapper)) {
        return;
    }

    // "8.8.8.8:80"
    ipFieldValue = StringUtils.trimToEmpty(ipFieldValue);
    ipFieldValue = StringUtils.removeStart(ipFieldValue, "\"");
    ipFieldValue = StringUtils.removeEnd(ipFieldValue, "\"");
    ipFieldValue = StringUtils.substringBefore(ipFieldValue, ":");

    if (StringUtils.isNotBlank(ipFieldValue) && !"127.0.0.1".equals(ipFieldValue)) {

        // 
        PropertyUtils.setNestedProperty(fact.eventBody, ipFieldName, ipFieldValue);

        Map params = ImmutableMap.of("ip", ipFieldValue);
        Map result = DataProxy.queryForMap(serviceName, operationName, params);
        if (result != null && !result.isEmpty()) {
            fact.eventBody.put(resultWrapper, result);
        } else {
            TraceLogger.traceLog("?. ip=" + ipFieldValue);
        }
    }
}

From source file:com.liusoft.dlog4j.search.SearchProxy.java

/**
 * //from   www.j  av  a2s. com
 * @param obj
 * @param field
 * @param value
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws IntrospectionException 
 * @throws InstantiationException 
 */
private static void setNestedProperty(Object obj, String field, Object value) throws IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, IntrospectionException, InstantiationException {
    StringTokenizer st = new StringTokenizer(field, ".");
    Class nodeClass = obj.getClass();
    StringBuffer tmp_prop = new StringBuffer();
    while (st.hasMoreElements()) {
        String f = st.nextToken();
        if (tmp_prop.length() > 0)
            tmp_prop.append('.');
        tmp_prop.append(f);
        PropertyDescriptor[] props = Introspector.getBeanInfo(nodeClass).getPropertyDescriptors();
        for (int i = 0; i < props.length; i++) {
            if (props[i].getName().equals(f)) {
                if (PropertyUtils.getNestedProperty(obj, tmp_prop.toString()) == null) {
                    nodeClass = props[i].getPropertyType();
                    PropertyUtils.setNestedProperty(obj, f, nodeClass.newInstance());
                }
                continue;
            }
        }
    }
    PropertyUtils.setNestedProperty(obj, field, value);
}

From source file:nonjsp.application.BuildComponentFromTagImpl.java

public void applyAttributesToComponentInstance(UIComponent child, Attributes attrs) {
    int attrLen, i = 0;
    String attrName, attrValue;//w  w w  . j  a  va 2 s.  c o m

    attrLen = attrs.getLength();
    for (i = 0; i < attrLen; i++) {
        attrName = mapAttrNameToPropertyName(attrs.getLocalName(i));
        attrValue = attrs.getValue(i);

        // First, try to set it as a bean property
        try {
            PropertyUtils.setNestedProperty(child, attrName, attrValue);
        } catch (NoSuchMethodException e) {
            // If that doesn't work, see if it requires special
            // treatment
            try {
                if (attrRequiresSpecialTreatment(attrName)) {
                    handleSpecialAttr(child, attrName, attrValue);
                } else {
                    // If that doesn't work, this will.
                    child.getAttributes().put(attrName, attrValue);
                }
            } catch (IllegalAccessException innerE) {
                innerE.printStackTrace();
                log.trace(innerE.getMessage());
            } catch (IllegalArgumentException innerE) {
                innerE.printStackTrace();
                log.trace(innerE.getMessage());
            } catch (InvocationTargetException innerE) {
                innerE.printStackTrace();
                log.trace(innerE.getMessage());
            } catch (NoSuchMethodException innerE) {
                innerE.printStackTrace();
                log.trace(innerE.getMessage());
            }
        } catch (IllegalArgumentException e) {
            try {
                if (attrRequiresSpecialTreatment(attrName)) {
                    handleSpecialAttr(child, attrName, attrValue);
                } else {
                    // If that doesn't work, this will.
                    child.getAttributes().put(attrName, attrValue);
                }
            } catch (IllegalAccessException innerE) {
                innerE.printStackTrace();
                log.trace(innerE.getMessage());
            } catch (IllegalArgumentException innerE) {
                innerE.printStackTrace();
                log.trace(innerE.getMessage());
            } catch (InvocationTargetException innerE) {
                innerE.printStackTrace();
                log.trace(innerE.getMessage());
            } catch (NoSuchMethodException innerE) {
                innerE.printStackTrace();
                log.trace(innerE.getMessage());
            }
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            log.trace(e.getMessage());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            log.trace(e.getMessage());
        }
    }

    // cleanup: make sure we have the necessary required attributes
    if (child.getId() == null) {
        String gId = "foo" + Util.generateId();
        child.setId(gId);
    }

}

From source file:omero.cmd.graphs.DuplicateI.java

/**
 * Duplicate model object properties, linking them as appropriate with each other and with other model objects.
 * @throws GraphException if duplication failed
 *///from  w  w  w.ja va 2 s .  co  m
private void setDuplicatePropertyValues() throws GraphException {
    /* organize duplicate index by class name and ID */
    final Map<Entry<String, Long>, IObject> duplicatesByOriginalClassAndId = new HashMap<Entry<String, Long>, IObject>();
    for (final Entry<IObject, IObject> originalAndDuplicate : originalsToDuplicates.entrySet()) {
        final IObject original = originalAndDuplicate.getKey();
        final String originalClass = Hibernate.getClass(original).getName();
        final Long originalId = original.getId();
        final IObject duplicate = originalAndDuplicate.getValue();
        duplicatesByOriginalClassAndId.put(Maps.immutableEntry(originalClass, originalId), duplicate);
    }
    /* allow lookup regardless of if original is actually a Hibernate proxy object */
    final Function<Object, Object> duplicateLookup = new Function<Object, Object>() {
        @Override
        public Object apply(Object original) {
            if (original instanceof IObject) {
                final String originalClass;
                if (original instanceof HibernateProxy) {
                    originalClass = Hibernate.getClass(original).getName();
                } else {
                    originalClass = original.getClass().getName();
                }
                final Long originalId = ((IObject) original).getId();
                return duplicatesByOriginalClassAndId.get(Maps.immutableEntry(originalClass, originalId));
            } else {
                return null;
            }
        }
    };
    /* copy property values into duplicates and link with other model objects */
    final Session session = helper.getSession();
    for (final Entry<IObject, IObject> originalAndDuplicate : originalsToDuplicates.entrySet()) {
        final IObject original = originalAndDuplicate.getKey();
        final IObject duplicate = originalAndDuplicate.getValue();
        final String originalClass = Hibernate.getClass(original).getName();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("copying properties from " + originalClass + ":" + original.getId());
        }
        try {
            /* process property values for a given object that is duplicated */
            for (final String superclassName : graphPathBean.getSuperclassesOfReflexive(originalClass)) {
                /* process property values that link from the duplicate to other model objects */
                for (final Entry<String, String> forwardLink : graphPathBean.getLinkedTo(superclassName)) {
                    /* next forward link */
                    final String linkedClassName = forwardLink.getKey();
                    final String property = forwardLink.getValue();
                    /* ignore details for now, duplicates never preserve original ownership */
                    if (property.startsWith("details.")) {
                        continue;
                    }
                    /* note which of the objects to which the original links should be ignored */
                    final Set<Long> linkedToIdsToIgnore = new HashSet<Long>();
                    for (final Entry<String, Collection<Long>> linkedToClassIds : graphTraversal
                            .getLinkeds(superclassName, property, original.getId()).asMap().entrySet()) {
                        final String linkedToClass = linkedToClassIds.getKey();
                        final Collection<Long> linkedToIds = linkedToClassIds.getValue();
                        if (classifier.getClass(
                                Class.forName(linkedToClass).asSubclass(IObject.class)) == Inclusion.IGNORE) {
                            linkedToIdsToIgnore.addAll(linkedToIds);
                        }
                    }
                    /* check for another accessor for inaccessible properties */
                    if (graphPathBean.isPropertyAccessible(superclassName, property)) {
                        /* copy the linking from the original's property over to the duplicate's */
                        Object value;
                        try {
                            value = PropertyUtils.getNestedProperty(original, property);
                        } catch (NestedNullException e) {
                            continue;
                        }
                        if (value instanceof Collection) {
                            /* if a collection property, include only the objects that aren't to be ignored */
                            final Collection<IObject> valueCollection = (Collection<IObject>) value;
                            final Collection<IObject> valueToCopy;
                            if (value instanceof List) {
                                valueToCopy = new ArrayList<IObject>();
                            } else if (value instanceof Set) {
                                valueToCopy = new HashSet<IObject>();
                            } else {
                                throw new GraphException("unexpected collection type: " + value.getClass());
                            }
                            for (final IObject linkedTo : valueCollection) {
                                if (!linkedToIdsToIgnore.contains(linkedTo.getId())) {
                                    valueToCopy.add(linkedTo);
                                }
                            }
                            value = valueToCopy;
                        } else if (value instanceof IObject) {
                            /* if the property value is to be ignored then null it */
                            if (linkedToIdsToIgnore.contains(((IObject) value).getId())) {
                                value = null;
                            }
                        }
                        /* copy the property value, replacing originals with corresponding duplicates */
                        final Object duplicateValue = GraphUtil.copyComplexValue(duplicateLookup, value);
                        try {
                            PropertyUtils.setNestedProperty(duplicate, property, duplicateValue);
                        } catch (NestedNullException e) {
                            throw new GraphException(
                                    "cannot set property " + superclassName + '.' + property + " on duplicate");
                        }
                    } else {
                        /* this could be a one-to-many property with direct accessors protected */
                        final Class<? extends IObject> linkerClass = Class.forName(superclassName)
                                .asSubclass(IObject.class);
                        final Class<? extends IObject> linkedClass = Class.forName(linkedClassName)
                                .asSubclass(IObject.class);
                        final Method reader, writer;
                        try {
                            reader = linkerClass.getMethod("iterate" + StringUtils.capitalize(property));
                            writer = linkerClass.getMethod("add" + linkedClass.getSimpleName(), linkedClass);
                        } catch (NoSuchMethodException | SecurityException e) {
                            /* no luck, so ignore this property */
                            continue;
                        }
                        /* copy the linking from the original's property over to the duplicate's */
                        final Iterator<IObject> linkedTos = (Iterator<IObject>) reader.invoke(original);
                        while (linkedTos.hasNext()) {
                            final IObject linkedTo = linkedTos.next();
                            /* copy only links to other duplicates, as otherwise we may steal objects from the original */
                            final IObject duplicateOfLinkedTo = (IObject) duplicateLookup.apply(linkedTo);
                            if (duplicateOfLinkedTo != null) {
                                writer.invoke(duplicate, duplicateOfLinkedTo);
                            }
                        }
                    }
                }
                /* process property values that link to the duplicate from other model objects */
                for (final Entry<String, String> backwardLink : graphPathBean.getLinkedBy(superclassName)) {
                    /* next backward link */
                    final String linkingClass = backwardLink.getKey();
                    final String property = backwardLink.getValue();
                    /* ignore inaccessible properties */
                    if (!graphPathBean.isPropertyAccessible(linkingClass, property)) {
                        continue;
                    }
                    for (final Entry<String, Collection<Long>> linkedFromClassIds : graphTraversal
                            .getLinkers(linkingClass, property, original.getId()).asMap().entrySet()) {
                        final String linkedFromClass = linkedFromClassIds.getKey();
                        final Collection<Long> linkedFromIds = linkedFromClassIds.getValue();
                        if (classifier.getClass(
                                Class.forName(linkedFromClass).asSubclass(IObject.class)) == Inclusion.IGNORE) {
                            /* these linkers are to be ignored */
                            continue;
                        }
                        /* load the instances that link to the original */
                        final String rootQuery = "FROM " + linkedFromClass + " WHERE id IN (:ids)";
                        for (final List<Long> idsBatch : Iterables.partition(linkedFromIds, BATCH_SIZE)) {
                            final List<IObject> linkers = session.createQuery(rootQuery)
                                    .setParameterList("ids", idsBatch).list();
                            for (final IObject linker : linkers) {
                                if (originalsToDuplicates.containsKey(linker)) {
                                    /* ignore linkers that are to be duplicated, those are handled as forward links */
                                    continue;
                                }
                                /* copy the linking from the original's property over to the duplicate's */
                                Object value;
                                try {
                                    value = PropertyUtils.getNestedProperty(linker, property);
                                } catch (NestedNullException e) {
                                    continue;
                                }
                                /* for linkers only adjust collection properties */
                                if (value instanceof Collection) {
                                    final Collection<IObject> valueCollection = (Collection<IObject>) value;
                                    final Collection<IObject> newDuplicates = new ArrayList<IObject>();
                                    for (final IObject originalLinker : valueCollection) {
                                        final IObject duplicateOfValue = originalsToDuplicates
                                                .get(originalLinker);
                                        if (duplicateOfValue != null) {
                                            /* previous had just original, now include duplicate too */
                                            newDuplicates.add(duplicateOfValue);
                                        }
                                    }
                                    valueCollection.addAll(newDuplicates);
                                }
                            }
                        }
                    }
                }
                /* process property values that do not relate to edges in the model object graph */
                for (final String property : graphPathBean.getSimpleProperties(superclassName)) {
                    /* ignore inaccessible properties */
                    if (!graphPathBean.isPropertyAccessible(superclassName, property)) {
                        continue;
                    }
                    /* copy original property value to duplicate */
                    final Object value = PropertyUtils.getProperty(original, property);
                    PropertyUtils.setProperty(duplicate, property,
                            GraphUtil.copyComplexValue(duplicateLookup, value));
                }
            }
        } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException
                | NoSuchMethodException e) {
            throw new GraphException("failed to duplicate " + originalClass + ':' + original.getId());
        }
    }
}

From source file:org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.java

/**
 * This is a util method to set a nested property of a given object. The nested property is a
 * dot separated string where each nesting level is separated by a dot. This method makes use of
 * PropertyUtils methods from apache-commons library and assumes that the field names provided in
 * the input propertyName have valid setters. eg. the propertyName sd.serdeInfo.inputFormat represents
 * the inputformat field of the serdeInfo field of the sd field. The argument bean should have these
 * fields (in this case it should be a Partition object). The value argument is the value to be set
 * for the nested field. Note that if in case of one of nested levels is null you must set
 * instantiateMissingFields argument to true otherwise this method could throw a NPE.
 *
 * @param bean the object whose nested field needs to be set. This object must have setter methods
 *             defined for each nested field name in the propertyName
 * @param propertyName the nested propertyName to be set. Each level of nesting is dot separated
 * @param value the value to which the nested property is set
 * @param instantiateMissingFields in case of some nestedFields being nulls, setting this argument
 *                                 to true will attempt to instantiate the missing fields using the
 *                                 default constructor. If there is no default constructor available this would throw a MetaException
 * @throws MetaException//from   w  ww  .  j  a  v  a  2  s. c o  m
 */
public static void setNestedProperty(Object bean, String propertyName, Object value,
        boolean instantiateMissingFields) throws MetaException {
    try {
        String[] nestedFields = propertyName.split("\\.");
        //check if there are more than one nested levels
        if (nestedFields.length > 1 && instantiateMissingFields) {
            StringBuilder fieldNameBuilder = new StringBuilder();
            //check if all the nested levels until the given fieldName is set
            for (int level = 0; level < nestedFields.length - 1; level++) {
                fieldNameBuilder.append(nestedFields[level]);
                String currentFieldName = fieldNameBuilder.toString();
                Object fieldVal = PropertyUtils.getProperty(bean, currentFieldName);
                if (fieldVal == null) {
                    //one of the nested levels is null. Instantiate it
                    PropertyDescriptor fieldDescriptor = PropertyUtils.getPropertyDescriptor(bean,
                            currentFieldName);
                    //this assumes the MPartition and the nested field objects have a default constructor
                    Object defaultInstance = fieldDescriptor.getPropertyType().newInstance();
                    PropertyUtils.setNestedProperty(bean, currentFieldName, defaultInstance);
                }
                //add dot separator for the next level of nesting
                fieldNameBuilder.append(DOT);
            }
        }
        PropertyUtils.setNestedProperty(bean, propertyName, value);
    } catch (Exception e) {
        throw new MetaException(org.apache.hadoop.hive.metastore.utils.StringUtils.stringifyException(e));
    }
}

From source file:org.bibsonomy.lucene.util.JNDITestDatabaseBinder.java

private static void bindLuceneConfig(String contextName, String fileName) {
    Context ctx;/*from  ww  w  .  j  a  v a 2  s .c om*/

    final Properties props;
    try {
        props = openPropertyFile(fileName);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    LuceneConfig config = new LuceneConfig();

    // get properties
    for (Object key : props.keySet()) {
        if (!present((key.toString())) || !(key.toString()).startsWith(CONTEXT_CONFIG_BEAN))
            continue;

        String propertyName = getPropertyName((String) key);
        String propertyValue = props.getProperty((String) key);
        try {
            PropertyUtils.setNestedProperty(config, propertyName, propertyValue);
            log.debug("Set lucene configuration property " + propertyName + " to " + propertyValue);
        } catch (Exception e) {
            log.warn("Error setting lucene configuration property " + propertyName + " to " + propertyValue
                    + "('" + e.getMessage() + "')");
        }
    }

    // bind bean in context
    try {
        MockContextFactory.setAsInitial();
        ctx = new InitialContext();
        ctx.bind(contextName + CONTEXT_CONFIG_BEAN, config);
    } catch (NamingException ex) {
        log.error("Error binding environment variable:'" + contextName + "' via JNDI ('" + ex.getMessage()
                + "')");
    }
}

From source file:org.bibsonomy.lucene.util.LuceneResourceConverter.java

/**
 * read property values from given lucene document and creates post model
 * //from w  w w.  ja  va2s. com
 * @param doc
 * @return the post representation of the lucene document
 */
public Post<R> writePost(final Document doc) {
    // initialize 
    final Post<R> post = this.createEmptyPost();

    // cycle though all properties and store the corresponding
    // values in the content hash map
    for (String propertyName : postPropertyMap.keySet()) {
        // get lucene index properties
        String fieldName = (String) postPropertyMap.get(propertyName).get(CFG_LUCENENAME);
        String propertyStr = doc.get(fieldName);

        if (!present(propertyStr))
            continue;

        @SuppressWarnings("unchecked")
        final LuceneTypeHandler<Object> typeHandler = (LuceneTypeHandler<Object>) postPropertyMap
                .get(propertyName).get(CFG_TYPEHANDLER);

        Object propertyValue = null;
        if (typeHandler != null) {
            propertyValue = typeHandler.setValue(propertyStr);
        } else
            propertyValue = propertyStr;

        try {
            PropertyUtils.setNestedProperty(post, propertyName, propertyValue);
        } catch (Exception e) {
            log.error("Error setting property " + propertyName + " to " + propertyValue.toString(), e);
        }
    }

    // all done.
    return post;
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.RuleFieldPersistenceProvider.java

protected boolean updateQuantityRule(EntityManager em, DataDTOToMVELTranslator translator, String entityKey,
        String fieldService, String jsonPropertyValue, Collection<QuantityBasedRule> criteriaList,
        Class<?> memberType, Object parent, String mappedBy, Property property) {
    boolean dirty = false;
    if (!StringUtils.isEmpty(jsonPropertyValue)) {
        //avoid lazy init exception on the criteria list for criteria created during an add
        criteriaList.size();//from w  w  w .  j  ava2 s .com
        DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(jsonPropertyValue);
        if (dw != null && StringUtils.isEmpty(dw.getError())) {
            List<QuantityBasedRule> updatedRules = new ArrayList<QuantityBasedRule>();
            for (DataDTO dto : dw.getData()) {
                if (dto.getId() != null && !CollectionUtils.isEmpty(criteriaList)) {
                    checkId: {
                        //updates are comprehensive, even data that was not changed
                        //is submitted here
                        //Update Existing Criteria
                        for (QuantityBasedRule quantityBasedRule : criteriaList) {
                            //make compatible with enterprise module
                            Long id = sandBoxHelper.getOriginalId(quantityBasedRule);
                            boolean isMatch = dto.getId().equals(id)
                                    || dto.getId().equals(quantityBasedRule.getId());
                            if (isMatch) {
                                String mvel;
                                //don't update if the data has not changed
                                if (!quantityBasedRule.getQuantity().equals(dto.getQuantity())) {
                                    dirty = true;
                                }
                                try {
                                    mvel = ruleFieldExtractionUtility.convertDTOToMvelString(translator,
                                            entityKey, dto, fieldService);
                                    if (!quantityBasedRule.getMatchRule().equals(mvel)) {
                                        dirty = true;
                                    }
                                } catch (MVELTranslationException e) {
                                    throw new RuntimeException(e);
                                }
                                if (!dirty && extensionManager != null) {
                                    ExtensionResultHolder<Boolean> resultHolder = new ExtensionResultHolder<Boolean>();
                                    ExtensionResultStatusType result = extensionManager.getProxy()
                                            .establishDirtyState(quantityBasedRule, resultHolder);
                                    if (ExtensionResultStatusType.NOT_HANDLED != result
                                            && resultHolder.getResult() != null) {
                                        dirty = resultHolder.getResult();
                                    }
                                }
                                if (dirty) {
                                    quantityBasedRule.setQuantity(dto.getQuantity());
                                    quantityBasedRule.setMatchRule(mvel);
                                    quantityBasedRule = em.merge(quantityBasedRule);
                                }
                                updatedRules.add(quantityBasedRule);
                                break checkId;
                            }
                        }
                        throw new IllegalArgumentException("Unable to update the rule of type ("
                                + memberType.getName() + ") because an update was requested for id ("
                                + dto.getId() + "), which does not exist.");
                    }
                } else {
                    //Create a new Criteria
                    QuantityBasedRule quantityBasedRule;
                    try {
                        quantityBasedRule = (QuantityBasedRule) memberType.newInstance();
                        quantityBasedRule.setQuantity(dto.getQuantity());
                        quantityBasedRule.setMatchRule(ruleFieldExtractionUtility
                                .convertDTOToMvelString(translator, entityKey, dto, fieldService));
                        if (StringUtils.isEmpty(quantityBasedRule.getMatchRule())
                                && !StringUtils.isEmpty(dw.getRawMvel())) {
                            quantityBasedRule.setMatchRule(dw.getRawMvel());
                        }
                        PropertyUtils.setNestedProperty(quantityBasedRule, mappedBy, parent);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    em.persist(quantityBasedRule);
                    dto.setId(quantityBasedRule.getId());
                    if (extensionManager != null) {
                        ExtensionResultHolder resultHolder = new ExtensionResultHolder();
                        extensionManager.getProxy().postAdd(quantityBasedRule, resultHolder);
                        if (resultHolder.getResult() != null) {
                            quantityBasedRule = (QuantityBasedRule) resultHolder.getResult();
                        }
                    }
                    updatedRules.add(quantityBasedRule);
                    dirty = true;
                }
            }
            //if an item was not included in the comprehensive submit from the client, we can assume that the
            //listing was deleted, so we remove it here.
            Iterator<QuantityBasedRule> itr = criteriaList.iterator();
            while (itr.hasNext()) {
                checkForRemove: {
                    QuantityBasedRule original = itr.next();
                    for (QuantityBasedRule quantityBasedRule : updatedRules) {
                        Long id = sandBoxHelper.getOriginalId(quantityBasedRule);
                        boolean isMatch = original.getId().equals(id)
                                || original.getId().equals(quantityBasedRule.getId());
                        if (isMatch) {
                            break checkForRemove;
                        }
                    }
                    em.remove(original);
                    itr.remove();
                    dirty = true;
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            String json;
            try {
                json = mapper.writeValueAsString(dw);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            property.setValue(json);
        }
    }
    return dirty;
}

From source file:org.jpos.ee.pm.core.PresentationManager.java

/**Setter for an object property value
 * @param obj The object/*w  w w  .  jav a 2s .c  om*/
 * @param name The property name
 * @param value The value to set
 * */
public void set(Object obj, String name, Object value) {
    try {
        PropertyUtils.setNestedProperty(obj, name, value);
    } catch (Exception e) {
        error(e);
    }
}