Example usage for java.beans PropertyDescriptor getWriteMethod

List of usage examples for java.beans PropertyDescriptor getWriteMethod

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getWriteMethod.

Prototype

public synchronized Method getWriteMethod() 

Source Link

Document

Gets the method that should be used to write the property value.

Usage

From source file:org.dspace.app.rest.model.hateoas.DSpaceResource.java

public DSpaceResource(T data, Utils utils, String... rels) {
    this.data = data;

    if (data != null) {
        try {/*from w w  w . ja  v a  2 s .c  o  m*/
            LinksRest links = data.getClass().getDeclaredAnnotation(LinksRest.class);
            if (links != null && rels != null) {
                List<String> relsList = Arrays.asList(rels);
                for (LinkRest linkAnnotation : links.links()) {
                    if (!relsList.contains(linkAnnotation.name())) {
                        continue;
                    }
                    String name = linkAnnotation.name();
                    Link linkToSubResource = utils.linkToSubResource(data, name);
                    String apiCategory = data.getCategory();
                    String model = data.getType();
                    LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory, model,
                            linkAnnotation.name());

                    if (!linkRepository.isEmbeddableRelation(data, linkAnnotation.name())) {
                        continue;
                    }
                    try {
                        //RestModel linkClass = linkAnnotation.linkClass().newInstance();
                        Method[] methods = linkRepository.getClass().getMethods();
                        boolean found = false;
                        for (Method m : methods) {
                            if (StringUtils.equals(m.getName(), linkAnnotation.method())) {
                                // TODO add support for single linked object other than for collections
                                Page<? extends Serializable> pageResult = (Page<? extends RestModel>) m.invoke(
                                        linkRepository, null, ((BaseObjectRest) data).getId(), null, null);
                                EmbeddedPage ep = new EmbeddedPage(linkToSubResource.getHref(), pageResult,
                                        null);
                                embedded.put(name, ep);
                                found = true;
                            }
                        }
                        // TODO custom exception
                        if (!found) {
                            throw new RuntimeException("Method for relation " + linkAnnotation.name()
                                    + " not found: " + linkAnnotation.method());
                        }
                    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            }

            for (PropertyDescriptor pd : Introspector.getBeanInfo(data.getClass()).getPropertyDescriptors()) {
                Method readMethod = pd.getReadMethod();
                String name = pd.getName();
                if (readMethod != null && !"class".equals(name)) {
                    LinkRest linkAnnotation = readMethod.getAnnotation(LinkRest.class);

                    if (linkAnnotation != null) {
                        if (StringUtils.isNotBlank(linkAnnotation.name())) {
                            name = linkAnnotation.name();
                        }
                        Link linkToSubResource = utils.linkToSubResource(data, name);
                        // no method is specified to retrieve the linked object(s) so check if it is already here
                        if (StringUtils.isBlank(linkAnnotation.method())) {
                            this.add(linkToSubResource);
                            Object linkedObject = readMethod.invoke(data);
                            Object wrapObject = linkedObject;
                            if (linkedObject instanceof RestModel) {
                                RestModel linkedRM = (RestModel) linkedObject;
                                wrapObject = utils
                                        .getResourceRepository(linkedRM.getCategory(), linkedRM.getType())
                                        .wrapResource(linkedRM);
                            } else {
                                if (linkedObject instanceof List) {
                                    List<RestModel> linkedRMList = (List<RestModel>) linkedObject;
                                    if (linkedRMList.size() > 0) {

                                        DSpaceRestRepository<RestModel, ?> resourceRepository = utils
                                                .getResourceRepository(linkedRMList.get(0).getCategory(),
                                                        linkedRMList.get(0).getType());
                                        // TODO should we force pagination also of embedded resource? 
                                        // This will force a pagination with size 10 for embedded collections as well
                                        //                                 int pageSize = 1;
                                        //                                 PageImpl<RestModel> page = new PageImpl(
                                        //                                       linkedRMList.subList(0,
                                        //                                             linkedRMList.size() > pageSize ? pageSize : linkedRMList.size()), new PageRequest(0, pageSize), linkedRMList.size()); 
                                        PageImpl<RestModel> page = new PageImpl(linkedRMList);
                                        wrapObject = new EmbeddedPage(linkToSubResource.getHref(),
                                                page.map(resourceRepository::wrapResource), linkedRMList);
                                    } else {
                                        wrapObject = null;
                                    }
                                }
                            }
                            if (linkedObject != null) {
                                embedded.put(name, wrapObject);
                            } else {
                                embedded.put(name, null);
                            }
                            Method writeMethod = pd.getWriteMethod();
                            writeMethod.invoke(data, new Object[] { null });
                        } else {
                            // call the link repository
                            try {
                                //RestModel linkClass = linkAnnotation.linkClass().newInstance();
                                String apiCategory = data.getCategory();
                                String model = data.getType();
                                LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory,
                                        model, linkAnnotation.name());
                                Method[] methods = linkRepository.getClass().getMethods();
                                boolean found = false;
                                for (Method m : methods) {
                                    if (StringUtils.equals(m.getName(), linkAnnotation.method())) {
                                        // TODO add support for single linked object other than for collections
                                        Page<? extends Serializable> pageResult = (Page<? extends RestModel>) m
                                                .invoke(linkRepository, null, ((BaseObjectRest) data).getId(),
                                                        null, null);
                                        EmbeddedPage ep = new EmbeddedPage(linkToSubResource.getHref(),
                                                pageResult, null);
                                        embedded.put(name, ep);
                                        found = true;
                                    }
                                }
                                // TODO custom exception
                                if (!found) {
                                    throw new RuntimeException("Method for relation " + linkAnnotation.name()
                                            + " not found: " + linkAnnotation.method());
                                }
                            } catch (IllegalAccessException | IllegalArgumentException
                                    | InvocationTargetException e) {
                                throw new RuntimeException(e.getMessage(), e);
                            }
                        }
                    } else if (RestModel.class.isAssignableFrom(readMethod.getReturnType())) {
                        Link linkToSubResource = utils.linkToSubResource(data, name);
                        this.add(linkToSubResource);
                        RestModel linkedObject = (RestModel) readMethod.invoke(data);
                        if (linkedObject != null) {
                            embedded.put(name, utils
                                    .getResourceRepository(linkedObject.getCategory(), linkedObject.getType())
                                    .wrapResource(linkedObject));
                        } else {
                            embedded.put(name, null);
                        }

                        Method writeMethod = pd.getWriteMethod();
                        writeMethod.invoke(data, new Object[] { null });
                    }
                }
            }
        } catch (IntrospectionException | IllegalArgumentException | IllegalAccessException
                | InvocationTargetException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        this.add(utils.linkToSingleResource(data, Link.REL_SELF));
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private boolean doPersist(ObjectsToPersist toPersist, String userName,
        Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId,
        EntityManager em, boolean validateBefore, Locale locale, boolean processExceptions)
        throws ClassNotFoundException, IntrospectionException, PersistenceException, IllegalAccessException,
        InvocationTargetException, InstantiationException {
    try {//www  .j ava 2 s  .  co  m
        Validator validator = validatorFactory.getValidator();
        List<INakedObject> toInsert = toPersist.getInsertedObjects();
        if (toInsert != null) {
            int max = 100 * toInsert.size();
            int idx = -1;
            int k = -1;
            int s = toInsert.size();
            int prevSize = s;
            while (!toInsert.isEmpty()) {

                if (s == toInsert.size()) {
                    k++;
                } else
                    k = 0;
                if (k == 1) {
                    logger.log(Level.FINE,
                            "Impossible to persist data : one linked object not found in toInsert list");
                    return false;
                }

                if (prevSize == toInsert.size()) {
                    idx++;
                } else {
                    idx = 0;
                    prevSize = toInsert.size();
                }
                if (idx > max) {
                    logger.log(Level.FINE,
                            "Impossible to persist data : one linked object not found in toInsert list...");
                    return false;
                }
                Iterator<INakedObject> it = toInsert.iterator();
                while (it.hasNext()) {
                    INakedObject o = (INakedObject) it.next();
                    String className = o.getClass().getName();
                    if (o instanceof IAuditable) {
                        IAuditable aud = (IAuditable) o;
                        aud.setCreateUser(userName);
                        aud.setCreateDate(new Date());
                    }

                    Set<PropertyDescriptor> ids = idsByClassName.get(className);

                    processLinkedCollectionsBeforePersist(o, collectionsByClassName.get(className));

                    if (!processLinkedObjectsBeforePersist(newIdByOldId, o, lazysByClassName.get(className),
                            toPersist))
                        continue;
                    if (!processLinkedObjectsBeforePersist(newIdByOldId, o,
                            eagerObjectsByClassName.get(className), toPersist))
                        continue;

                    if (generatedIdClasses.contains(className)) {
                        PropertyDescriptor idPd = ids.iterator().next();
                        Object oldId = idPd.getReadMethod().invoke(o, StorageService.emptyArg);
                        Object[] args = new Object[1];
                        if (!idPd.getPropertyType().isPrimitive())
                            args[0] = null;
                        else
                            args[0] = 0L;
                        idPd.getWriteMethod().invoke(o, args);

                        if (validateBefore) {
                            Set<ConstraintViolation<INakedObject>> errors = validator.validate(o);
                            if (errors != null && !errors.isEmpty()) {
                                it.remove();
                                continue;
                            }
                            try {
                                em.persist(o);
                            } catch (Exception e) {
                                it.remove();
                                continue;
                            }
                        } else
                            em.persist(o);
                        Object newId = idPd.getReadMethod().invoke(o, StorageService.emptyArg);
                        newIdByOldId.put(oldId, new IdHolder(newId, className));
                        List<Object> idVals = new ArrayList<Object>(1);
                        idVals.add(oldId);
                        List<String> idFields = new ArrayList<String>(1);
                        idFields.add(idPd.getName());
                        res.put(new com.hiperf.common.ui.shared.util.Id(idFields, idVals), o);

                        it.remove();
                    } else {
                        com.hiperf.common.ui.shared.util.Id id = getId(o, ids);
                        int i = 0;
                        boolean toProcess = true;
                        for (Object idVal : id.getFieldValues()) {
                            if ((idVal instanceof Long && ((Long) idVal).longValue() < 0)
                                    || (idVal instanceof String
                                            && ((String) idVal).startsWith(PersistenceManager.SEQ_PREFIX))) {
                                IdHolder newIds = newIdByOldId.get(idVal);
                                if (newIds != null) {
                                    String att = id.getFieldNames().get(i);
                                    for (PropertyDescriptor idPd : ids) {
                                        if (idPd.getName().equals(att)) {
                                            Object[] args = new Object[1];
                                            args[0] = newIds.getId();
                                            idPd.getWriteMethod().invoke(o, args);
                                            break;
                                        }
                                    }
                                } else {
                                    toProcess = false;
                                    break;
                                }
                            }
                            i++;
                        }
                        if (toProcess) {
                            if (validateBefore) {
                                Set<ConstraintViolation<INakedObject>> errors = validator.validate(o);
                                if (errors != null && !errors.isEmpty()) {
                                    it.remove();
                                    continue;
                                }
                                try {
                                    refreshManyToOneLinkedWithId(o, id, em);
                                    em.persist(o);
                                } catch (Exception e) {
                                    it.remove();
                                    continue;
                                }
                            } else {
                                refreshManyToOneLinkedWithId(o, id, em);
                                em.persist(o);
                            }
                            id = getId(o, ids);
                            res.put(id, o);
                            it.remove();
                        }
                    }
                }
            }
        }
        Map<String, Set<com.hiperf.common.ui.shared.util.Id>> toDelete = toPersist
                .getRemovedObjectsIdsByClassName();
        if (toDelete != null) {
            for (String className : toDelete.keySet()) {
                Set<com.hiperf.common.ui.shared.util.Id> ids = toDelete.get(className);
                Class<?> clazz = Class.forName(className);
                Map<Field, Field> toRemove = null;
                if (ids != null && !ids.isEmpty()) {
                    com.hiperf.common.ui.shared.util.Id id = ids.iterator().next();
                    if (id.getFieldValues().size() > 1) {
                        toRemove = new HashMap<Field, Field>();
                        Field[] fields = clazz.getDeclaredFields();
                        for (Field f : fields) {
                            if (f.isAnnotationPresent(ManyToOne.class)) {
                                Field[] ff = f.getType().getDeclaredFields();
                                for (Field lf : ff) {
                                    OneToMany ann = lf.getAnnotation(OneToMany.class);
                                    if (ann != null && ann.targetEntity() != null
                                            && ann.targetEntity().equals(clazz)) {
                                        toRemove.put(f, lf);
                                    }
                                }
                            }
                        }
                        // TODO : manage annotations on the getters...
                    }
                }
                for (com.hiperf.common.ui.shared.util.Id id : ids) {
                    INakedObject no = getObject(clazz, id, em);
                    if (no != null) {
                        if (toRemove != null && !toRemove.isEmpty()) {
                            for (Entry<Field, Field> e : toRemove.entrySet()) {
                                Field f = e.getKey();
                                Field ff = e.getValue();
                                boolean b1 = false;
                                boolean b2 = false;
                                if (!f.isAccessible()) {
                                    f.setAccessible(true);
                                    b1 = true;
                                }
                                if (!ff.isAccessible()) {
                                    ff.setAccessible(true);
                                    b2 = true;
                                }
                                ((Collection) ff.get(f.get(no))).remove(no);
                                if (b1)
                                    f.setAccessible(false);
                                if (b2)
                                    ff.setAccessible(false);
                            }
                        } else {
                            // TODO : manage annotations on the getters...
                        }
                        em.remove(no);
                    }
                }
            }
        }
        Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>>> toUpdate = toPersist
                .getUpdatedObjects();
        if (toUpdate != null) {
            for (String className : toUpdate.keySet()) {
                Map<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>> map = toUpdate
                        .get(className);
                Class<?> clazz = Class.forName(className);
                Iterator<Entry<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>>> iterator = map
                        .entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>> entry = iterator
                            .next();
                    com.hiperf.common.ui.shared.util.Id id = entry.getKey();
                    INakedObject original = getObject(clazz, id, em);
                    Map<String, Serializable> updateMap = entry.getValue();
                    for (String att : updateMap.keySet()) {
                        Object object = updateMap.get(att);
                        if (object != null && object instanceof NakedObjectHandler) {
                            NakedObjectHandler oo = (NakedObjectHandler) object;
                            com.hiperf.common.ui.shared.util.Id objId = oo.getId();
                            if (generatedIdClasses.contains(oo.getClassName())
                                    && newIdByOldId.containsKey(objId.getFieldValues().get(0))) {
                                IdHolder newIds = newIdByOldId.get(objId.getFieldValues().get(0));
                                List<Object> idVals = new ArrayList<Object>(1);
                                idVals.add(newIds.getId());
                                List<String> idFields = new ArrayList<String>(1);
                                idFields.add(idsByClassName.get(oo.getClassName()).iterator().next().getName());
                                com.hiperf.common.ui.shared.util.Id newObjId = new com.hiperf.common.ui.shared.util.Id(
                                        idFields, idVals);
                                object = getObject(Class.forName(oo.getClassName()), newObjId, em);
                            } else {
                                object = getObject(Class.forName(oo.getClassName()), oo.getId(), em);
                            }
                        }
                        updateAttributeValue(className, original, att, object);
                    }
                    if (original instanceof IAuditable) {
                        IAuditable aud = (IAuditable) original;
                        aud.setModifyUser(userName);
                        aud.setModifyDate(new Date());
                    }
                    INakedObject o = null;
                    if (validateBefore) {
                        Set<ConstraintViolation<INakedObject>> errors = validator.validate(original);
                        if (errors != null && !errors.isEmpty()) {
                            iterator.remove();
                            continue;
                        }
                        try {
                            o = em.merge(original);
                            em.flush();
                        } catch (Exception e) {
                            iterator.remove();
                            continue;
                        }
                    } else
                        o = em.merge(original);

                    res.put(id, o);
                }
            }
        }
        processAddedManyToMany(toPersist, res, newIdByOldId, em);
        processRemovedManyToMany(toPersist, res, newIdByOldId, em);
        em.flush();
        return true;
    } catch (Exception e) {
        logger.log(Level.WARNING, "Exception", e);
        if (processExceptions) {
            processDbExceptions(locale, e);
            return false;
        } else
            throw new PersistenceException(e);
    }

}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private void processAddedManyToMany(ObjectsToPersist toPersist,
        Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId,
        EntityManager em) throws ClassNotFoundException, IntrospectionException, PersistenceException,
        IllegalAccessException, InvocationTargetException, NoSuchFieldException {
    Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> manyToManyAdded = toPersist
            .getManyToManyAddedByClassName();
    if (manyToManyAdded != null && !manyToManyAdded.isEmpty()) {
        for (Entry<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> e : manyToManyAdded
                .entrySet()) {/*from  www  .ja va 2 s .c o m*/
            String className = e.getKey();
            Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> map = e
                    .getValue();
            if (map != null && !map.isEmpty()) {
                Class<?> clazz = Class.forName(className);
                for (Entry<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> entry : map
                        .entrySet()) {
                    com.hiperf.common.ui.shared.util.Id id = entry.getKey();
                    Map<String, List<com.hiperf.common.ui.shared.util.Id>> m = entry.getValue();
                    if (m != null && !m.isEmpty()) {
                        Object objId = id.getFieldValues().get(0);
                        if (newIdByOldId.containsKey(objId))
                            objId = newIdByOldId.get(objId).getId();
                        Object o = em.find(clazz, objId);
                        if (o != null) {
                            PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(className);
                            for (Entry<String, List<com.hiperf.common.ui.shared.util.Id>> ee : m.entrySet()) {
                                String attr = ee.getKey();
                                List<com.hiperf.common.ui.shared.util.Id> ll = ee.getValue();
                                if (ll != null && !ll.isEmpty()) {
                                    Collection coll = null;
                                    Class classInColl = null;
                                    PropertyDescriptor myPd = null;
                                    String mappedBy = null;
                                    for (PropertyDescriptor pd : pds) {
                                        if (pd.getName().equals(attr)) {
                                            myPd = pd;
                                            coll = (Collection) pd.getReadMethod().invoke(o,
                                                    StorageService.emptyArg);
                                            if (coll == null) {
                                                if (List.class.isAssignableFrom(pd.getPropertyType()))
                                                    coll = new ArrayList();
                                                else
                                                    coll = new HashSet();
                                                pd.getWriteMethod().invoke(o, coll);
                                            }
                                            ManyToMany ann = pd.getReadMethod().getAnnotation(ManyToMany.class);
                                            if (ann == null) {
                                                ann = clazz.getDeclaredField(pd.getName())
                                                        .getAnnotation(ManyToMany.class);
                                            }
                                            if (ann != null) {
                                                mappedBy = ann.mappedBy();
                                            }
                                            break;
                                        }
                                    }
                                    if (coll != null) {
                                        ParameterizedType genericType = (ParameterizedType) clazz
                                                .getDeclaredField(myPd.getName()).getGenericType();
                                        if (genericType != null) {
                                            for (Type t : genericType.getActualTypeArguments()) {

                                                if (t instanceof Class
                                                        && INakedObject.class.isAssignableFrom((Class) t)) {
                                                    classInColl = (Class) t;
                                                    break;
                                                }
                                            }
                                        }
                                        for (com.hiperf.common.ui.shared.util.Id i : ll) {
                                            Object idObj = i.getFieldValues().get(0);
                                            if (newIdByOldId.containsKey(idObj))
                                                idObj = newIdByOldId.get(idObj).getId();
                                            Object linkedObj = em.find(classInColl, idObj);
                                            if (mappedBy == null || mappedBy.length() == 0)
                                                coll.add(linkedObj);
                                            else {
                                                PropertyDescriptor[] pds2 = propertyDescriptorsByClassName
                                                        .get(classInColl.getName());
                                                if (pds2 == null) {
                                                    pds2 = propertyDescriptorsByClassName
                                                            .get(classInColl.getName());
                                                }
                                                for (PropertyDescriptor pd : collectionsByClassName
                                                        .get(classInColl.getName())) {
                                                    if (pd.getName().equals(mappedBy)) {
                                                        Collection coll2 = (Collection) pd.getReadMethod()
                                                                .invoke(linkedObj, StorageService.emptyArg);
                                                        if (coll2 == null) {
                                                            if (List.class
                                                                    .isAssignableFrom(pd.getPropertyType()))
                                                                coll2 = new ArrayList();
                                                            else
                                                                coll2 = new HashSet();
                                                            pd.getWriteMethod().invoke(linkedObj, coll2);
                                                        }
                                                        coll2.add(o);
                                                    }
                                                }
                                                em.merge(linkedObj);
                                            }
                                            if (linkedObj instanceof INakedObject)
                                                res.put(i, (INakedObject) linkedObj);
                                        }
                                    }
                                }
                            }
                            res.put(id, (INakedObject) em.merge(o));
                        }
                    }

                }
            }
        }
    }
}

From source file:com.dell.asm.asmcore.asmmanager.app.rest.ServiceTemplateService.java

public static <M> void merge(M target, M source) {
    try {//from  ww  w . j  a va 2s.  c om
        final BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());

        // Iterate over all the attributes
        for (final PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            // Only copy writable attributes
            if (descriptor.getWriteMethod() != null) {
                final Object originalValue = descriptor.getReadMethod().invoke(target);
                // Only copy values values where the destination values is null
                if (originalValue == null) {
                    final Object defaultValue = descriptor.getReadMethod().invoke(source);
                    descriptor.getWriteMethod().invoke(target, defaultValue);
                }
            }
        }
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.tinygroup.weblayer.webcontext.parser.util.BeanWrapperImpl.java

private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue = null;//from  w  w  w .ja  v a 2 s.c o  m
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "': returned null");
        } else if (propValue.getClass().isArray()) {
            Class requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor()) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue,
                        pv.getValue(), requiredType);
                Array.set(propValue, Integer.parseInt(key), convertedValue);
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, oldValue, pv.getValue());
                throw new TypeMismatchException(pce, requiredType, ex);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class requiredType = null;
            if (JdkVersion.isAtLeastJava15()) {
                requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                        tokens.keys.length);
            }
            List list = (List) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            try {
                Object convertedValue = this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue,
                        pv.getValue(), requiredType);
                if (index < list.size()) {
                    list.set(index, convertedValue);
                } else if (index >= list.size()) {
                    for (int i = list.size(); i < index; i++) {
                        try {
                            list.add(null);
                        } catch (NullPointerException ex) {
                            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                    "Cannot set element with index " + index + " in List of size " + list.size()
                                            + ", accessed using property path '" + propertyName
                                            + "': List does not support filling up gaps with null elements");
                        }
                    }
                    list.add(convertedValue);
                }
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, oldValue, pv.getValue());
                throw new TypeMismatchException(pce, requiredType, ex);
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class mapKeyType = null;
            Class mapValueType = null;
            if (JdkVersion.isAtLeastJava15()) {
                mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                        tokens.keys.length);
                mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                        tokens.keys.length);
            }
            Map map = (Map) propValue;
            Object convertedMapKey = null;
            Object convertedMapValue = null;
            try {
                // IMPORTANT: Do not pass full property name in here - property editors
                // must not kick in for map keys but rather only for map values.
                convertedMapKey = this.typeConverterDelegate.convertIfNecessary(key, mapKeyType);
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, null, pv.getValue());
                throw new TypeMismatchException(pce, mapKeyType, ex);
            }
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            try {
                // Pass full property name and old value in here, since we want full
                // conversion ability for map values.
                convertedMapValue = this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue,
                        pv.getValue(), mapValueType, null,
                        new MethodParameter(pd.getReadMethod(), -1, tokens.keys.length + 1));
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, oldValue, pv.getValue());
                throw new TypeMismatchException(pce, mapValueType, ex);
            }
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.resolvedDescriptor;
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                        matches.buildErrorMessage(), matches.getPossibleMatches());
            }
            pv.getOriginalPropertyValue().resolvedDescriptor = pd;
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        try {
                            oldValue = readMethod.invoke(this.object, new Object[0]);
                        } catch (Exception ex) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = this.typeConverterDelegate.convertIfNecessary(oldValue, originalValue, pd);
                }
                pv.getOriginalPropertyValue().conversionNecessary = Boolean
                        .valueOf(valueToApply != originalValue);
            }
            Method writeMethod = pd.getWriteMethod();
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                writeMethod.setAccessible(true);
            }
            writeMethod.invoke(this.object, new Object[] { valueToApply });
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (IllegalArgumentException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new TypeMismatchException(pce, pd.getPropertyType(), ex);
        } catch (IllegalAccessException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:org.openmrs.util.ReportingcompatibilityUtil.java

/**
 * Uses reflection to translate a PatientSearch into a PatientFilter
 *//*from  w  ww.  j av a 2 s.com*/
@SuppressWarnings("unchecked")
public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history,
        EvaluationContext evalContext) {
    if (search.isSavedSearchReference()) {
        PatientSearch ps = ((PatientSearchReportObject) Context.getService(ReportObjectService.class)
                .getReportObject(search.getSavedSearchId())).getPatientSearch();
        return toPatientFilter(ps, history, evalContext);
    } else if (search.isSavedFilterReference()) {
        return Context.getService(ReportObjectService.class).getPatientFilterById(search.getSavedFilterId());
    } else if (search.isSavedCohortReference()) {
        Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId());
        // to prevent lazy loading exceptions, cache the member ids here
        if (c != null) {
            c.getMemberIds().size();
        }
        return new CohortFilter(c);
    } else if (search.isComposition()) {
        if (history == null && search.requiresHistory()) {
            throw new IllegalArgumentException("You can't evaluate this search without a history");
        } else {
            return search.cloneCompositionAsFilter(history, evalContext);
        }
    } else {
        Class clz = search.getFilterClass();
        if (clz == null) {
            throw new IllegalArgumentException(
                    "search must be saved, composition, or must have a class specified");
        }
        log.debug("About to instantiate " + clz);
        PatientFilter pf = null;
        try {
            pf = (PatientFilter) clz.newInstance();
        } catch (Exception ex) {
            log.error("Couldn't instantiate a " + search.getFilterClass(), ex);
            return null;
        }
        Class[] stringSingleton = { String.class };
        if (search.getArguments() != null) {
            for (SearchArgument sa : search.getArguments()) {
                if (log.isDebugEnabled()) {
                    log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> "
                            + sa.getValue());
                }
                PropertyDescriptor pd = null;
                try {
                    pd = new PropertyDescriptor(sa.getName(), clz);
                } catch (IntrospectionException ex) {
                    log.error("Error while examining property " + sa.getName(), ex);
                    continue;
                }
                Class<?> realPropertyType = pd.getPropertyType();

                // instantiate the value of the search argument
                String valueAsString = sa.getValue();
                String testForExpression = search.getArgumentValue(sa.getName());
                if (testForExpression != null) {
                    log.debug("Setting " + sa.getName() + " to: " + testForExpression);
                    if (evalContext != null && EvaluationContext.isExpression(testForExpression)) {
                        Object evaluated = evalContext.evaluateExpression(testForExpression);
                        if (evaluated != null) {
                            if (evaluated instanceof Date) {
                                valueAsString = Context.getDateFormat().format((Date) evaluated);
                            } else {
                                valueAsString = evaluated.toString();
                            }
                        }
                        log.debug("Evaluated " + sa.getName() + " to: " + valueAsString);
                    }
                }

                Object value = null;
                Class<?> valueClass = sa.getPropertyClass();
                try {
                    // If there's a valueOf(String) method, just use that
                    // (will cover at least String, Integer, Double,
                    // Boolean)
                    Method valueOfMethod = null;
                    try {
                        valueOfMethod = valueClass.getMethod("valueOf", stringSingleton);
                    } catch (NoSuchMethodException ex) {
                    }
                    if (valueOfMethod != null) {
                        Object[] holder = { valueAsString };
                        value = valueOfMethod.invoke(pf, holder);
                    } else if (realPropertyType.isEnum()) {
                        // Special-case for enum types
                        List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants());
                        for (Enum e : constants) {
                            if (e.toString().equals(valueAsString)) {
                                value = e;
                                break;
                            }
                        }
                    } else if (String.class.equals(valueClass)) {
                        value = valueAsString;
                    } else if (Location.class.equals(valueClass)) {
                        LocationEditor ed = new LocationEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Concept.class.equals(valueClass)) {
                        ConceptEditor ed = new ConceptEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Program.class.equals(valueClass)) {
                        ProgramEditor ed = new ProgramEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (ProgramWorkflowState.class.equals(valueClass)) {
                        ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (EncounterType.class.equals(valueClass)) {
                        EncounterTypeEditor ed = new EncounterTypeEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Form.class.equals(valueClass)) {
                        FormEditor ed = new FormEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Drug.class.equals(valueClass)) {
                        DrugEditor ed = new DrugEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (PersonAttributeType.class.equals(valueClass)) {
                        PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Cohort.class.equals(valueClass)) {
                        CohortEditor ed = new CohortEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Date.class.equals(valueClass)) {
                        // TODO: this uses the date format from the current
                        // session, which could cause problems if the user
                        // changes it after searching.
                        DateFormat df = Context.getDateFormat(); // new
                        // SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()),
                        // Context.getLocale());
                        CustomDateEditor ed = new CustomDateEditor(df, true, 10);
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (LogicCriteria.class.equals(valueClass)) {
                        value = Context.getLogicService().parseString(valueAsString);
                    } else {
                        // TODO: Decide whether this is a hack. Currently
                        // setting Object arguments with a String
                        value = valueAsString;
                    }
                } catch (Exception ex) {
                    log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex);
                    continue;
                }

                if (value != null) {

                    if (realPropertyType.isAssignableFrom(valueClass)) {
                        log.debug("setting value of " + sa.getName() + " to " + value);
                        try {
                            pd.getWriteMethod().invoke(pf, value);
                        } catch (Exception ex) {
                            log.error("Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> "
                                    + value, ex);
                            continue;
                        }
                    } else if (Collection.class.isAssignableFrom(realPropertyType)) {
                        log.debug(sa.getName() + " is a Collection property");
                        // if realPropertyType is a collection, add this
                        // value to it (possibly after instantiating)
                        try {
                            Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null);
                            if (collection == null) {
                                // we need to instantiate this collection.
                                // I'm going with the following rules, which
                                // should be rethought:
                                // SortedSet -> TreeSet
                                // Set -> HashSet
                                // Otherwise -> ArrayList
                                if (SortedSet.class.isAssignableFrom(realPropertyType)) {
                                    collection = new TreeSet();
                                    log.debug("instantiated a TreeSet");
                                    pd.getWriteMethod().invoke(pf, collection);
                                } else if (Set.class.isAssignableFrom(realPropertyType)) {
                                    collection = new HashSet();
                                    log.debug("instantiated a HashSet");
                                    pd.getWriteMethod().invoke(pf, collection);
                                } else {
                                    collection = new ArrayList();
                                    log.debug("instantiated an ArrayList");
                                    pd.getWriteMethod().invoke(pf, collection);
                                }
                            }
                            collection.add(value);
                        } catch (Exception ex) {
                            log.error("Error instantiating collection for property " + sa.getName()
                                    + " whose class is " + realPropertyType, ex);
                            continue;
                        }
                    } else {
                        log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType
                                + " but is given as " + valueClass);
                    }
                }
            }
        }
        log.debug("Returning " + pf);
        return pf;
    }
}

