Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

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

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

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

Usage

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

private static void processMethod(String className, PropertyDescriptor[] pds, Set<PropertyDescriptor> ids,
        Set<PropertyDescriptor> collections, Set<PropertyDescriptor> lazys, Set<PropertyDescriptor> eagers,
        Set<LinkFileInfo> linkedFiles, PropertyDescriptor pd) throws PersistenceException {
    Method readMethod = pd.getReadMethod();
    if (readMethod != null) {
        if (readMethod.isAnnotationPresent(Id.class)) {
            ids.add(pd);/*from  w  w w. ja v a 2s. c o m*/
            if (readMethod.isAnnotationPresent(GeneratedValue.class)) {
                generatedIdClasses.add(className);
            }
        }
        OneToMany oneToMany = readMethod.getAnnotation(OneToMany.class);
        if (oneToMany != null) {
            collections.add(pd);
        } else {
            ManyToMany manyToMany = readMethod.getAnnotation(ManyToMany.class);
            if (manyToMany != null) {
                collections.add(pd);
            } else if (INakedObject.class.isAssignableFrom(pd.getPropertyType())) {
                OneToOne oneToOne = readMethod.getAnnotation(OneToOne.class);
                if (oneToOne != null) {
                    if (oneToOne.fetch().equals(FetchType.LAZY))
                        lazys.add(pd);
                    else
                        eagers.add(pd);
                } else {
                    ManyToOne manyToOne = readMethod.getAnnotation(ManyToOne.class);
                    if (manyToOne != null) {
                        if (manyToOne.fetch().equals(FetchType.LAZY))
                            lazys.add(pd);
                        else
                            eagers.add(pd);
                    } else {
                        Basic basic = readMethod.getAnnotation(Basic.class);
                        if (basic != null) {
                            if (basic.fetch().equals(FetchType.LAZY))
                                lazys.add(pd);
                            else
                                eagers.add(pd);
                        }
                    }
                }
            }
        }
        //processLinkedFiles(pds, linkedFiles, pd);
    }
}

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

/**
 * <p>/*w ww. j  a va  2 s .c om*/
 * Return the entire set of properties for which the specified bean provides
 * a read method. This map contains the unconverted property values for all
 * properties for which a read method is provided (i.e. where the
 * <code>getReadMethod()</code> returns non-null).
 * </p>
 *
 * <p>
 * <strong>FIXME</strong> - Does not account for mapped properties.
 * </p>
 *
 * @param bean
 *            Bean whose properties are to be extracted
 * @return The set of properties for the bean
 *
 * @throws IllegalAccessException
 *             if the caller does not have access to the property accessor
 *             method
 * @throws IllegalArgumentException
 *             if <code>bean</code> is null
 * @throws InvocationTargetException
 *             if the property accessor method throws an exception
 * @throws NoSuchMethodException
 *             if an accessor method for this propety cannot be found
 */
public Map<String, Object> describe(final Object bean)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }
    final Map<String, Object> description = new HashMap<String, Object>();
    {
        final PropertyDescriptor[] descriptors = getPropertyDescriptors(bean);
        for (final PropertyDescriptor descriptor : descriptors) {
            final String name = descriptor.getName();
            if (descriptor.getReadMethod() != null) {
                description.put(name, getProperty(bean, name));
            }
        }
    }
    return description;

}

From source file:org.evergreen.web.utils.beanutils.BeanUtilsBean.java

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>/*from w  w  w  .j a va  2s .  c  om*/
 *
 * @param bean Bean on which setting is to be performed
 * @param name Property name (can be nested/indexed/mapped/combo)
 * @param value Value to be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
