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:org.paxml.control.IterateTag.java

private ChildrenResultList visitBean(Context context, Object bean, boolean readValue) {
    if (bean == null) {
        return null;
    }//from  ww  w  .j  a  va 2s  . co m
    ChildrenResultList list = null;
    int i = 0;
    for (PropertyDescriptor d : ReflectUtils.getPropertyDescriptors(bean.getClass(),
            PropertyDescriptorType.GETTER)) {
        Method method = d.getReadMethod();
        Object value = null;
        if (readValue) {
            try {
                value = method.invoke(bean);
            } catch (Exception e) {
                throw new PaxmlRuntimeException(
                        "Cannot read property '" + d.getName() + "' from class: " + bean.getClass().getName(),
                        e);
            }
        }

        list = addAll(list, visit(context, bean, d.getName(), i++, value));
    }
    return list;
}

From source file:org.apache.tapestry.enhance.ComponentClassFactory.java

/**
 * @return true if pd is not null and both read/write methods are implemented
 *//*from  w  w w  .ja  v a2  s. c o m*/
public boolean isImplemented(PropertyDescriptor pd) {
    if (pd == null)
        return false;

    return isImplemented(pd.getReadMethod()) && isImplemented(pd.getWriteMethod());
}

From source file:org.apache.struts2.interceptor.debugging.DebuggingInterceptor.java

/**
 * Recursive function to serialize objects to XML. Currently it will
 * serialize Collections, maps, Arrays, and JavaBeans. It maintains a stack
 * of objects serialized already in the current functioncall. This is used
 * to avoid looping (stack overflow) of circular linked objects. Struts and
 * XWork objects are ignored.//from   ww w  .ja v a  2  s .c o m
 *
 * @param bean   The object you want serialized.
 * @param name   The name of the object, used for element <name/>
 * @param writer The XML writer
 * @param stack  List of objects we're serializing since the first calling
 *               of this function (to prevent looping on circular references).
 */
protected void serializeIt(Object bean, String name, PrettyPrintWriter writer, List<Object> stack) {
    writer.flush();
    // Check stack for this object
    if ((bean != null) && (stack.contains(bean))) {
        if (log.isInfoEnabled()) {
            log.info("Circular reference detected, not serializing object: " + name);
        }
        return;
    } else if (bean != null) {
        // Push object onto stack.
        // Don't push null objects ( handled below)
        stack.add(bean);
    }
    if (bean == null) {
        return;
    }
    String clsName = bean.getClass().getName();

    writer.startNode(name);

    // It depends on the object and it's value what todo next:
    if (bean instanceof Collection) {
        Collection col = (Collection) bean;

        // Iterate through components, and call ourselves to process
        // elements
        for (Object aCol : col) {
            serializeIt(aCol, "value", writer, stack);
        }
    } else if (bean instanceof Map) {

        Map map = (Map) bean;

        // Loop through keys and call ourselves
        for (Object key : map.keySet()) {
            Object Objvalue = map.get(key);
            serializeIt(Objvalue, key.toString(), writer, stack);
        }
    } else if (bean.getClass().isArray()) {
        // It's an array, loop through it and keep calling ourselves
        for (int i = 0; i < Array.getLength(bean); i++) {
            serializeIt(Array.get(bean, i), "arrayitem", writer, stack);
        }
    } else {
        if (clsName.startsWith("java.lang")) {
            writer.setValue(bean.toString());
        } else {
            // Not java.lang, so we can call ourselves with this object's
            // values
            try {
                BeanInfo info = Introspector.getBeanInfo(bean.getClass());
                PropertyDescriptor[] props = info.getPropertyDescriptors();

                for (PropertyDescriptor prop : props) {
                    String n = prop.getName();
                    Method m = prop.getReadMethod();

                    // Call ourselves with the result of the method
                    // invocation
                    if (m != null) {
                        serializeIt(m.invoke(bean), n, writer, stack);
                    }
                }
            } catch (Exception e) {
                log.error(e, e);
            }
        }
    }

    writer.endNode();

    // Remove object from stack
    stack.remove(bean);
}

From source file:com.eclecticlogic.pedal.dialect.postgresql.CopyCommand.java

