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.opensymphony.xwork2.ognl.OgnlUtil.java

/**
 * Creates a Map with read properties for the given source object.
 * <p>//  ww w.  j  a  v a2 s . c  o m
 * If the source object does not have a read property (i.e. write-only) then
 * the property is added to the map with the value <code>here is no read method for property-name</code>.
 * </p>
 *
 * @param source the source object.
 * @return a Map with (key = read property name, value = value of read property).
 * @throws IntrospectionException is thrown if an exception occurs during introspection.
 * @throws OgnlException          is thrown by OGNL if the property value could not be retrieved
 */
public Map<String, Object> getBeanMap(final Object source) throws IntrospectionException, OgnlException {
    Map<String, Object> beanMap = new HashMap<>();
    final Map sourceMap = createDefaultContext(source, null);
    PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(source);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final String propertyName = propertyDescriptor.getDisplayName();
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null) {
            final Object value = compileAndExecute(propertyName, null, new OgnlTask<Object>() {
                public Object execute(Object expr) throws OgnlException {
                    return Ognl.getValue(expr, sourceMap, source);
                }
            });
            beanMap.put(propertyName, value);
        } else {
            beanMap.put(propertyName, "There is no read method for " + propertyName);
        }
    }
    return beanMap;
}

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

/**
 * Mould data from domain object and its related objects into a new JavaBean based
 * domain object graph, based on the defined mapping rules.
 *
 * @param source           Source object to mould data from, typically extends Persistent
 * @param target           Target object to mould data to, typically extends GraphDataObject
 * @param graph            The mapping class with the rules of how to map this source object
 * @param filter           Filter object that it is used to control what fields are populated or the target objects
 * @param objectPath       The path of this object being processed. This identifies possible parent
 *                         and/or indexed entries where this object is contained.
 * @param includeKeys      true if key fields should be included in results regardless of the filters
 * @param originalCriteria the original graph criteria.
 * @param handler          Possible bean handler to be used when processing this source object graph
 * @throws ApplicationExceptions Thrown if one or more application logic errors are generated during moulding
 * @throws FrameworkException    Thrown if any runtime moulding error has occured.
 *///from w  ww  .j a  v a  2  s. c  o  m