public void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {
    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        sb.append(bean);
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String[] values = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    Resolver resolver = getPropertyUtils().getResolver();
    while (resolver.hasNested(name)) {
        try {
            target = getPropertyUtils().getProperty(target, resolver.next(name));
            name = resolver.remove(name);
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("    Target bean = " + target);
        log.trace("    Target name = " + name);
    }

    // Declare local variables we will require
    String propName = resolver.getProperty(name); // Simple name of target property
    Class type = null; // Java type of target property
    int index = resolver.getIndex(name); // Indexed subscript value (if any)
    String key = resolver.getKey(name); // Mapped key value (if any)

    // Calculate the property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else if (target instanceof Map) {
        type = Object.class;
    } else if (target != null && target.getClass().isArray() && index >= 0) {
        type = Array.get(target, index).getClass();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else if (key != null) {
            if (descriptor.getReadMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = (value == null) ? Object.class : value.getClass();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String[] values = new String[1];
            values[0] = null;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String) {
            newValue = getConvertUtils().convert(value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = convert(value, type);
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String || value == null) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = convert(value, type.getComponentType());
        }
    } else { // Value into scalar
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else {
            newValue = convert(value, type);
        }
    }

    // Invoke the setter method
    try {
        getPropertyUtils().setProperty(target, name, newValue);
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:org.ajax4jsf.builder.config.ComponentBaseBean.java

/**
 * @param superClass/*from   w  w w.  j av a 2s . co m*/
 */
private void checkPropertiesForClass(Class<?> superClass) {
    getLog().debug("Check properties for class " + superClass.getName());
    // get all property descriptors
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(superClass);
    // for all properties, add it to component. If property have not abstract getter/setter ,
    // add it with exist = true . If property in list of hidden names, set hidden = true.
    PropertyBean property;
    for (int i = 0; i < properties.length; i++) {
        PropertyDescriptor descriptor = properties[i];
        if (!containProperty(descriptor.getName())) {
            if (isIgnorableProperty(superClass, descriptor.getName())) {
                continue;
            }
            Class<?> type = descriptor.getPropertyType();
            getLog().debug("Register property  " + descriptor.getName() + " with type name "
                    + type.getCanonicalName());
            property = new PropertyBean();
            property.setName(descriptor.getName());
            property.setDescription(descriptor.getShortDescription());
            property.setDisplayname(descriptor.getDisplayName());
            property.setClassname(descriptor.getPropertyType().getCanonicalName());
            property.setExist(true);
            addProperty(property);
        } else {
            // Load and check property.
            getLog().debug("Check  property  " + descriptor.getName());
            property = (PropertyBean) this.properties.get(descriptor.getName());
            if (property.getClassname() == null) {
                property.setClassname(descriptor.getPropertyType().getCanonicalName());
            } else {
                if (!property.getClassname().equals(descriptor.getPropertyType().getCanonicalName())) {
                    String message = "Class " + property.getClassname() + " for property " + property.getName()
                            + " not equals with real bean property type: "
                            + descriptor.getPropertyType().getCanonicalName();
                    getLog().error(message);
                    //throw new IllegalArgumentException(message);
                }
            }
            if (property.getDescription() == null) {
                property.setDescription(descriptor.getShortDescription());
            }
            if (property.getDisplayname() == null) {
                property.setDisplayname(descriptor.getDisplayName());
            }
            property.setExist(true);
        }
        Method getter = descriptor.getReadMethod();
        Method setter = descriptor.getWriteMethod();
        // Abstract methods
        if (null != setter && null != getter) {
            if ((Modifier.isAbstract(getter.getModifiers()) && Modifier.isAbstract(setter.getModifiers()))
                    || superClass.isInterface()) {
                getLog().debug("Detect as abstract property  " + descriptor.getName());
                property.setExist(false);
            }
        }

        if (null == setter || (!Modifier.isPublic(setter.getModifiers()))) {
            getLog().debug("Detect as hidden property  " + descriptor.getName());
            property.setHidden(true);
        }
        if (isAttachedProperty(property)) {
            property.setAttachedstate(true);
        }
        if (property.isInstanceof("javax.faces.el.MethodBinding")
                || property.isInstanceof("javax.faces.el.ValueBinding")) {
            property.setElonly(true);
        }

    }
}

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;/* ww w  . j av 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()) {
                // #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);
        }
    }
}

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

private com.hiperf.common.ui.shared.util.Id getId(INakedObject o, Set<PropertyDescriptor> ids)
        throws IllegalAccessException, InvocationTargetException {
    com.hiperf.common.ui.shared.util.Id myOldId;
    List<Object> idList = new ArrayList<Object>();
    List<String> idFields = new ArrayList<String>();
    for (PropertyDescriptor pd : ids) {
        idFields.add(pd.getName());/*from  ww  w.  ja  va  2  s  . com*/
        idList.add(pd.getReadMethod().invoke(o, StorageService.emptyArg));
    }
    myOldId = new com.hiperf.common.ui.shared.util.Id(idFields, idList);
    return myOldId;
}

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

private boolean processLinkedObjectsBeforePersist(Map<Object, IdHolder> newIdByOldId, INakedObject o,
        Set<PropertyDescriptor> linkedObjects, ObjectsToPersist toPersist)
        throws IllegalAccessException, InvocationTargetException, ClassNotFoundException,
        IntrospectionException, PersistenceException, InstantiationException {
    if (linkedObjects != null && !linkedObjects.isEmpty()) {
        for (PropertyDescriptor pd : linkedObjects) {
            INakedObject no = (INakedObject) pd.getReadMethod().invoke(o, StorageService.emptyArg);
            if (no != null) {
                Class<? extends INakedObject> linkedClass = no.getClass();
                String linkedClassName = linkedClass.getName();
                Set<PropertyDescriptor> loIds = idsByClassName.get(linkedClassName);
                com.hiperf.common.ui.shared.util.Id loId = getId(no, loIds);
                if (loId.isLocal()) {
                    INakedObject newObj = linkedClass.newInstance();
                    int i = 0;
                    for (Object id : loId.getFieldValues()) {
                        if ((id instanceof Long && ((Long) id).longValue() < 0) || (id instanceof String
                                && ((String) id).startsWith(PersistenceManager.SEQ_PREFIX))) {
                            IdHolder ids = newIdByOldId.get(id);
                            if (ids == null)
                                return false;
                            else
                                id = ids.getId();
                        }/* w w  w.  j a v  a2s . c o  m*/
                        setIdField(loIds, loId, newObj, i, id);
                        i++;
                    }
                    setObject(o, pd, newObj);
                } else if (!newIdByOldId
                        .containsValue(new IdHolder(loId.getFieldValues().get(0), linkedClassName))
                        && toPersist.getUpdatedObjects() != null
                        && toPersist.getUpdatedObjects().containsKey(linkedClassName)
                        && toPersist.getUpdatedObjects().get(linkedClassName).get(loId) != null) {
                    INakedObject newObj = linkedClass.newInstance();
                    int i = 0;
                    for (Object id : loId.getFieldValues()) {
                        setIdField(loIds, loId, newObj, i, id);
                        i++;
                    }
                    setObject(o, pd, newObj);
                }
            }
        }
    }
    return true;
}

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

private INakedObject deproxyLinkedObject(INakedObject no, String attributeName, Set<PropertyDescriptor> colls,
        EntityManager em) throws IllegalAccessException, InvocationTargetException, InstantiationException,
        IntrospectionException, PersistenceException, ClassNotFoundException {

    for (PropertyDescriptor pd : colls) {
        if (attributeName.equals(pd.getName())) {
            Method readMethod = pd.getReadMethod();
            INakedObject linkedObj = (INakedObject) readMethod.invoke(no, new Object[0]);
            return deproxyNakedObject(linkedObj, em,
                    new HashMap<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>>());
        }//  w  ww  .ja  va 2 s  . co m
    }
    return null;
}

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 {//w w w .j a v a 2  s . 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);/*from  w ww.j ava  2s. 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;
}