From source file:org.springframework.beans.BeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;//from  w w w  .  j a  v a  2 s.  c o m
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // TODO: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // IMPORTANT: Do not pass full property name in here - property editors
            // must not kick in for map keys but rather only for map values.
            TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
            Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.resolvedDescriptor;
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().resolvedDescriptor = pd;
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())
                                && !readMethod.isAccessible()) {
                            if (System.getSecurityManager() != null) {
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        readMethod.setAccessible(true);
                                        return null;
                                    }
                                });
                            } else {
                                readMethod.setAccessible(true);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv2) throws BeansException {
    net.yasion.common.core.bean.wrapper.PropertyValue pv = new net.yasion.common.core.bean.wrapper.PropertyValue(
            "", null);
    AfxBeanUtils.copySamePropertyValue(pv2, pv);
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;/*from   w  w  w.  j  av  a 2s  .c om*/
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // #TO#DO#: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // IMPORTANT: Do not pass full property name in here - property editors
            // must not kick in for map keys but rather only for map values.
            TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
            Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.getResolvedDescriptor();
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().setResolvedDescriptor(pd);
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.getConversionNecessary())) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())
                                && !readMethod.isAccessible()) {
                            if (System.getSecurityManager() != null) {
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        readMethod.setAccessible(true);
                                        return null;
                                    }
                                });
                            } else {
                                readMethod.setAccessible(true);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().setConversionNecessary(valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}