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:com.webpagebytes.cms.engine.JSONToFromObjectConverter.java

public <T> T objectFromJSONString(String jsonString, Class<T> objClass) {
    try {/* ww  w  .  j av  a  2  s.c  o m*/
        org.json.JSONObject json = new org.json.JSONObject(jsonString);
        T newObj = objClass.newInstance();
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields) {
            Object storeAdn = field.getAnnotation(WPBAdminFieldStore.class);
            if (storeAdn == null) {
                storeAdn = field.getAnnotation(WPBAdminFieldKey.class);
                if (storeAdn == null) {
                    storeAdn = field.getAnnotation(WPBAdminFieldTextStore.class);
                    if (storeAdn == null) {
                        storeAdn = field.getAnnotation(WPBAdminField.class);
                    }
                }
            }

            if (storeAdn != null) {
                String fieldName = field.getName();
                try {
                    PropertyDescriptor pd = new PropertyDescriptor(fieldName, objClass);
                    Object fieldValue = fieldFromJSON(json, fieldName, field.getType());
                    if (fieldValue != null) {
                        pd.getWriteMethod().invoke(newObj, fieldFromJSON(json, fieldName, field.getType()));
                    }
                } catch (Exception e) {
                    // do nothing, there is no write method for our field
                }
            }
        }

        return newObj;

    } catch (Exception e) {
        // do nothing
    }
    return null;

}

From source file:org.hopen.framework.rewrite.CachedIntrospectionResults.java

private PropertyDescriptor buildGenericTypeAwarePropertyDescriptor(Class beanClass, PropertyDescriptor pd) {
    try {//w w  w .j a  v  a  2  s .c  o m
        return new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(),
                pd.getWriteMethod(), pd.getPropertyEditorClass());
    } catch (IntrospectionException ex) {
        throw new FatalBeanException("Failed to re-introspect class [" + beanClass.getName() + "]", ex);
    }
}

From source file:com.lakeside.data.sqldb.BaseDao.java

/**
 * ?//from  w ww .  j ava  2s  .com
 * @param entity
 * @return
 */
public T merge(final T entity) {
    Assert.notNull(entity, "entity?");
    Session session = getSession();
    String idName = getIdName();
    PropertyDescriptor idp = BeanUtils.getPropertyDescriptor(entityClass, idName);
    PK idvalue = null;
    try {
        idvalue = (PK) idp.getReadMethod().invoke(entity);
    } catch (Exception e) {
        throw new FatalBeanException("Could not copy properties from source to target", e);
    }
    T dest = null;
    if (idvalue != null) {
        dest = (T) session.get(entityClass, idvalue);
    }
    if (dest != null) {
        // merge the properties
        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(entityClass);
        for (PropertyDescriptor p : descriptors) {
            if (p.getWriteMethod() != null) {
                try {
                    Method readMethod = p.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(entity);
                    if (value == null) {
                        continue;
                    }
                    Method writeMethod = p.getWriteMethod();
                    if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                        writeMethod.setAccessible(true);
                    }
                    writeMethod.invoke(dest, value);
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    } else {
        // destination object is empty, save the entity object parameted
        dest = entity;
    }
    session.saveOrUpdate(dest);
    logger.debug("merge entity: {}", entity);
    return dest;
}

From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java

public void populateEntityCacheData() throws HibernateException {

    Iterator itr = null;//from   w  w w .  j a  v a  2 s. com
    if (!useEjb)
        itr = configuration.getClassMappings();
    else
        itr = ejb3Configuration.getClassMappings();

    while (itr.hasNext()) {
        Class entityClass = ((PersistentClass) itr.next()).getMappedClass(); //(Class) classMappings.next();
        log.warn(entityClass.getName());
        if (!Entity.class.isAssignableFrom(entityClass))
            continue;

        Class[] innerClasses = entityClass.getDeclaredClasses();
        for (Class innerClass : innerClasses) {
            // TODO: assume that this is the inner CACHE class !???!!! maybe make Cache extend an interface to indicate this??
            if (innerClass.isEnum() && !entityClass.equals(Party.class)) {
                try {
                    final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass);
                    final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
                    final Hashtable pdsByName = new Hashtable();
                    for (int i = 0; i < descriptors.length; i++) {
                        final PropertyDescriptor descriptor = descriptors[i];
                        if (descriptor.getWriteMethod() != null)
                            pdsByName.put(descriptor.getReadMethod().getName(), descriptor.getWriteMethod());
                    }

                    Object[] enumObjects = innerClass.getEnumConstants();
                    // now match the enum methods with the enclosing class' methods
                    for (Object enumObj : enumObjects) {
                        Object entityObj = entityClass.newInstance();
                        final Method[] enumMethods = enumObj.getClass().getMethods();
                        for (Method enumMethod : enumMethods) {
                            final Method writeMethod = (Method) pdsByName.get(enumMethod.getName());
                            if (writeMethod != null) {
                                writeMethod.invoke(entityObj, enumMethod.invoke(enumObj));
                            }
                        }
                        HibernateUtil.getSession().save(entityObj);
                    }
                } catch (IntrospectionException e) {
                    log.error(e);
                } catch (IllegalAccessException e) {
                    log.error(e);
                } catch (InstantiationException e) {
                    log.error(e);
                } catch (InvocationTargetException e) {
                    log.error(e);
                } catch (HibernateException e) {
                    log.error(e);
                }
            }
        }
    }
}

From source file:org.walkmod.conf.entities.impl.ConfigurationImpl.java

private List<PropertyDefinition> getProperties(Object o) {
    List<PropertyDefinition> result = new LinkedList<PropertyDefinition>();
    PropertyDescriptor[] properties = BeanUtils.getPropertyDescriptors(o.getClass());
    if (properties != null) {
        for (PropertyDescriptor pd : properties) {
            if (pd.getWriteMethod() != null) {
                String name = pd.getDisplayName();
                Class<?> clazz = pd.getPropertyType();
                String type = clazz.getSimpleName();
                String value = "";
                if (String.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz)
                        || clazz.isPrimitive()) {
                    if (pd.getReadMethod() != null) {
                        try {
                            value = pd.getReadMethod().invoke(o).toString();
                        } catch (Exception e) {
                        }/*  www.  ja va  2s.co m*/
                    } else {
                        Field[] fields = o.getClass().getDeclaredFields();
                        boolean found = false;
                        for (int i = 0; i < fields.length && !found; i++) {
                            if (fields[i].getName().equals(name)) {
                                found = true;
                                fields[i].setAccessible(true);
                                try {
                                    value = fields[i].get(o).toString();
                                } catch (Exception e) {
                                }
                            }
                        }
                    }
                }

                PropertyDefinition item = new PropertyDefinitionImpl(type, name, value);

                result.add(item);
            }
        }
    }
    return result;
}

