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.yes.cart.bulkimport.csv.impl.CsvBulkImportServiceImpl.java

/**
 * Fill the given entity object with line information using import column descriptions.
 *
 * @param tuple         given csv line/* w w w.j  a  v a 2 s.c  o m*/
 * @param object        entity object
 * @param importColumns particular type column collection
 * @throws Exception in case if something wrong with reflection (IntrospectionException,
 *                   InvocationTargetException,
 *                   IllegalAccessException)
 */
private void fillEntityFields(final ImportTuple tuple, final Object object,
        final Collection<ImportColumn> importColumns) throws Exception {

    final Class clz = object.getClass();

    PropertyDescriptor propertyDescriptor = null;

    for (ImportColumn importColumn : importColumns) {
        try {
            if (StringUtils.isNotBlank(importColumn.getName())) { //can be just lookup query

                Object writeObject = object;

                if (importColumn.getName().indexOf('.') == -1) {
                    // direct property
                    propertyDescriptor = new PropertyDescriptor(importColumn.getName(), clz);
                } else {
                    // object path
                    final String[] chain = importColumn.getName().split("\\.");
                    for (int i = 0; i < chain.length - 1; i++) {
                        propertyDescriptor = new PropertyDescriptor(chain[i], writeObject.getClass());
                        writeObject = propertyDescriptor.getReadMethod().invoke(writeObject);
                    }
                    propertyDescriptor = new PropertyDescriptor(chain[chain.length - 1],
                            writeObject.getClass());
                }

                Object singleObjectValue = tuple.getColumnValue(importColumn, valueDataAdapter);
                if (importColumn.getLanguage() != null) {
                    final I18NModel model = new StringI18NModel(
                            (String) propertyDescriptor.getReadMethod().invoke(object));
                    model.putValue(importColumn.getLanguage(), String.valueOf(singleObjectValue));
                    singleObjectValue = model.toString();
                }
                if (singleObjectValue != null
                        && !singleObjectValue.getClass().equals(propertyDescriptor.getPropertyType())) {
                    // if we have mismatch try on the fly conversion - this happens if someone omits <data-type> for non String values
                    singleObjectValue = extendedConversionService.convert(singleObjectValue,
                            TypeDescriptor.valueOf(singleObjectValue.getClass()),
                            TypeDescriptor.valueOf((propertyDescriptor.getPropertyType())));
                }

                propertyDescriptor.getWriteMethod().invoke(writeObject, singleObjectValue);
            }
        } catch (Exception exp) {

            final String propName = propertyDescriptor != null ? propertyDescriptor.getName() : null;
            final String propType = propertyDescriptor != null ? propertyDescriptor.getPropertyType().getName()
                    : null;

            throw new Exception(
                    MessageFormat.format("Failed to process property name {0} type {1} object is {2}", propName,
                            propType, object),
                    exp);
        }
    }

}

From source file:org.nextframework.controller.ExtendedBeanWrapper.java

