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.grails.orm.hibernate.support.HibernateBeanWrapper.java

/**
 * Checks Hibernate.isInitialized before calling super method.
 *
 * @param name target property//from   w w  w . ja  v  a2 s .com
 * @return null if false or super'name value if true
 * @throws BeansException
 */
@Override
public Object getPropertyValue(String name) throws BeansException {
    PropertyDescriptor desc = getPropertyDescriptor(name);
    Method method = desc.getReadMethod();
    Object owner = getWrappedInstance();
    try {
        if (Hibernate.isInitialized(method.invoke(owner))) {
            return super.getPropertyValue(name);
        }
    } catch (Exception e) {
        LOG.error("Error checking Hibernate initialization on method " + method.getName() + " for class "
                + owner.getClass().getName(), e);
    }
    return null;
}

From source file:name.martingeisse.wicket.autoform.describe.DefaultAutoformBeanDescriberHelper.java

@Override
protected <A extends Annotation> A getPropertyAnnotation(final PropertyDescriptor propertyDescriptor,
        final Class<A> annotationClass) {
    return propertyDescriptor.getReadMethod().getAnnotation(annotationClass);
}

From source file:com.link_intersystems.beans.PropertyDescriptor2AccessorsTransformer.java

public Object transform(Object input) {
    Object transformed = input;/* w  w w .  j ava2 s . co  m*/
    if (input instanceof PropertyDescriptor) {
        PropertyDescriptor descriptor = PropertyDescriptor.class.cast(input);
        Method readMethod = descriptor.getReadMethod();
        Method writeMethod = descriptor.getWriteMethod();
        List<Method> methods = new ArrayList<Method>();
        if (readMethod != null) {
            methods.add(readMethod);
        }

        if (writeMethod != null) {
            methods.add(writeMethod);
        }
        transformed = methods.iterator();
    }
    return transformed;
}

From source file:com.zigbee.framework.common.util.BeanCopyUtil.java

/**
 * ?/*  w  ww.  ja  v  a 2 s.c  om*/
 * @author tun.tan
 * @Date 2011-9-29 ?11:18:42
 */
public static void copyProps(Object source, Object target, String[] igonre) {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");
    Class<?> actualEditable = target.getClass();
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    Object methodName = null;
    //      Object targetValue=null;
    //?
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {

            try {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (igonre != null) {
                    boolean jump = false;
                    //
                    for (int i = 0; i < igonre.length; i++) {
                        if (igonre[i] == null) {//
                            continue;
                        }
                        if (targetPd.getName().equals(igonre[i])) {//?
                            logger.info(targetPd.getName());
                            jump = true;
                        }
                    }
                    if (jump) {//
                        continue;
                    }
                }
                if (sourcePd != null && sourcePd.getReadMethod() != null) {//
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(source);
                    //Check whether the value is empty, only copy the properties which are not empty
                    //                  targetValue=value;
                    if (value != null) {//
                        Method writeMethod = targetPd.getWriteMethod();
                        methodName = writeMethod.getName();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    }

                }
            } catch (BeansException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage();
                logger.error(errMsg);
                throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause());

            } catch (SecurityException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage();
                logger.error(errMsg);
                throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause());

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage();
                logger.error(errMsg);
                throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause());

            } catch (IllegalAccessException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage();
                logger.error(errMsg);
                throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause());

            } catch (InvocationTargetException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage();
                logger.error(errMsg);
                throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause());

            }

        }
    }
}

From source file:com.cloudera.csd.validation.constraints.components.UniqueFieldValidatorImpl.java

/**
 * @return return the value of the property
 *///from ww w  . j  ava  2 s  .c  o  m
@VisibleForTesting
Object propertyValue(Object obj, String property) {
    try {
        PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(obj, property);
        return desc.getReadMethod().invoke(obj, new Object[] {});
    } catch (Exception e) {
        throw new ValidationException(e);
    }
}

From source file:eagle.log.entity.meta.EntitySerDeserializer.java

public Map<String, byte[]> writeValue(TaggedLogAPIEntity entity, EntityDefinition ed) throws Exception {
    Map<String, byte[]> qualifierValues = new HashMap<String, byte[]>();
    // iterate all modified qualifiers
    for (String fieldName : entity.modifiedQualifiers()) {
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(entity, fieldName);
        Object obj = pd.getReadMethod().invoke(entity);
        Qualifier q = ed.getDisplayNameMap().get(fieldName);
        EntitySerDeser<Object> ser = q.getSerDeser();
        byte[] value = ser.serialize(obj);
        qualifierValues.put(q.getQualifierName(), value);
    }/* ww w  . j  a  v a2s  . c o  m*/
    return qualifierValues;
}

From source file:de.erdesignerng.dialect.ModelItemProperties.java