public static void buildGraphFromDomain(Object source, Object target, GraphMapping graph, MappingFilter filter,
        String objectPath, boolean includeKeys, GraphCriteria originalCriteria, ITransformationHandler handler)
        throws ApplicationExceptions, FrameworkException {

    if (graph == null)
        graph = MappingFactory.getInstance(target);

    boolean useQueryDomain = graph.getQueryDomainClass() != null
            && source.getClass().isAssignableFrom(graph.getQueryDomainClass());

    //throw new InstantiationException("A GraphMapping must be supplied");
    if (filter == null)
        filter = MappingFilter.getInstance(graph);

    try {
        // get list of target fileds to populate
        String[] tFields = graph.getDataFieldNames();
        if (tFields != null && tFields.length != 0)
            for (int i = 0; i < tFields.length; i++) {
                // Try to map a source to a target
                String tName = tFields[i];
                String fullName = tName;
                if (objectPath != null)
                    fullName = objectPath + "." + fullName;

                if (filter == null || filter.isFieldIncluded(fullName)
                        || (includeKeys && graph.isKeyField(tName))) {
                    String sName = graph.getDomainFieldName(tName);
                    AccessibleObject tAccessibleObject = graph.getDataMutator(tName);
                    PropertyDescriptor tDesc = graph.getDataFieldDescriptor(tName);
                    PropertyDescriptor sDesc = useQueryDomain ? graph.getQueryDomainFieldDescriptor(tName)
                            : graph.getDomainFieldDescriptor(tName);

                    if (useQueryDomain && sDesc == null)
                        continue;

                    // Based on validation in GraphMapping, that there is a
                    // GraphObject descriptor with a setter, and a DO descriptor with a getter
                    if (sDesc == null)
                        log.error("No Getter for " + tName + " in path " + fullName);

                    // incase getter is not public, make it available
                    Method sm = sDesc.getReadMethod();
                    if (!sm.isAccessible())
                        sm.setAccessible(true);

                    // Set the value if the source and target are the same datatype
                    Class tClass = tDesc.getPropertyType();
                    Class sClass = sDesc.getPropertyType();
                    if (tClass.isAssignableFrom(sClass)) {
                        // Get the value being copied
                        Object sValue = sm.invoke(source, (Object[]) null);
                        setValue(tAccessibleObject, target, sValue);
                        if (log.isDebugEnabled())
                            log.debug("Set " + tName + " = " + sValue);

                        // See if there is a datatype mapper for these classes
                    } else if (DataTypeMapper.instance().isMappable(sClass, tClass)) {
                        // Get the value being copied
                        Object sValue = sm.invoke(source, (Object[]) null);
                        if (sValue != null) {
                            sValue = DataTypeMapper.instance().map(sValue, tClass);
                            if (log.isDebugEnabled())
                                log.debug("Set " + tName + " = " + sValue);
                        }
                        setValue(tAccessibleObject, target, sValue);

                        // See if target is a GraphObject, this could be a foreign object or one-to-one relationship...
                    } else if (GraphDataObject.class.isAssignableFrom(tClass)
                            && IPersistent.class.isAssignableFrom(sClass)) {
                        // Get the mapper for the related GraphObject, if it has keys, it must be a foriegn object
                        if (graph.isForeignField(tName)) {
                            // look at foreign key fields, and make sure they are not null
                            List foreignKeys = graph.getForeignKeys(tName);
                            List foreignKeyValues = new ArrayList();
                            boolean nullKey = false;
                            for (Iterator k = foreignKeys.iterator(); k.hasNext();) {
                                String doProp = (String) k.next();
                                Object value = null;
                                PropertyDescriptor doPd = graph.getRealDomainFieldDescriptor(doProp);
                                if (doPd != null && doPd.getReadMethod() != null) {
                                    Method m = doPd.getReadMethod();
                                    if (!m.isAccessible())
                                        m.setAccessible(true);
                                    value = m.invoke(source, new Object[] {});
                                    if (value == null)
                                        nullKey = true;
                                    foreignKeyValues.add(value);
                                } else {
                                    throw new TransformException(TransformException.INVALID_FK_MAPPING,
                                            objectPath, doProp, graph.getDomainClassShortName());
                                }
                            }
                            if (nullKey) {
                                if (log.isDebugEnabled())
                                    log.debug("Did not create skeleton object '" + tClass.getName()
                                            + "': one or more foreign key values missing.");
                            } else {
                                // Create the foreign object
                                if (log.isDebugEnabled())
                                    log.debug("Creating foreign object - " + tClass.getName());
                                Object newGDO = newGraphDataObject(tClass);
                                boolean createSkeleton = true;
                                // Only retrieve related domain object and introspect if need
                                if (filter.areSubFieldsIncluded(fullName)) {
                                    // read object and introspect all
                                    if (log.isDebugEnabled())
                                        log.debug("Read foreign object '" + fullName + "' and mold");
                                    try {
                                        Object sValue = sm.invoke(source, (Object[]) null);
                                        if (sValue != null) {
                                            DataTransformer.buildGraphFromDomain(sValue, newGDO, null, filter,
                                                    fullName, true, originalCriteria, handler);
                                            createSkeleton = false;
                                        }
                                    } catch (InvocationTargetException e) {
                                        // If the foreign object is not found, create the skeleton
                                        if (e.getCause() != null
                                                && e.getCause() instanceof InvalidForeignKeyException) {
                                            if (log.isDebugEnabled())
                                                log.debug(
                                                        "All foreign keys present, but foreign object does not exist",
                                                        e);
                                        } else
                                            throw e;
                                    }
                                }
                                if (createSkeleton) {
                                    // just set foreign keys from current object
                                    if (log.isDebugEnabled())
                                        log.debug("Set keys on skeleton foreign object only");
                                    GraphMapping graph2 = MappingFactory.getInstance(newGDO);
                                    Set keys = graph2.getKeyFields();
                                    if (keys == null || keys.size() != foreignKeyValues.size()) {
                                        throw new TransformException(TransformException.MISMATCH_FK_MAPPING,
                                                objectPath, target.getClass().getName(),
                                                newGDO.getClass().getName());
                                    }
                                    int k2 = 0;
                                    // Look through all the foreign keys on the skeleton object
                                    for (Iterator k = keys.iterator(); k.hasNext(); k2++) {
                                        String keyField = (String) k.next();
                                        Object keyValue = foreignKeyValues.get(k2);
                                        AccessibleObject accessibleObject = graph2.getDataMutator(keyField);
                                        if (accessibleObject != null) {
                                            setValue(accessibleObject, newGDO, keyValue);
                                        } else {
                                            throw new TransformException(TransformException.CANT_SET_KEY_FIELD,
                                                    objectPath, keyField, newGDO.getClass().getName());
                                        }
                                    }
                                }
                                setValue(tAccessibleObject, target, newGDO);
                                if (log.isDebugEnabled())
                                    log.debug("Set " + tName + " = " + newGDO);
                            }
                        } else {
                            // This is not a foreign object, must be a related object
                            if (filter.areSubFieldsIncluded(fullName)) {
                                // Create the related object
                                if (log.isDebugEnabled())
                                    log.debug("Creating One-To-One object - " + tClass.getName());
                                Object newGDO = newGraphDataObject(tClass);
                                // read object and introspect all
                                if (log.isDebugEnabled())
                                    log.debug("Read related object '" + fullName + "' and mold");
                                Object sValue = sm.invoke(source, (Object[]) null);
                                if (sValue != null) {
                                    DataTransformer.buildGraphFromDomain(sValue, newGDO, null, filter, fullName,
                                            false, originalCriteria, handler);
                                    setValue(tAccessibleObject, target, newGDO);
                                    if (log.isDebugEnabled())
                                        log.debug("Set " + tName + " = " + newGDO);
                                } else {
                                    if (log.isDebugEnabled())
                                        log.debug("Related object '" + fullName + "' not found. Ignore it!");
                                }
                            } else {
                                if (log.isDebugEnabled())
                                    log.debug("No subfields for object " + fullName
                                            + " included. Object not retrieved");
                            }
                        } //END-related object

                        // See if Target may be an array of GraphObject's
                    } else if (tClass.isArray()
                            && GraphDataObject.class.isAssignableFrom(tClass.getComponentType())
                            && filter.areSubFieldsIncluded(fullName)) {
                        if (log.isDebugEnabled())
                            log.debug("Target is an array of GraphObject's");
                        if (sClass.isArray() && IPersistent.class.isAssignableFrom(sClass.getComponentType())) {
                            if (log.isDebugEnabled()) {
                                log.debug("Source is an array of Persistent Objects");
                                log.debug("Read related objects '" + fullName + "' and mold");
                            }
                            Object[] sArray = findRelatedObjects(source, sClass, sm, handler, originalCriteria,
                                    fullName);
                            if (sArray != null && sArray.length > 0) {
                                Object[] tArray = (Object[]) Array.newInstance(tClass.getComponentType(),
                                        sArray.length);
                                if (log.isDebugEnabled())
                                    log.debug("Translate Array of Size " + sArray.length);
                                for (int j = 0; j < sArray.length; j++) {
                                    Object newGDO = newGraphDataObject(tClass.getComponentType());
                                    DataTransformer.buildGraphFromDomain(sArray[j], newGDO, null, filter,
                                            fullName, false, originalCriteria, handler);
                                    tArray[j] = newGDO;
                                    if (log.isDebugEnabled())
                                        log.debug("Add to array [" + j + "] : " + newGDO);
                                }
                                setValue(tAccessibleObject, target, tArray);
                                if (log.isDebugEnabled())
                                    log.debug("Set Array " + tName);
                            } else {
                                if (log.isDebugEnabled())
                                    log.debug("Source Array is empty! Do Nothing");
                            }
                        } // source is DO array

                        // Error... No way to map property
                    } else {
                        String err = "Can't Mold Property " + fullName + " from " + sClass.getName() + " to "
                                + tClass.getName();
                        log.error(err);
                        throw new RuntimeException(err);
                    }
                } // is included in filtered fields
            }

        // Load flex fields
        // By default all the domain-mapped flex fields will be loaded; unless excluded by a rule
        if (source instanceof IFlexFields && target instanceof IFlexFields) {
            String fullName = (objectPath != null ? objectPath + '.' : "") + "flexBean";
            if (filter == null || filter.isFieldIncluded(fullName)) {
                if (log.isDebugEnabled())
                    log.debug("Loading FlexBean " + fullName);
                FlexBean sFlexBean = ((IFlexFields) source).getFlexBean();
                FlexBean tFlexBean = ((IFlexFields) target).getFlexBean();
                if (sFlexBean != null && tFlexBean != null) {
                    for (DynaProperty flexProperty : sFlexBean.getDynaClass().getDynaProperties()) {
                        String name = flexProperty.getName();
                        Boolean include = filter.includeField(fullName + '.' + name);
                        if (include != null ? include
                                : ((FlexProperty) flexProperty).getFlexInfo()
                                        .getProperty("domain-mapping") != null) {
                            Object value = sFlexBean.get(name);
                            if (value != null) {
                                if (log.isDebugEnabled())
                                    log.debug("Loaded flex field '" + name + '=' + value + '\'');
                                tFlexBean.set(name, value);
                            }
                        }
                    }
                }
            }
        }

        // Clear changed fields on updated GraphObject
        if (target != null && target instanceof GraphDataObject)
            ((GraphDataObject) target).clearChanges();

        // Invoke the handler
        if (handler != null) {
            if (log.isDebugEnabled()) {
                log.debug("Invoking the endBeanLoad on the handler");
            }
            for (ITransformationHandler transformationHandler : handler.getTransformationHandlers()) {
                transformationHandler.endBeanLoad(objectPath, source, target, filter, originalCriteria);
            }
        }

    } catch (ApplicationException e) {
        throw new ApplicationExceptions(e);
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, objectPath,
                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, objectPath, e);
        log.error(me.getLocalizedMessage(), me.getCause());
        throw me;
    } catch (InstantiationException e) {
        TransformException me = new TransformException(TransformException.INSTANTICATION_ERROR, objectPath,
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    }
}

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) {
                        }/*w ww  .j av a  2 s . c o 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:com.nortal.petit.beanmapper.BeanMappingFactoryImpl.java

@SuppressWarnings("unchecked")
private <B> void initProperty(Map<String, Property<B, Object>> props, List<Property<B, Object>> idProps,
        String name, Class<B> type) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, name);

    if (!isPropertyReadableAndWritable(pd)) {
        return;/*from  w ww . j  a v a2  s  .c om*/
    }

    List<Annotation> ans = BeanMappingReflectionUtils.readAnnotations(type, pd.getName());

    if (BeanMappingReflectionUtils.getAnnotation(ans, Transient.class) != null) {
        return;
    }

    Column column = BeanMappingReflectionUtils.getAnnotation(ans, Column.class);

    ReflectionProperty<B, Object> prop = new ReflectionProperty<B, Object>(name,
            (Class<Object>) pd.getPropertyType(), inferColumn(name, column), pd.getWriteMethod(),
            pd.getReadMethod());

    if (column != null) {
        prop.readOnly(!column.insertable());
    }

    if (BeanMappingReflectionUtils.getAnnotation(ans, Id.class) != null) {
        idProps.add(prop);
    }

    if (useAdditionalConfiguration()) {
        prop.getConfiguration().setAnnotations(ans);
        if (Collection.class.isAssignableFrom(pd.getPropertyType())) {
            prop.getConfiguration().setCollectionTypeArguments(
                    ((ParameterizedType) pd.getReadMethod().getGenericReturnType()).getActualTypeArguments());
        }
    }

    if (BeanMappingReflectionUtils.getAnnotation(ans, Embedded.class) != null) {
        props.putAll(getCompositeProperties(prop, ans));
    } else {
        props.put(prop.name(), prop);
    }
}