protected Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;
    PropertyDescriptor pd = getPropertyDescriptorInternal(tokens.actualName);
    if (pd == null || pd.getReadMethod() == null) {
        throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName);
    }//  w  w w . j  a  v a  2  s  .co  m
    if (logger.isDebugEnabled())
        logger.debug("About to invoke read method [" + pd.getReadMethod() + "] on object of class ["
                + this.object.getClass().getName() + "]");
    try {
        Object value = pd.getReadMethod().invoke(this.object, (Object[]) null);
        Type genericReturnType = pd.getReadMethod().getGenericReturnType();
        Class rawReturnType = pd.getReadMethod().getReturnType();
        if (tokens.keys != null) {
            // apply indexes and map keys
            for (int i = 0; i < tokens.keys.length; i++) {
                String key = tokens.keys[i];

                //cria listas sob demanda.. no  mais necessrio utilizar o ListSet no pojo
                Class originalClass = null;
                if (value != null) {
                    originalClass = value.getClass();
                }
                if (value == null && rawReturnType != null && genericReturnType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) genericReturnType;
                    if (Map.class.isAssignableFrom(rawReturnType)) {
                        value = new LinkedHashMap();
                        pd.getWriteMethod().invoke(this.object, value);
                    } else if (List.class.isAssignableFrom(rawReturnType)
                            || Set.class.isAssignableFrom(rawReturnType)) {
                        Type type = parameterizedType.getActualTypeArguments()[0];
                        value = new ListSet(type instanceof Class ? (Class) type
                                : (Class) ((ParameterizedType) type).getRawType());
                        pd.getWriteMethod().invoke(this.object, value);
                    }
                }
                //fim da criacao sob demanda

                if (value == null) {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                } else if (value.getClass().isArray()) {
                    value = Array.get(value, Integer.parseInt(key));
                } else if (value instanceof List) {
                    List list = (List) value;
                    try {
                        value = list.get(Integer.parseInt(key));
                    } catch (IndexOutOfBoundsException e) {
                        //tentar instanciar um bean da lista
                        String extraMessage = "";
                        if (genericReturnType instanceof ParameterizedType) {
                            ParameterizedType parameterizedType = (ParameterizedType) genericReturnType;
                            Type type = parameterizedType.getActualTypeArguments()[0];
                            if (type instanceof Class) {
                                Class clazz = (Class) type;
                                extraMessage = "A classe " + clazz.getName()
                                        + " no possui um construtor publico sem argumentos";
                                try {
                                    value = clazz.newInstance();
                                    int index = Integer.parseInt(key);
                                    int insertNulls = index - list.size();
                                    while (insertNulls > 0) { // 11/06/2012
                                        list.add(null);
                                        insertNulls--;
                                    }

                                    list.add(index, value); // CDIGO 15/01/2007
                                } catch (InstantiationException e1) {
                                    throw new RuntimeException(
                                            "Aconteceu um erro ao acessar um elemento da classe "
                                                    + originalClass.getName() + " propriedade " + propertyName
                                                    + "  No foi possvel instanciar um bean para preencher a lista. "
                                                    + extraMessage,
                                            e);
                                }
                            }
                        } else if (originalClass != null) {
                            throw new RuntimeException("Aconteceu um erro ao acessar um elemento da classe "
                                    + originalClass.getName() + " propriedade " + propertyName
                                    + "  Sugesto: Utilize uma lista que cresa quando for necessrio como o ListSet ou no instancie nenhum objeto para essa propriedade",
                                    e);
                        } else {
                            throw e;
                        }
                    }
                } else if (value instanceof Set) {
                    // apply index to Iterator in case of a Set
                    //TODO CRIAR AUTOMATICAMENTE O BEAN DO SET
                    Set set = (Set) value;
                    int index = Integer.parseInt(key);
                    if (index < 0 || index >= set.size()) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot get element with index " + index + " from Set of size " + set.size()
                                        + ", accessed using property path '" + propertyName + "'"
                                        + "  Sugesto: Utilize o ListSet ou no instancie nenhum objeto");
                    }
                    Iterator it = set.iterator();
                    for (int j = 0; it.hasNext(); j++) {
                        Object elem = it.next();
                        if (j == index) {
                            value = elem;
                            break;
                        }
                    }
                } else if (value instanceof Map) {
                    if (!(genericReturnType instanceof ParameterizedType)) {
                        throw new NotParameterizedTypeException(
                                "Path direciona a um Map no parameterizado com generics. " + " Propriedade '"
                                        + this.nestedPath + propertyName + "' da classe ["
                                        + this.rootObject.getClass().getName() + "]");
                    }
                    ParameterizedType parameterizedType = ((ParameterizedType) genericReturnType);
                    Type mapKeyType = parameterizedType.getActualTypeArguments()[0];
                    Type mapValueType = parameterizedType.getActualTypeArguments()[1];
                    Class rawKeyType = mapKeyType instanceof Class ? (Class) mapKeyType
                            : (Class) ((ParameterizedType) mapKeyType).getRawType();
                    Class rawValueType = mapValueType instanceof Class ? (Class) mapValueType
                            : (Class) ((ParameterizedType) mapValueType).getRawType();
                    Object objectKey = doTypeConversionIfNecessary(key, rawKeyType);
                    Map map = (Map) value;
                    value = map.get(objectKey);
                    if (value == null && List.class.isAssignableFrom(rawValueType)) {
                        List mapValue;
                        try {
                            Type listType = ((ParameterizedType) mapValueType).getActualTypeArguments()[0];
                            mapValue = new ListSet(listType instanceof Class ? (Class) listType
                                    : (Class) ((ParameterizedType) listType).getRawType());
                        } catch (ClassCastException e) {
                            throw new RuntimeException(
                                    "Na path " + propertyName + " um mapa contm uma lista no parametrizada");
                        }
                        map.put(objectKey, mapValue);
                        value = mapValue;
                    }
                } else {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Property referenced in indexed property path '" + propertyName
                                    + "' is neither an array nor a List nor a Set nor a Map; returned value was ["
                                    + value + "]");
                }
            }
        }
        return value;
    } catch (InvocationTargetException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Getter for property '" + actualName + "' threw exception", ex);
    } catch (IllegalAccessException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Illegal attempt to get property '" + actualName + "' threw exception", ex);
    } catch (IndexOutOfBoundsException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Index of out of bounds in property path '" + propertyName + "'", ex);
    } catch (NumberFormatException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    }
}

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