private String extractColumnName(Method method, Class<? extends Serializable> clz) {
    String beanPropertyName = null;
    try {/*from w  w  w.jav a 2 s  . c  om*/
        BeanInfo info;

        info = Introspector.getBeanInfo(clz);

        for (PropertyDescriptor propDesc : info.getPropertyDescriptors()) {
            if (method.equals(propDesc.getReadMethod())) {
                beanPropertyName = propDesc.getName();
                break;
            }
        }
    } catch (IntrospectionException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    String columnName = null;
    if (clz.isAnnotationPresent(AttributeOverrides.class)) {
        for (AttributeOverride annotation : clz.getAnnotation(AttributeOverrides.class).value()) {
            if (annotation.name().equals(beanPropertyName)) {
                columnName = annotation.column().name();
                break;
            }
        }
    } else if (clz.isAnnotationPresent(AttributeOverride.class)) {
        AttributeOverride annotation = clz.getAnnotation(AttributeOverride.class);
        if (annotation.name().equals(beanPropertyName)) {
            columnName = annotation.column().name();
        }
    }
    return columnName == null ? method.getAnnotation(Column.class).name() : columnName;
}

From source file:org.codehaus.groovy.grails.plugins.couchdb.domain.CouchDomainClassProperty.java

public CouchDomainClassProperty(GrailsDomainClass domain, PropertyDescriptor descriptor) {
    this.ownerClass = domain.getClazz();
    this.domainClass = domain;
    this.descriptor = descriptor;
    this.name = descriptor.getName();
    this.type = descriptor.getPropertyType();
    this.getter = descriptor.getReadMethod();

    try {/* ww  w. j a  v  a 2s .  c om*/
        this.field = domain.getClazz().getDeclaredField(descriptor.getName());
    } catch (NoSuchFieldException e) {
        // ignore
    }

    this.persistent = checkPersistence(descriptor);

    checkIfTransient();
}

From source file:dhbw.ka.mwi.businesshorizon2.ui.process.period.input.AbstractInputPresenter.java

public void processEvent(ShowInputViewEventInterface event) {
    logger.debug("ShowDirektViewEvent erhalten");
    period = event.getPeriod();//from ww w .j av  a 2  s  .  c  o m
    getView().initForm();
    getView().addHeader(period.getYear());

    try {
        for (PropertyDescriptor pd : Introspector.getBeanInfo(period.getClass(), Object.class)
                .getPropertyDescriptors()) {
            logger.debug("Processing: " + pd.getName());
            if (Arrays.asList(shownProperties).contains(pd.getDisplayName())) {
                try {
                    String germanName;
                    germanName = germanNamesProperties[Arrays.asList(shownProperties)
                            .indexOf(pd.getDisplayName())];
                    boolean skipInitialContent = true;
                    for (PropertyDescriptor pdr : Introspector.getBeanInfo(period.getClass(), Object.class)
                            .getPropertyDescriptors()) {
                        if ((pd.getDisplayName() + "Set").equals(pdr.getDisplayName())) {

                            skipInitialContent = !(boolean) pdr.getReadMethod().invoke(period);
                            logger.debug("method found and skipInitialContent set to " + skipInitialContent);
                        }
                    }
                    if (skipInitialContent) {
                        getView().addInputField(germanName);
                        logger.debug("initialContent skipped");

                    } else {
                        getView().addInputField(germanName, (double) pd.getReadMethod().invoke(period));
                        logger.debug("initialContent written");
                    }
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (IntrospectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:de.xwic.appkit.webbase.toolkit.app.EditorToolkit.java

/**
 * Loads the field values into the controls. Entity is coming by internal editor model.
 *//*from   w  w w.  ja v a  2s  . co m*/
public void loadFieldValues() {
    Object obj = null;
    Class<?> clazz = null;
    if (null != baseObj) {
        obj = baseObj;
        clazz = obj.getClass();
    } else if (null != model) {
        obj = model.getEntity();
        clazz = ((IEntity) obj).type();
    }

    for (Iterator<String> iterator = registeredControls.keySet().iterator(); iterator.hasNext();) {
        String controlId = iterator.next();
        IControl control = registeredControls.get(controlId);

        String propName = getPropertyName(control);

        Object value = null;

        try {
            PropertyDescriptor propInfo = new PropertyDescriptor(propName, clazz);
            value = propInfo.getReadMethod().invoke(obj, (Object[]) null);
        } catch (Exception ex) {
            throw new RuntimeException("Property not found: " + propName, ex);
        }

        IToolkitControlHelper helper = allControls.get(control.getClass());

        if (helper == null) {
            throw new RuntimeException("Could not find control helper: " + control.getClass());
        }

        Object controlValue;
        ITypeConverter converter = registeredConverters.get(propName);
        if (converter != null) {
            //if we have a type converter registered for the property, convert the entity type to the control value type first
            controlValue = converter.convertLeft(value);
        } else {
            controlValue = value;
        }

        helper.loadContent(control, controlValue);
    }
}

From source file:com.expressui.core.dao.query.EntityQuery.java

/**
 * Clear this query so that all filters (query parameters) and sort-criteria are removed (except for defaults).
 * The method uses reflection to clear any filters defined as bean properties by subclasses. Once cleared,
 * re-execution of query results in all records being found or a default list of default filters are specified.
 *
 * @see #initializeDefaults/*w ww  .j  a  va2 s  .co  m*/
 */
public void clear() {
    try {
        for (PropertyDescriptor descriptor : descriptors) {
            Method writeMethod = descriptor.getWriteMethod();
            Method readMethod = descriptor.getReadMethod();
            if (readMethod != null && writeMethod != null
                    && !writeMethod.getDeclaringClass().equals(EntityQuery.class)
                    && !writeMethod.getDeclaringClass().equals(Object.class)) {
                Class type = descriptor.getPropertyType();
                if (type.isPrimitive() && !type.isArray()) {
                    if (ReflectionUtil.isNumberType(type)) {
                        writeMethod.invoke(this, 0);
                    } else if (Boolean.class.isAssignableFrom(type)) {
                        writeMethod.invoke(this, false);
                    }
                } else {
                    writeMethod.invoke(this, new Object[] { null });
                }
            }
        }
    } catch (IllegalAccessException e) {
        Assert.PROGRAMMING.fail(e);
    } catch (InvocationTargetException e) {
        Assert.PROGRAMMING.fail(e);
    }

    initializeDefaults();
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * Applies a collection of properties to a JavaBean. Converts String and
 * String[] values to correct property types
 * //from w w  w .  ja v  a2 s  . c  o  m
 * @param properties A map of the properties to set on the JavaBean
 * @param bean The JavaBean to set the properties on
 */
public void convertPropertiesToBean(Map<String, Object> properties, Object bean) throws IntrospectionException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException {
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
    for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) {
        String name = p.getName();
        Object value = properties.get(name);
        Method reader = p.getReadMethod();
        Method writer = p.getWriteMethod();
        // we only care about "complete" properties
        if (reader != null && writer != null && value != null) {
            Class<?> propertyType = writer.getParameterTypes()[0];
            if (isBean(propertyType)) {
                // this is a bean
                if (propertyType.isArray()) {
                    propertyType = propertyType.getComponentType();
                    Object beanArray = Array.newInstance(propertyType, 1);

                    if (value.getClass().isArray()) {
                        Object[] valueArrary = (Object[]) value;
                        int length = valueArrary.length;
                        beanArray = Array.newInstance(propertyType, length);
                        for (int index = 0; index < valueArrary.length; ++index) {
                            Object valueObject = valueArrary[index];
                            fillBeanInArray(propertyType, beanArray, index, valueObject);
                        }
                    } else {
                        fillBeanInArray(propertyType, beanArray, 0, value);
                    }
                    value = beanArray;
                } else if (propertyType == Timestamp.class) {
                    value = new Timestamp(TIMESTAMP_FORMAT.parse((String) value).getTime());
                } else {
                    Object beanObject = createBeanObject(propertyType, value);
                    value = beanObject;
                }
            } else {
                Class<?> valueType = value.getClass();
                if (!propertyType.isAssignableFrom(valueType)) {
                    // convert string input values to property type
                    try {
                        if (valueType == String.class) {
                            value = ConvertUtils.convert((String) value, propertyType);
                        } else if (valueType == String[].class) {
                            value = ConvertUtils.convert((String[]) value, propertyType);
                        } else if (valueType == Object[].class) {
                            // best effort conversion
                            Object[] objectValues = (Object[]) value;
                            String[] stringValues = new String[objectValues.length];
                            for (int i = 0; i < objectValues.length; i++) {
                                stringValues[i] = objectValues[i] == null ? null : objectValues[i].toString();
                            }
                            value = ConvertUtils.convert(stringValues, propertyType);
                        } else {
                        }
                    } catch (ConversionException e) {
                        throw new IllegalArgumentException(
                                "Conversion failed for " + "property '" + name + "' with value '" + value + "'",
                                e);
                    }
                }
            }
            // We only write values that are present in the map. This allows
            // defaults or previously set values in the bean to be retained.
            writer.invoke(bean, value);
        }
    }
}

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

public void populateEntityCacheData() throws HibernateException {

    Iterator itr = null;/*from  w  ww.ja  v  a  2 s. c  o m*/
    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);
                }
            }
        }
    }
}