public void copyTo(T aObject) {

    ModelProperties theProperties = aObject.getProperties();

    try {//from  w w  w .  ja  v  a  2s.co m
        for (PropertyDescriptor theDescriptor : PropertyUtils.getPropertyDescriptors(this)) {
            if (theDescriptor.getReadMethod() != null && theDescriptor.getWriteMethod() != null) {
                Object theValue = PropertyUtils.getProperty(this, theDescriptor.getName());
                if (theValue != null) {
                    theProperties.setProperty(theDescriptor.getName(), theValue.toString());
                } else {
                    theProperties.setProperty(theDescriptor.getName(), null);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Take a source object and try and mold it back it its domain object
 *
 * @param path    The path of this object being processed. This identifies possible parent and/or indexed entries where this object is contained.
 * @param source  Source object to mould from, typically a GraphDataObject
 * @param uow     Transaction handle all creates/update will be performed within. Throws an exception if null.
 * @param handler Possible bean handler to be used when processing this source object graph
 * @return In VALIDATE_ONLY mode the source object will be returned with default data. Else a GraphDataObject with just the key-fields of the root object will be returned if that object was newly created. Else a null will be returned.
 * @throws ApplicationExceptions Thrown if one or more application logic errors are generated during moulding
 * @throws FrameworkException    Thrown if any runtime moulding error has occured.
 *//*w ww. j  av a  2s .com*/
private static GraphDataObject updateGraph(String path, GraphDataObject source, UOW uow,
        ITransformationHandler handler, Mode mode, GraphDataObject newGraph)
        throws ApplicationExceptions, FrameworkException {
    if (log.isDebugEnabled())
        log.debug("Update Bean " + path);
    if (source.getDeleteObject() != null && source.getDeleteObject()) {
        if (mode == Mode.VALIDATE_ONLY) {
            if (log.isDebugEnabled())
                log.debug(
                        "The 'deleteObject' property is true. No prevalidations will be performed. The input object will be returned as is.");
            return source;
        } else {
            if (log.isDebugEnabled())
                log.debug("The 'deleteObject' property is true. Invoking deleteGraph()");
            deleteGraph(path, source, uow, handler);
            return null;
        }
    } else {
        try {
            IPersistent domainObject = null;
            GraphMapping mapping = MappingFactory.getInstance(source);
            Map keys = new LinkedHashMap();
            Class doClass = mapping.getDomainClass();

            // Get the key fields used in the domain object
            // In CLONE mode, get the keys from the new graph, and force the creation of the domain object
            boolean gotKeys = false;
            if (mode == Mode.CLONE) {
                if (newGraph != null)
                    gotKeys = TransformerUtils.fillInKeys(path, newGraph, mapping, keys);
            } else
                gotKeys = TransformerUtils.fillInKeys(path, source, mapping, keys);

            // read DO based on key
            if (gotKeys) {
                // get the method on the DO to read via PK
                Method[] ma = doClass.getMethods();
                Method findByPK = null;
                for (int i = 0; i < ma.length; i++) {
                    if (ma[i].getName().equals("findByPK")) {
                        if (ma[i].getParameterTypes().length == (keys.size() + 1)
                                && (ma[i].getParameterTypes())[0] == UOW.class) {
                            // Found with name and correct no. of input params
                            findByPK = ma[i];
                            break;
                        }
                    }
                }
                if (findByPK == null)
                    throw new ApplicationExceptions(
                            new DomainObjectNotFoundException(TransformerUtils.findDomainLabel(doClass)));

                // Build input array
                Object[] inputs = new Object[keys.size() + 1];
                {
                    inputs[0] = uow;
                    int i = 1;
                    for (Iterator it = keys.values().iterator(); it.hasNext(); i++) {
                        inputs[i] = it.next();
                    }
                }

                // Find Object based on key
                domainObject = (IPersistent) findByPK.invoke(null, inputs);

                if (domainObject != null && mode == Mode.CLONE)
                    throw new ApplicationExceptions(
                            new DuplicateKeyException(TransformerUtils.findDomainLabel(doClass)));

            } else {
                if (log.isDebugEnabled())
                    log.debug("Object " + path
                            + " has either missing or null key values - Assume Create is needed");
            }

            // Create object if not found
            boolean createMode = false;
            if (domainObject == null) {
                // In MASS_UPDATE mode, error if DO not found
                if (mode == Mode.MASS_UPDATE)
                    throw new ApplicationExceptions(
                            new DomainObjectNotFoundException(TransformerUtils.findDomainLabel(doClass)));

                // NEW OBJECT, create and reflect keys
                if (log.isDebugEnabled())
                    log.debug("DO '" + mapping.getDomainClassShortName()
                            + "' not found with key, create a new one...");
                domainObject = (IPersistent) doClass.newInstance();
                // set the key fields
                for (Iterator it = keys.keySet().iterator(); it.hasNext();) {
                    String keyField = (String) it.next();
                    if (mapping.isReadOnly(keyField))
                        continue;
                    Object value = keys.get(keyField);
                    TransformerUtils.updateProperty(mapping.getDomainFieldDescriptor(keyField), value,
                            domainObject);
                }
                createMode = true;
            } else {
                if (log.isDebugEnabled())
                    log.debug("Found DO '" + mapping.getDomainClassShortName() + "' with key,");
            }

            // Now update all domain fields
            TransformerUtils.updateBeanData(path, source, uow, handler, mapping, domainObject, mode, newGraph);

            // Invoke the changeDone trigger
            if (handler != null && handler.isChangeDone()) {
                for (ITransformationHandler transformationHandler : handler.getTransformationHandlers()) {
                    transformationHandler.changeDone(path, source, domainObject, uow);
                }
            }

            // Return an appropriate output
            if (mode == Mode.VALIDATE_ONLY) {
                // In VALIDATE_ONLY mode, return the input graph (with defaulted data)
                return source;
            } else if (createMode) {
                // In create-mode, Create a new graph and stamp just the keys
                GraphDataObject outputGraph = source.getClass().newInstance();
                for (Iterator i = keys.keySet().iterator(); i.hasNext();) {
                    String keyField = (String) i.next();
                    PropertyDescriptor pd = mapping.getDomainFieldDescriptor(keyField);
                    if (pd != null && pd.getReadMethod() != null) {
                        Method m = pd.getReadMethod();
                        if (!m.isAccessible())
                            m.setAccessible(true);
                        Object value = m.invoke(domainObject, (Object[]) null);
                        AccessibleObject accessibleObject = mapping.getDataMutator(keyField);
                        setValue(accessibleObject, outputGraph, value);
                    } else {
                        TransformException me = new TransformException(TransformException.NO_KEY_ON_OBJECT,
                                path, keyField, source.getClass().getName());
                        log.error(me.getLocalizedMessage());
                        throw me;
                    }
                }
                return outputGraph;
            } else {
                // In update-mode, return a null
                return null;
            }
        } catch (IllegalAccessException e) {
            TransformException me = new TransformException(TransformException.ACCESS_ERROR, path,
                    e.getMessage());
            log.error(me.getLocalizedMessage(), e);
            throw me;
        } catch (InvocationTargetException e) {
            ApplicationExceptions appExps = ExceptionHelper.extractApplicationExceptions(e);
            if (appExps != null)
                throw appExps;
            FrameworkException fe = ExceptionHelper.extractFrameworkException(e);
            if (fe != null)
                throw fe;
            TransformException me = new TransformException(TransformException.INVOCATION_ERROR, path, e);
            log.error(me.getLocalizedMessage(), me.getCause());
            throw me;
        } catch (InstantiationException e) {
            TransformException me = new TransformException(TransformException.INSTANTICATION_ERROR, path,
                    e.getMessage());
            log.error(me.getLocalizedMessage(), e);
            throw me;
        }
    }
}

From source file:com.zhumeng.dream.orm.hibernate.HibernateDao.java

/**
 * ?,hibernate???select count(o) from Xxx o?BUG,
 * hibernatejpql??sqlselect count(field1,field2,...),count()
 * ??HQL?:"select count(*) from Object"/*from   w  w  w.  ja  va2 s .c o m*/
 * @author: lizhong
 * @param <E>
 * @param clazz
 * @return
 */
protected static <E> String getCountField(Class<E> clazz) {
    String out = "o";
    try {
        PropertyDescriptor[] propertys = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
        for (PropertyDescriptor property : propertys) {
            Method method = property.getReadMethod();
            if (method != null && method.isAnnotationPresent(EmbeddedId.class)) {
                PropertyDescriptor[] props = Introspector.getBeanInfo(property.getPropertyType())
                        .getPropertyDescriptors();
                out = "o." + property.getName() + "."
                        + (!props[1].getName().equals("class") ? props[1].getName() : props[0].getName());
                break;
            }
        }
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }
    return out;
}

From source file:jp.gr.java_conf.ka_ka_xyz.processor.JPA20AnnotationProcessor.java

private void registerMethodAnnotation(Field field, Class<?> clazz) {
    try {/*from w  w w  . jav  a  2  s.co  m*/
        String fieldName = field.getName();
        PropertyDescriptor pd = new PropertyDescriptor(fieldName, clazz);
        Column column = pd.getReadMethod().getAnnotation(Column.class);
        String colName;
        if (column != null) {
            colName = column.name();
            fieldColMap.put(fieldName, colName);
        }

    } catch (IntrospectionException e) {
        e.printStackTrace();
        return;
    }
}