private void processLinkedCollectionsBeforePersist(INakedObject o, Set<PropertyDescriptor> linkedObjects)
        throws IllegalAccessException, InvocationTargetException, ClassNotFoundException,
        IntrospectionException, PersistenceException {
    if (linkedObjects != null && !linkedObjects.isEmpty()) {
        for (PropertyDescriptor pd : linkedObjects) {
            pd.getWriteMethod().invoke(o, nullArg);
        }/*from  w w w. j  av  a 2 s.  c  o m*/
    }
}

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

@Override
public void updateAttributeValue(String className, INakedObject original, String att, Object object)
        throws PersistenceException {
    for (PropertyDescriptor pd : propertyDescriptorsByClassName.get(className)) {
        if (pd.getName() != null && pd.getName().equals(att) && pd.getWriteMethod() != null) {
            try {
                pd.getWriteMethod().invoke(original, object);
                return;
            } catch (Exception e) {
                throw new PersistenceException(e);
            }//from  w  w w.  j av  a  2s  . c  o m
        }
    }
}

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

@Override
public Object saveFile(String fileClass, String fileNameField, String fileStorageField, String fileName,
        FileItem item) throws PersistenceException {
    getIdFieldFromFileStorageClass(fileClass);
    TransactionContext tc = null;/*from  w  ww.  j  ava 2s . c om*/
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        Class clazz = Class.forName(fileClass);
        Object o = clazz.newInstance();
        for (PropertyDescriptor pd : propertyDescriptorsByClassName.get(fileClass)) {
            if (fileNameField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileName);
            } else if (fileStorageField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, item.get());
            }
        }
        em.persist(o);
        tx.commit();
        return idsByClassName.get(fileClass).iterator().next().getReadMethod().invoke(o, new Object[0]);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
        try {
            if (tc != null)
                tc.rollback();
        } catch (Exception ee) {
        }
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }

}

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

private void setObject(INakedObject o, PropertyDescriptor pd, INakedObject newObj)
        throws IllegalAccessException, InvocationTargetException {
    Object[] args = new Object[1];
    args[0] = newObj;//from   ww  w .j ava 2 s.c om
    pd.getWriteMethod().invoke(o, args);
}

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

@Override
public String replaceFile(String fileClass, String fileNameField, String fileStorageField, String fileName,
        FileItem fileItem, String existingId) throws PersistenceException {
    String idField = getIdFieldFromFileStorageClass(fileClass);
    boolean error = false;
    TransactionContext tc = null;/*from   ww  w .  ja v  a  2 s .  c o m*/
    Object id = null;
    PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(fileClass);

    try {
        id = getFileId(existingId, idField, pds);
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        Object o;
        Class<?> clazz = Class.forName(fileClass);
        o = em.find(clazz, id);
        for (PropertyDescriptor pd : pds) {
            if (fileNameField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileName);
            } else if (fileStorageField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileItem.get());
            }
        }
        em.merge(o);

        tx.commit();
        //idsByClassName.get(fileClass).iterator().next().getReadMethod().invoke(o, new Object[0]);
    } catch (Exception e) {
        error = true;
        logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
        try {
            if (tc != null)
                tc.rollback();
        } catch (Exception ee) {
        }
    } finally {
        if (tc != null) {
            if (!error)
                close(tc);
            else
                tc.close();
        }
    }
    if (error) {
        try {
            tc = createTransactionalContext();
            EntityManager em = tc.getEm();
            ITransaction tx = tc.getTx();
            tx.begin();
            Class<?> clazz = Class.forName(fileClass);
            em.createQuery("delete from " + fileClass + " o where o." + idField + " = :id")
                    .setParameter("id", id).executeUpdate();
            Object newDoc = clazz.newInstance();
            for (PropertyDescriptor pd : pds) {
                if (fileNameField.equals(pd.getName())) {
                    pd.getWriteMethod().invoke(newDoc, fileName);
                } else if (fileStorageField.equals(pd.getName())) {
                    pd.getWriteMethod().invoke(newDoc, fileItem.get());
                }
            }
            em.persist(newDoc);
            tx.commit();
            for (PropertyDescriptor pd : pds) {
                if (idField.equals(pd.getName())) {
                    existingId = pd.getReadMethod().invoke(newDoc, new String[0]).toString();
                    break;
                }
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
            try {
                if (tc != null)
                    tc.rollback();
            } catch (Exception ee) {
            }
            throw new PersistenceException(e.getMessage(), e);
        } finally {
            if (tc != null)
                close(tc);
        }
    }

    return existingId;
}

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