From source file:org.jaffa.soa.dataaccess.TransformerUtils.java

/**
 * Same as printGraph(Object source), except the objectStack lists all the parent
 * objects its printed, and if this is one of them, it stops. This allows detection
 * of possible infinite recusion.//from   ww w .j  a  va  2 s  .c o  m
 *
 * @param source      Javabean who's contents should be printed
 * @param objectStack List of objects already traversed
 * @return multi-line string of this beans properties and their values
 */
public static String printGraph(Object source, List objectStack) {
    if (source == null)
        return null;

    // Prevent infinite object recursion
    if (objectStack != null)
        if (objectStack.contains(source))
            return "Object Already Used. " + source.getClass().getName() + '@' + source.hashCode();
        else
            objectStack.add(source);
    else {
        objectStack = new ArrayList();
        objectStack.add(source);
    }

    StringBuffer out = new StringBuffer();
    out.append(source.getClass().getName());
    out.append("\n");

    try {
        BeanInfo sInfo = Introspector.getBeanInfo(source.getClass());
        PropertyDescriptor[] sDescriptors = sInfo.getPropertyDescriptors();
        if (sDescriptors != null && sDescriptors.length != 0)
            for (int i = 0; i < sDescriptors.length; i++) {
                PropertyDescriptor sDesc = sDescriptors[i];
                Method sm = sDesc.getReadMethod();
                if (sm != null && sDesc.getWriteMethod() != null) {
                    if (!sm.isAccessible())
                        sm.setAccessible(true);
                    Object sValue = sm.invoke(source, (Object[]) null);

                    out.append("  ");
                    out.append(sDesc.getName());
                    if (source instanceof GraphDataObject) {
                        if (((GraphDataObject) source).hasChanged(sDesc.getName()))
                            out.append('*');
                    }
                    out.append('=');
                    if (sValue == null)
                        out.append("<--NULL-->\n");
                    else if (sm.getReturnType().isArray()
                            && !sm.getReturnType().getComponentType().isPrimitive()) {
                        StringBuffer out2 = new StringBuffer();
                        out2.append("Array of ");
                        out2.append(sm.getReturnType().getComponentType().getName());
                        out2.append("\n");
                        // Loop through array
                        Object[] a = (Object[]) sValue;
                        for (int j = 0; j < a.length; j++) {
                            out2.append('[');
                            out2.append(j);
                            out2.append("] ");
                            if (a[j] == null)
                                out2.append("<--NULL-->");
                            else if (GraphDataObject.class.isAssignableFrom(a[j].getClass()))
                                out2.append(((GraphDataObject) a[j]).toString(objectStack));
                            else
                                //out2.append(StringHelper.linePad(a[j].toString(), 4, " ",true));
                                out2.append(a[j].toString());
                        }
                        out.append(StringHelper.linePad(out2.toString(), 4, " ", true));
                    } else {
                        if (GraphDataObject.class.isAssignableFrom(sValue.getClass()))
                            out.append(StringHelper.linePad(((GraphDataObject) sValue).toString(objectStack), 4,
                                    " ", true));
                        else {
                            out.append(StringHelper.linePad(sValue.toString(), 4, " ", true));
                            out.append("\n");
                        }

                    }
                }
            }
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, "???", e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    } catch (InvocationTargetException e) {
        TransformException me = new TransformException(TransformException.INVOCATION_ERROR, "???", e);
        log.error(me.getLocalizedMessage(), me.getCause());
        //throw me;
    } catch (IntrospectionException e) {
        TransformException me = new TransformException(TransformException.INTROSPECT_ERROR, "???",
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    }
    return out.toString();
}

From source file:org.springbyexample.util.log.LoggerBeanPostProcessor.java

/**
 * Processes a property descriptor to inject a logger.
 *///from   w w w. j  a va 2  s. c  o m
public void injectMethod(Object bean, Method method) {
    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);

    if (pd != null) {
        String canonicalName = pd.getPropertyType().getCanonicalName();

        Object logger = getLogger(bean.getClass().getName(), canonicalName);

        if (logger != null) {
            try {
                pd.getWriteMethod().invoke(bean, new Object[] { logger });
            } catch (Throwable e) {
                throw new FatalBeanException("Problem injecting logger.  " + e.getMessage(), e);
            }
        }
    }
}

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