From source file:it.doqui.index.ecmengine.client.webservices.AbstractWebServiceDelegateBase.java

@SuppressWarnings("unchecked")
protected Object convertDTO(Object sourceDTO, Class destDTOClass) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("[" + getClass().getSimpleName() + "::convertDTO] BEGIN");
    }//from  ww w .j  a  va2  s.  c  o  m

    Object destDTO = null;
    try {
        if (sourceDTO != null) {
            if (log.isDebugEnabled()) {
                log.debug("[" + getClass().getSimpleName() + "::convertDTO] converting DTO from type "
                        + sourceDTO.getClass().getName() + " to type " + destDTOClass.getName());
            }
            destDTO = BeanUtils.instantiateClass(destDTOClass);
            PropertyDescriptor[] targetpds = BeanUtils.getPropertyDescriptors(destDTOClass);
            PropertyDescriptor sourcepd = null;
            if (log.isDebugEnabled()) {
                log.debug(" found " + targetpds.length + " properties for type " + destDTOClass.getName());
            }

            for (int i = 0; i < targetpds.length; i++) {
                if (targetpds[i].getWriteMethod() != null) {
                    Method writeMethod = targetpds[i].getWriteMethod();
                    sourcepd = BeanUtils.getPropertyDescriptor(sourceDTO.getClass(), targetpds[i].getName());
                    if (sourcepd != null && sourcepd.getReadMethod() != null) {
                        if (log.isDebugEnabled()) {
                            log.debug("[" + getClass().getSimpleName() + "::convertDTO] found property: "
                                    + targetpds[i].getName());
                            log.debug("[" + getClass().getSimpleName() + "::convertDTO] source type: "
                                    + sourcepd.getPropertyType().getName() + ", dest type: "
                                    + targetpds[i].getPropertyType().getName());
                        }
                        Method readMethod = sourcepd.getReadMethod();
                        Object valueObject = null;
                        if (!BeanUtils.isSimpleProperty(targetpds[i].getPropertyType())) {
                            if (sourcepd.getPropertyType().isArray()) {
                                valueObject = convertDTOArray(
                                        (Object[]) readMethod.invoke(sourceDTO, new Object[] {}),
                                        targetpds[i].getPropertyType().getComponentType());
                            } else if (sourcepd.getPropertyType().equals(java.util.Calendar.class)
                                    && targetpds[i].getPropertyType().equals(java.util.Date.class)) {
                                // if java.util.Calendar => convert to java.util.Date
                                valueObject = readMethod.invoke(sourceDTO, new Object[0]);
                                if (valueObject != null) {
                                    valueObject = ((Calendar) valueObject).getTime();
                                }
                            } else if (sourcepd.getPropertyType().equals(java.util.Date.class)
                                    && targetpds[i].getPropertyType().equals(java.util.Calendar.class)) {
                                // if java.util.Date => convert to java.util.Calendar
                                Calendar calendar = Calendar.getInstance();
                                valueObject = readMethod.invoke(sourceDTO, new Object[0]);
                                if (valueObject != null) {
                                    calendar.setTime((Date) valueObject);
                                    valueObject = calendar;
                                }
                            } else {
                                valueObject = convertDTO(readMethod.invoke(sourceDTO, new Object[0]),
                                        targetpds[i].getPropertyType());
                            }
                        } else {
                            valueObject = readMethod.invoke(sourceDTO, new Object[0]);
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("[" + getClass().getSimpleName() + "::convertDTO] writing value: "
                                    + valueObject);
                        }
                        writeMethod.invoke(destDTO, new Object[] { valueObject });
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("[" + getClass().getSimpleName() + "::convertDTO] skipping property: "
                                    + targetpds[i].getName());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("[" + getClass().getSimpleName() + "::convertDTO] ERROR", e);
        throw e;
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("[" + getClass().getSimpleName() + "::convertDTO] END");
        }
    }
    return destDTO;
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
  * Overwrites the values of the bean in parameter with the form values
  * @param source/*from   ww w .  j  a v a 2s  .c  o m*/
  * @return
  */
public <R> void mergeInto(R source) {

    for (Field field : fields()) {
        // if applicable, remove the fieldPrefix to get the bean field name
        String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length()) : field.name();
        BeanWrapper beanWrapper = new BeanWrapperImpl(source);
        try {
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                beanWrapper.setPropertyValue(fieldName, field.value());
            }
        } catch (InvalidPropertyException ex) {
            logger.log(Level.WARNING, "Form property not in source");
        }
    }
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
 * bind all or only the specified properties of the object to this Form. 
 * Validation is automatically performed after the binding, validating all or only the specified properties. 
 * The result of the validation is available by calling form.hasErrors() and/or field.hasErrors() 
 * /* ww w  .j av a2 s . c  o m*/
 * @param object
 * @param properties
 * @return
 */
public Form<T> bindObject(T object, String... properties) {
    if (object != null) {
        this.object = object;
        BeanWrapper beanWrapper = new BeanWrapperImpl(object);
        for (Field field : fields()) {
            // if applicable, remove the fieldPrefix to get the bean field name 
            String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length())
                    : field.name();
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                Object propertyValue = beanWrapper.getPropertyValue(fieldName);

                String strPropValue = propertyValue != null
                        ? (propertyValue instanceof java.time.Instant
                                ? format((java.time.Instant) propertyValue)
                                : propertyValue.toString())
                        : null;
                field.value(strPropValue);
            }
        }
    }
    return this;
}