private void setIdField(Set<PropertyDescriptor> loIds, com.hiperf.common.ui.shared.util.Id loId,
        INakedObject newObj, int i, Object id) throws IllegalAccessException, InvocationTargetException {
    for (PropertyDescriptor pdId : loIds) {
        if (pdId.getName().equals(loId.getFieldNames().get(i))) {
            Object[] aa = new Object[1];
            aa[0] = id;//from   w ww  .  j  a v a2s  .  com
            pdId.getWriteMethod().invoke(newObj, aa);
            break;
        }
    }
}

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

@Override
public Collection<INakedObject> deproxyCollection(INakedObject no, String attributeName, EntityManager em,
        Map<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>> deproxyContext)
        throws PersistenceException {
    try {//from w w w .  j a v a2s  .co  m
        String name = no.getClass().getName();
        Set<PropertyDescriptor> colls = collectionsByClassName.get(name);
        if (colls != null && !colls.isEmpty()) {
            for (PropertyDescriptor pd : colls) {
                if (attributeName.equals(pd.getName())) {
                    Method readMethod = pd.getReadMethod();
                    deproxyCollection(no, readMethod, pd.getWriteMethod(),
                            (Collection) readMethod.invoke(no, new Object[0]), null, em, deproxyContext);
                    return (Collection<INakedObject>) readMethod.invoke(no, new Object[0]);
                }
            }
        }
        return null;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in deproxyCollection", e);
        throw new PersistenceException("Exception in deproxyCollection...", e);
    }
}

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