/**
 * Subclasses should extend this method to provide specifc checks
 * /*from  w w w  . j a v a2s  . co  m*/
 * Check existing and default properties
 * For properties filled from configuration, attempt to set additional parameters.
 * If base class have any bean properties, append it to configured
 * @throws ConfigurationException 
 */
public void checkProperties() throws ParsingException {
    try {
        getLog().debug("Parse properties for Component " + getName() + " with superclass " + getSuperclass());
        if (getSuperclass() != null) {
            Class<?> superClass = getLoader().loadClass(getSuperclass());

            new ClassWalkingLogic(superClass).walk(new ClassVisitor() {
                public void visit(Class<?> clazz) {
                    checkPropertiesForClass(clazz);
                }
            });
        }
    } catch (ClassNotFoundException e) {
        getLog().error("superclass not found for component " + getName(), e);
    }
    if (null != getTag()) {
        try {
            Class superClass = getLoader().loadClass(getTag().getSuperclass());
            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.
            for (int i = 0; i < properties.length; i++) {
                PropertyDescriptor descriptor = properties[i];
                Method writeMethod = descriptor.getWriteMethod();
                if (containProperty(descriptor.getName())) {
                    if (null != writeMethod && !Modifier.isAbstract(writeMethod.getModifiers())
                            && Modifier.isPublic(writeMethod.getModifiers())) {
                        ((PropertyBean) this.properties.get(descriptor.getName())).setExistintag(true);
                    }
                } else if (null != writeMethod && Modifier.isPublic(writeMethod.getModifiers())) {
                    if (Arrays.asList(enabledTagProperties).contains(descriptor.getName())) {
                        Class type = descriptor.getPropertyType();
                        getLog().debug("Register tag property  " + descriptor.getName() + " with type name "
                                + type.getCanonicalName());
                        PropertyBean property = new PropertyBean();
                        property.setName(descriptor.getName());
                        property.setDescription(descriptor.getShortDescription());
                        property.setDisplayname(descriptor.getDisplayName());
                        property.setClassname(descriptor.getPropertyType().getCanonicalName());
                        property.setExist(true);
                        if (!Modifier.isAbstract(writeMethod.getModifiers())) {
                            property.setExistintag(true);
                        }
                        addProperty(property);
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            getLog().error("superclass not found for tag " + getTag().getName(), e);
        }

    }
}

From source file:org.openengsb.core.ekb.persistence.edb.internal.EDBConverter.java

/**
 * Generate the value for a specific property of a model out of an EDBObject.
 *///w w w .j  a va2  s  .  c  o m
private Object getValueForProperty(PropertyDescriptor propertyDescriptor, EDBObject object) {
    Method setterMethod = propertyDescriptor.getWriteMethod();
    String propertyName = propertyDescriptor.getName();
    Object value = object.getObject(propertyName);
    Class<?> parameterType = setterMethod.getParameterTypes()[0];

    // TODO: OPENENGSB-2719 do that in a better way than just an if-else series
    if (Map.class.isAssignableFrom(parameterType)) {
        List<Class<?>> classes = getGenericMapParameterClasses(setterMethod);
        value = getMapValue(classes.get(0), classes.get(1), propertyName, object);
    } else if (List.class.isAssignableFrom(parameterType)) {
        Class<?> clazz = getGenericListParameterClass(setterMethod);
        value = getListValue(clazz, propertyName, object);
    } else if (value == null) {
        return null;
    } else if (OpenEngSBModel.class.isAssignableFrom(parameterType)) {
        EDBObject obj = edbService.getObject((String) value);
        value = convertEDBObjectToUncheckedModel(parameterType, obj);
        object.remove(propertyName);
    } else if (parameterType.equals(FileWrapper.class)) {
        FileWrapper wrapper = new FileWrapper();
        String filename = object.getString(propertyName + EDBConverterUtils.FILEWRAPPER_FILENAME_SUFFIX);
        String content = (String) value;
        wrapper.setFilename(filename);
        wrapper.setContent(Base64.decodeBase64(content));
        value = wrapper;
        object.remove(propertyName + EDBConverterUtils.FILEWRAPPER_FILENAME_SUFFIX);
    } else if (parameterType.equals(File.class)) {
        return null;
    } else if (object.containsKey(propertyName)) {
        if (parameterType.isEnum()) {
            value = getEnumValue(parameterType, value);
        } else if (Number.class.isAssignableFrom(parameterType)) {
            value = NumberUtils.createNumber((String) value);
        }
    }
    object.remove(propertyName);
    return value;
}

From source file:org.lightadmin.core.web.ApplicationController.java

private Object cloneEntityOfDomain(String entityId, String domainTypeName) {
    DomainTypeAdministrationConfiguration domainTypeConfiguration = configuration.forEntityName(domainTypeName);
    DynamicJpaRepository repository = domainTypeConfiguration.getRepository();

    PersistentEntity persistentEntity = domainTypeConfiguration.getPersistentEntity();
    Serializable id = (Serializable) conversionService.convert(entityId,
            persistentEntity.getIdProperty().getActualType());

    Object found = repository.findOne(id);
    if (found != null) {
        try {/*from ww w  .j a  v a2  s .co  m*/
            Object newInstance = null;
            if (found instanceof CloneableEntity) {
                newInstance = CloneableEntity.class.cast(found).clone();
            } else {
                newInstance = domainTypeConfiguration.getDomainType().newInstance();

                BeanUtils.copyProperties(found, newInstance, persistentEntity.getIdProperty().getName());

                PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(newInstance);

                for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {

                    if (propertyDescriptor.getReadMethod() != null
                            && propertyDescriptor.getWriteMethod() != null) {
                        Object value = propertyDescriptor.getReadMethod().invoke(newInstance);

                        Object newValue = null;
                        try {
                            if (value instanceof SortedSet) {
                                newValue = new TreeSet(SortedSet.class.cast(value));
                            } else if (value instanceof Set) {
                                newValue = new HashSet(Set.class.cast(value));
                            } else if (value instanceof SortedMap) {
                                newValue = new TreeMap(SortedMap.class.cast(value));
                            } else if (value instanceof Collection) {
                                newValue = new ArrayList(Collection.class.cast(value));
                            } else if (value instanceof Map) {
                                newValue = new HashMap(Map.class.cast(value));
                            }
                        } catch (Throwable t) {
                            if (logger.isWarnEnabled()) {
                                logger.warn("Can't clone " + propertyDescriptor.getName(), t);
                            }
                        }

                        if (newValue != null) {
                            propertyDescriptor.getWriteMethod().invoke(newInstance, newValue);
                        }
                    }

                }
            }

            Object saved = repository.saveAndFlush(newInstance);

            PersistentProperty idProperty = persistentEntity.getIdProperty();
            Field idField = idProperty.getField();
            idField.setAccessible(true);
            return idProperty.usePropertyAccess() ? idProperty.getGetter().invoke(saved) : idField.get(saved);
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    } else {
        return null;
    }
}