From source file:ca.sqlpower.matchmaker.swingui.SaveAndOpenWorkspaceActionTest.java

/**
 * Takes two SPObjects and recursively determines if all persistable properties
 * are equal. This is used in testing before-states and after-states for
 * persistence tests./*from   ww w  .  j a  v a  2 s .  c  o  m*/
 */
private boolean checkEquality(SPObject spo1, SPObject spo2) {

    try {
        Set<String> s = TestUtils.findPersistableBeanProperties(spo1, false, false);
        List<PropertyDescriptor> settableProperties = Arrays
                .asList(PropertyUtils.getPropertyDescriptors(spo1.getClass()));

        for (PropertyDescriptor property : settableProperties) {
            @SuppressWarnings("unused")
            Object oldVal;
            if (!s.contains(property.getName()))
                continue;
            if (property.getName().equals("parent"))
                continue; //Changing the parent causes headaches.
            if (property.getName().equals("session"))
                continue;
            if (property.getName().equals("type"))
                continue;
            try {
                oldVal = PropertyUtils.getSimpleProperty(spo1, property.getName());
                // check for a getter
                if (property.getReadMethod() == null)
                    continue;

            } catch (NoSuchMethodException e) {
                logger.debug("Skipping non-settable property " + property.getName() + " on "
                        + spo1.getClass().getName());
                continue;
            }
            Object spo1Property = PropertyUtils.getSimpleProperty(spo1, property.getName());
            Object spo2Property = PropertyUtils.getSimpleProperty(spo2, property.getName());

            assertEquals("Failed to equate " + property.getName() + " on object of type " + spo1.getClass(),
                    spo1Property, spo2Property);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // look at children
    Iterator<? extends SPObject> i = (spo1.getChildren().iterator());
    Iterator<? extends SPObject> j = (spo2.getChildren().iterator());
    while (i.hasNext() && j.hasNext()) {
        SPObject ii = i.next();
        SPObject jj = j.next();
        logger.debug("Comparing: " + ii.getClass().getSimpleName() + "," + jj.getClass().getSimpleName());
        checkEquality(ii, jj);
    }
    return (!(i.hasNext() || j.hasNext()));
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
 * Creates a Bean of the given class type from the form values
 * @param cls class of the result bean//from  w w w  .ja  v a2s  .  c o  m
 * @param <R> type of the bean
 * @return
 */
public <R> R deriveBean(Class<R> cls) {

    R result = null;
    try {
        result = cls.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        logger.log(Level.WARNING, "Could not instantiate derived bean", e);
        return null;
    }

    for (Field field : fields()) {
        // if applicable, remove the fieldPrefix to get the bean field name
        String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length()) : field.name();
        BeanWrapper beanWrapper = new BeanWrapperImpl(result);
        try {
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                beanWrapper.setPropertyValue(fieldName, field.value());
            }
        } catch (InvalidPropertyException ex) {
            logger.log(Level.WARNING, "Form property not in bean");
        }

    }

    return result;
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
  * Creates a Bean with the given class from the from values
  * @param object Source object we're taking the values from
  * @return this object/*w ww.  j a  v  a  2s  .co m*/
  */
public Form<T> fillFromBean(Object object) {

    BeanWrapper beanWrapper = new BeanWrapperImpl(object);
    for (Field field : fields()) {
        // if applicable, remove the fieldPrefix to get the bean field name
        String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length()) : field.name();
        try {
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                Object propertyValue = beanWrapper.getPropertyValue(fieldName);
                String strPropValue = propertyValue != null ? propertyValue.toString() : null;

                // If the field hasn't got a value already, clear the potential errors as they will be meaningless
                // and the set the field value
                if (field.value() == null) {
                    field.value(strPropValue);
                    field.errors().clear();
                }
            }
        } catch (InvalidPropertyException e) {
            logger.log(Level.WARNING,
                    "Could not find property " + fieldName + " for bean " + object.getClass().getName(), e);
            continue;
        }

    }
    return this;
}