private INakedObject deproxyNakedObject(boolean root, Set<PropertyDescriptor> collections,
        Set<PropertyDescriptor> lazys, Set<PropertyDescriptor> eagers, Set<LinkFileInfo> linkedFiles,
        INakedObject no, Set<PropertyDescriptor> idPds, Map<String, Map<Object, Object>> oldIdByNewId,
        EntityManager em, Map<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>> deproxyContext)
        throws IllegalAccessException, InvocationTargetException, InstantiationException,
        IntrospectionException, ClassNotFoundException, PersistenceException {
    String name = getClassName(no);
    if (isProxy(no, name))
        no = clone(no, name);/* w w  w  .j  a v a2s . c o  m*/
    Map<com.hiperf.common.ui.shared.util.Id, INakedObject> map = deproxyContext.get(name);
    if (map == null) {
        map = new HashMap<com.hiperf.common.ui.shared.util.Id, INakedObject>();
        deproxyContext.put(name, map);
    }
    com.hiperf.common.ui.shared.util.Id noId = getId(no, idsByClassName.get(name));
    if (map.containsKey(noId))
        return no;
    map.put(noId, no);

    if (root && linkedFiles != null && !linkedFiles.isEmpty()) {
        for (LinkFileInfo a : linkedFiles) {
            Object fileId = a.getLocalFileIdGetter().invoke(no, new Object[0]);
            if (fileId != null)
                a.getLocalFileNameSetter().invoke(no,
                        getFileName(a.getFileClassName(), a.getFileNameField(), fileId, getEntityManager()));
        }
    }

    if (collections != null) {
        for (PropertyDescriptor pd : collections) {
            Method readMethod = pd.getReadMethod();
            Method writeMethod = pd.getWriteMethod();
            Object o = readMethod.invoke(no, new Object[0]);
            if (o != null) {
                if (root) {
                    Collection orig = (Collection) o;
                    boolean processed = false;
                    Type type = readMethod.getGenericReturnType();
                    Class classInCollection = null;
                    if (type instanceof ParameterizedType) {
                        classInCollection = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
                    }
                    if (classInCollection != null) {
                        if (Number.class.isAssignableFrom(classInCollection)
                                || String.class.equals(classInCollection)
                                || Boolean.class.equals(classInCollection)) {
                            Collection targetColl;
                            int size = orig.size();
                            if (List.class.isAssignableFrom(readMethod.getReturnType())) {
                                targetColl = new ArrayList(size);
                            } else {
                                targetColl = new HashSet(size);
                            }
                            if (size > 0)
                                targetColl.addAll(orig);
                            writeMethod.invoke(no, targetColl);
                            processed = true;
                        }
                    }
                    if (!processed) {
                        //deproxyCollection(no, readMethod, writeMethod, orig, oldIdByNewId, em, deproxyContext);
                        com.hiperf.common.ui.shared.util.Id id = getId(no, idPds);
                        CollectionInfo ci = null;
                        if (!id.isLocal()) {
                            String className = getClassName(no);
                            String attName = pd.getName();
                            ci = getCollectionInfo(em, id, className, attName);
                        }
                        if (List.class.isAssignableFrom(readMethod.getReturnType())) {
                            if (ci != null)
                                writeMethod.invoke(no,
                                        new LazyList<INakedObject>(ci.getSize(), ci.getDescription()));
                            else
                                writeMethod.invoke(no, new LazyList<INakedObject>());
                        } else {
                            if (ci != null)
                                writeMethod.invoke(no,
                                        new LazySet<INakedObject>(ci.getSize(), ci.getDescription()));
                            else
                                writeMethod.invoke(no, new LazySet<INakedObject>());
                        }
                    }
                } else {
                    if (List.class.isAssignableFrom(readMethod.getReturnType())) {
                        writeMethod.invoke(no, new LazyList<INakedObject>());
                    } else {
                        writeMethod.invoke(no, new LazySet<INakedObject>());
                    }

                }

            }
        }
    }
    if (lazys != null) {
        for (PropertyDescriptor pd : lazys) {
            Method readMethod = pd.getReadMethod();
            Object o = readMethod.invoke(no, new Object[0]);
            if (o != null) {
                Class<?> targetClass = pd.getPropertyType();
                if (root) {
                    String targetClassName = targetClass.getName();
                    if (isProxy(o, targetClassName)) {
                        o = deproxyObject(targetClass, o);
                    }
                    Set<PropertyDescriptor> ids = idsByClassName.get(targetClassName);
                    o = deproxyNakedObject(root, collectionsByClassName.get(targetClassName),
                            lazysByClassName.get(targetClassName), eagerObjectsByClassName.get(targetClassName),
                            linkedFilesByClassName.get(targetClassName), (INakedObject) o, ids, oldIdByNewId,
                            em, deproxyContext);
                    pd.getWriteMethod().invoke(no, o);
                } else {
                    Object lazyObj = newLazyObject(targetClass);

                    pd.getWriteMethod().invoke(no, lazyObj);
                }
            }
        }
    }
    if (eagers != null) {
        for (PropertyDescriptor pd : eagers) {
            String targetClassName = pd.getPropertyType().getName();
            Method readMethod = pd.getReadMethod();
            Object o = readMethod.invoke(no, new Object[0]);
            if (o != null) {
                Set<PropertyDescriptor> ids = idsByClassName.get(targetClassName);
                deproxyNakedObject(root, collectionsByClassName.get(targetClassName),
                        lazysByClassName.get(targetClassName), eagerObjectsByClassName.get(targetClassName),
                        linkedFilesByClassName.get(targetClassName), (INakedObject) o, ids, oldIdByNewId, em,
                        deproxyContext);
            }
        }
    }

    if (oldIdByNewId != null && idPds != null) {
        Map<Object, Object> map2 = oldIdByNewId.get(no.getClass().getName());
        if (map2 != null && !map2.isEmpty()) {
            for (PropertyDescriptor pd : idPds) {
                Object id = pd.getReadMethod().invoke(no, StorageService.emptyArg);
                Object oldId = map2.get(id);
                if (oldId != null) {
                    pd.getWriteMethod().invoke(no, new Object[] { oldId });
                }
            }
        }
    }

    try {
        em.remove(no);
    } catch (Exception e) {
    }
    return no;
}