Example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors

List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors.

Prototype

public static PropertyDescriptor[] getPropertyDescriptors(Object bean) 

Source Link

Document

Retrieve the property descriptors for the specified bean, introspecting and caching them the first time a particular bean class is encountered.

For more details see PropertyUtilsBean.

Usage

From source file:com.github.dozermapper.core.util.ReflectionUtils.java

static PropertyDescriptor[] getInterfacePropertyDescriptors(Class<?> interfaceClass) {
    List<PropertyDescriptor> propDescriptors = new ArrayList<>();
    // Add prop descriptors for interface passed in
    propDescriptors.addAll(Arrays.asList(PropertyUtils.getPropertyDescriptors(interfaceClass)));

    // Look for interface inheritance. If super interfaces are found, recurse up the hierarchy tree and add prop
    // descriptors for each interface found.
    // PropertyUtils.getPropertyDescriptors() does not correctly walk the inheritance hierarchy for interfaces.
    Class<?>[] interfaces = interfaceClass.getInterfaces();
    if (interfaces != null) {
        for (Class<?> superInterfaceClass : interfaces) {
            List<PropertyDescriptor> superInterfacePropertyDescriptors = Arrays
                    .asList(getInterfacePropertyDescriptors(superInterfaceClass));
            /*/*  www  . ja  v  a 2  s .  com*/
             * #1814758
             * Check for existing descriptor with the same name to prevent 2 property descriptors with the same name being added
             * to the result list.  This caused issues when getter and setter of an attribute on different interfaces in
             * an inheritance hierarchy
             */
            for (PropertyDescriptor superPropDescriptor : superInterfacePropertyDescriptors) {
                PropertyDescriptor existingPropDescriptor = findPropDescriptorByName(propDescriptors,
                        superPropDescriptor.getName());
                if (existingPropDescriptor == null) {
                    propDescriptors.add(superPropDescriptor);
                } else {
                    try {
                        if (existingPropDescriptor.getReadMethod() == null) {
                            existingPropDescriptor.setReadMethod(superPropDescriptor.getReadMethod());
                        }
                        if (existingPropDescriptor.getWriteMethod() == null) {
                            existingPropDescriptor.setWriteMethod(superPropDescriptor.getWriteMethod());
                        }
                    } catch (IntrospectionException e) {
                        throw new MappingException(e);
                    }

                }
            }
        }
    }
    return propDescriptors.toArray(new PropertyDescriptor[propDescriptors.size()]);
}

From source file:ca.sqlpower.architect.swingui.TestPlayPen.java

/**
 * Checks that the properties of an instance from the copy constructor are equal to the original.
 * In the case of a mutable property, it also checks that they don't share the same instance.
 * /*  w  w  w.  j a v  a 2  s  .  c o m*/
 * @throws Exception
 */
public void testCopyConstructor() throws Exception {
    List<PropertyDescriptor> settableProperties = Arrays
            .asList(PropertyUtils.getPropertyDescriptors(pp.getClass()));
    Set<String> copyIgnoreProperties = new HashSet<String>();

    copyIgnoreProperties.add("UI");
    copyIgnoreProperties.add("UIClassID");
    copyIgnoreProperties.add("accessibleContext");
    copyIgnoreProperties.add("actionMap");
    copyIgnoreProperties.add("alignmentX");
    copyIgnoreProperties.add("alignmentY");
    copyIgnoreProperties.add("ancestorListeners");
    copyIgnoreProperties.add("autoscrolls");
    copyIgnoreProperties.add("border");
    copyIgnoreProperties.add("class");
    copyIgnoreProperties.add("component");
    copyIgnoreProperties.add("componentPopupMenu");
    copyIgnoreProperties.add("containerListeners");
    copyIgnoreProperties.add("contentPane");
    copyIgnoreProperties.add("cursorManager");
    copyIgnoreProperties.add("debugGraphicsOptions");
    copyIgnoreProperties.add("doubleBuffered");
    copyIgnoreProperties.add("enabled");
    copyIgnoreProperties.add("focusCycleRoot");
    copyIgnoreProperties.add("focusTraversalKeys");
    copyIgnoreProperties.add("focusTraversalPolicy");
    copyIgnoreProperties.add("focusTraversalPolicyProvider");
    copyIgnoreProperties.add("focusTraversalPolicySet");
    copyIgnoreProperties.add("focusable");
    copyIgnoreProperties.add("fontRenderContext");
    copyIgnoreProperties.add("graphics");
    copyIgnoreProperties.add("height");
    copyIgnoreProperties.add("ignoreTreeSelection");
    copyIgnoreProperties.add("inheritsPopupMenu");
    copyIgnoreProperties.add("inputMap");
    copyIgnoreProperties.add("inputVerifier");
    copyIgnoreProperties.add("insets");
    copyIgnoreProperties.add("layout");
    copyIgnoreProperties.add("managingFocus");
    copyIgnoreProperties.add("maximumSize");
    copyIgnoreProperties.add("minimumSize");
    copyIgnoreProperties.add("mouseMode");
    copyIgnoreProperties.add("name");
    copyIgnoreProperties.add("nextFocusableComponent");
    copyIgnoreProperties.add("opaque");
    copyIgnoreProperties.add("optimizedDrawingEnabled");
    copyIgnoreProperties.add("paintingEnabled");
    copyIgnoreProperties.add("paintingTile");
    copyIgnoreProperties.add("panel");
    copyIgnoreProperties.add("playPenContentPane");
    copyIgnoreProperties.add("preferredScrollableViewportSize");
    copyIgnoreProperties.add("preferredSize");
    copyIgnoreProperties.add("registeredKeyStrokes");
    copyIgnoreProperties.add("requestFocusEnabled");
    copyIgnoreProperties.add("rootPane");
    copyIgnoreProperties.add("scrollableTracksViewportHeight");
    copyIgnoreProperties.add("scrollableTracksViewportWidth");
    copyIgnoreProperties.add("selectedItems");
    copyIgnoreProperties.add("selectedRelationShips");
    copyIgnoreProperties.add("selectedTables");
    copyIgnoreProperties.add("session");
    copyIgnoreProperties.add("topLevelAncestor");
    copyIgnoreProperties.add("toolTipText");
    copyIgnoreProperties.add("transferHandler");
    copyIgnoreProperties.add("usedArea");
    copyIgnoreProperties.add("validateRoot");
    copyIgnoreProperties.add("verifyInputWhenFocusTarget");
    copyIgnoreProperties.add("vetoableChangeListeners");
    copyIgnoreProperties.add("viewPosition");
    copyIgnoreProperties.add("viewportSize");
    copyIgnoreProperties.add("visible");
    copyIgnoreProperties.add("visibleRect");
    copyIgnoreProperties.add("width");
    copyIgnoreProperties.add("x");
    copyIgnoreProperties.add("y");

    copyIgnoreProperties.add("draggingTablePanes");
    copyIgnoreProperties.add("rubberBand");

    // These should not be copied because any new PlayPen needs
    // different values or else it will not work on the new
    // PlayPen.
    copyIgnoreProperties.add("mouseZoomInAction");
    copyIgnoreProperties.add("mouseZoomOutAction");
    copyIgnoreProperties.add("scrollPane");

    // we're not sure if zoom should be duplicated...
    // it might mess up printing?!?!?
    copyIgnoreProperties.add("zoom");

    // individual lists (e.g. tables) checked instead
    copyIgnoreProperties.add("components");

    // The copy of the play pen is for things like print preview, so we don't want to
    // duplicate menus and other interactive features. (?)
    copyIgnoreProperties.add("popupFactory");

    //This property is specific to each play pen and it's settings will be re-calculated
    //regularly so it does not need to be copied.
    copyIgnoreProperties.add("criticismBucket");

    // First pass: set all settable properties, because testing the duplication of
    //             an object with all its properties at their defaults is not a
    //             very convincing test of duplication!
    for (PropertyDescriptor property : settableProperties) {
        if (copyIgnoreProperties.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(pp, property.getName());
            // check for a setter
            if (property.getWriteMethod() != null) {
                Object newVal = getNewDifferentValue(property, oldVal);
                BeanUtils.copyProperty(pp, property.getName(), newVal);
            }
        } catch (NoSuchMethodException e) {
            logger.warn(
                    "Skipping non-settable property " + property.getName() + " on " + pp.getClass().getName());
        }
    }
    // Second pass get a copy make sure all of 
    // the original mutable objects returned from getters are different
    // between the two objects, but have the same values. 
    PlayPen duplicate = new PlayPen(pp.getSession(), pp);
    for (PropertyDescriptor property : settableProperties) {
        logger.info(property.getName() + property.getDisplayName() + property.getShortDescription());
        if (copyIgnoreProperties.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(pp, property.getName());
            Object copyVal = PropertyUtils.getSimpleProperty(duplicate, property.getName());
            if (oldVal == null) {
                throw new NullPointerException("We forgot to set " + property.getName());
            } else {
                assertEquals("The two values for property " + property.getDisplayName() + " in "
                        + pp.getClass().getName() + " should be equal", oldVal, copyVal);

                if (isPropertyInstanceMutable(property)) {
                    assertNotSame("Copy shares mutable property with original, property name: "
                            + property.getDisplayName(), copyVal, oldVal);
                }
            }
        } catch (NoSuchMethodException e) {
            logger.warn(
                    "Skipping non-settable property " + property.getName() + " on " + pp.getClass().getName());
        }
    }
}

From source file:com.expedia.tesla.compiler.plugins.JavaTypeMapper.java

/**
 * Generate Tesla schema from Java class by reflection.
 * <p>//from w ww  .  ja  v a 2s. c  o  m
 * Tesla can generate schema from existing Java classes that follow the
 * JavaBeans Spec. Only properties with following attributes will be
 * included:
 * <li>public accessible.</li>
 * <li>writable (has both getter and setter).</li>
 * <li>has no {@code SkipField} annotation.</li>
 * <p>
 * Tesla will map Java type to it's closest Tesla type by default.
 * Developers can override this by either providing their own
 * {@code TypeMapper}, or with Tesla annoations.
 * <p>
 * Tesla will map all Java object types to nullable types only for class
 * properties. If you want an property to be not nullable, use annotation
 * {@code NotNullable}.
 * 
 * @param schemaBuilder
 *            All non-primitive Tesla types must be defined inside a schema.
 *            This is the schema object into which the Tesla type will be
 *            generated.
 * 
 * @param javaType
 *            The java class object.
 * 
 * @return The Tesla type created from the java class by reflection.
 * 
 * @throws TeslaSchemaException
 */
public Type fromJavaClass(Schema.SchemaBuilder schemaBuilder, java.lang.Class<?> javaType)
        throws TeslaSchemaException {
    String className = javaType.getCanonicalName();
    if (className == null) {
        throw new TeslaSchemaException(
                String.format("Tesla cannot generate schema for local class '%s'.", javaType.getName()));
    }
    String classTypeId = Class.nameToId(className);
    Class clss = (Class) schemaBuilder.findType(classTypeId);
    if (clss != null) {
        return clss;
    }

    clss = (Class) schemaBuilder.addType(classTypeId);

    Class superClass = null;
    java.lang.Class<?> base = javaType.getSuperclass();
    if (base != null && base != java.lang.Object.class) {
        superClass = (Class) fromJavaClass(schemaBuilder, javaType.getSuperclass());
    }

    List<Field> fields = new ArrayList<>();
    for (PropertyDescriptor propDesc : PropertyUtils.getPropertyDescriptors(javaType)) {
        Type fieldType = null;
        String fieldName = propDesc.getName();
        Method readMethod = propDesc.getReadMethod();
        Method writeMethod = propDesc.getWriteMethod();

        // Ignore the property it missing getter or setter method.
        if (writeMethod == null || readMethod == null) {
            continue;
        }
        if ((superClass != null && superClass.hasField(fieldName)) || clss.hasField(fieldName)) {
            continue;
        }
        // Ignore the property if it is annotated with "SkipField".
        if (readMethod.getAnnotation(com.expedia.tesla.schema.annotation.SkipField.class) != null) {
            continue;
        }
        com.expedia.tesla.schema.annotation.TypeId tidAnnotation = readMethod
                .getAnnotation(com.expedia.tesla.schema.annotation.TypeId.class);

        String typeId = null;
        if (tidAnnotation != null) {
            typeId = tidAnnotation.value();
        }
        java.lang.reflect.Type propType = readMethod.getGenericReturnType();
        fieldType = fromJava(schemaBuilder, propType);
        if (typeId != null) {
            fieldType = schemaBuilder.addType(typeId);
        } else {
            if (!(propType instanceof java.lang.Class<?> && ((java.lang.Class<?>) propType).isPrimitive())) {
                fieldType = schemaBuilder.addType(String.format("nullable<%s>", fieldType.getTypeId()));
            }
            com.expedia.tesla.schema.annotation.NotNullable anntNotNullable = readMethod
                    .getAnnotation(com.expedia.tesla.schema.annotation.NotNullable.class);
            com.expedia.tesla.schema.annotation.Nullable anntNullable = readMethod
                    .getAnnotation(com.expedia.tesla.schema.annotation.Nullable.class);
            if (anntNotNullable != null && anntNullable != null) {
                throw new TeslaSchemaException(String.format(
                        "Property '%' of class '%s' has conflict annotations." + "'NotNullable' and 'Nullable'",
                        fieldName));
            }
            if (fieldType.isNullable() && anntNotNullable != null) {
                fieldType = ((Nullable) fieldType).getElementType();
            }
            if (!fieldType.isReference()
                    && readMethod.getAnnotation(com.expedia.tesla.schema.annotation.Reference.class) != null) {
                fieldType = schemaBuilder.addType(String.format("reference<%s>", fieldType.getTypeId()));
            }
        }

        com.expedia.tesla.schema.annotation.FieldName fnAnnotation = readMethod
                .getAnnotation(com.expedia.tesla.schema.annotation.FieldName.class);
        if (fnAnnotation != null) {
            fieldName = fnAnnotation.value();
        }

        String fieldDisplayName = propDesc.getDisplayName();
        String getter = readMethod.getName();
        String setter = propDesc.getWriteMethod().getName();
        com.expedia.tesla.schema.annotation.DisplayName dnAnnotation = readMethod
                .getAnnotation(com.expedia.tesla.schema.annotation.DisplayName.class);
        if (dnAnnotation != null) {
            fieldDisplayName = dnAnnotation.value();
        }
        java.util.Map<String, String> attributes = new java.util.HashMap<String, String>();
        attributes.put("getter", getter);
        attributes.put("setter", setter);

        fields.add(new Field(fieldName, fieldDisplayName, fieldType, attributes, null));
    }

    clss.define(superClass == null ? null : Arrays.asList(new Class[] { superClass }), fields, null);
    return clss;
}

From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java

/**
 * This will reflectively iterate over all of the properties in the Wabit
 * object and set each value that has a setter and getter. When the property
 * is set it should cause the property to be persisted through the
 * {@link WorkspacePersisterListener}./*from w w  w  . ja  v a  2s .c o m*/
 */
public void testPropertiesArePersisted() throws Exception {

    CountingWabitPersister countingPersister = new CountingWabitPersister();
    WorkspacePersisterListener listener = new WorkspacePersisterListener(
            new StubWabitSession(new StubWabitSessionContext()), countingPersister, true);

    SPObject wo = getObjectUnderTest();
    wo.addSPListener(listener);

    WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter(
            new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true);
    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass()));

    //Ignore properties that are not in events because we won't have an event
    //to respond to.
    Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents();

    Set<String> propertiesToIgnoreForPersisting = getPropertiesToIgnoreForPersisting();

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;

        if (propertiesToIgnoreForEvents.contains(property.getName()))
            continue;
        if (propertiesToIgnoreForPersisting.contains(property.getName()))
            continue;

        countingPersister.clearAllPropertyChanges();
        try {
            oldVal = PropertyUtils.getSimpleProperty(wo, property.getName());

            // check for a setter
            if (property.getWriteMethod() == null)
                continue;

        } catch (NoSuchMethodException e) {
            logger.debug(
                    "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName());
            continue;
        }

        Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());
        int oldChangeCount = countingPersister.getPersistPropertyCount();

        try {
            logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(wo, property.getName(), newVal);

            assertTrue("Did not persist property " + property.getName(),
                    oldChangeCount < countingPersister.getPersistPropertyCount());

            //The first property change at current is always the property change we are
            //looking for, this may need to be changed in the future to find the correct
            //property.
            PersistedSPOProperty propertyChange = null;

            for (PersistedSPOProperty nextPropertyChange : countingPersister.getAllPropertyChanges()) {
                if (nextPropertyChange.getPropertyName().equals(property.getName())) {
                    propertyChange = nextPropertyChange;
                    break;
                }
            }
            assertNotNull("A property change event cannot be found for the property " + property.getName(),
                    propertyChange);

            assertEquals(wo.getUUID(), propertyChange.getUUID());
            assertEquals(property.getName(), propertyChange.getPropertyName());

            //XXX will replace this later
            List<Object> additionalVals = new ArrayList<Object>();
            if (wo instanceof OlapQuery && property.getName().equals("currentCube")) {
                additionalVals.add(((OlapQuery) wo).getOlapDataSource());
            }

            Object oldConvertedType = converterFactory.convertToBasicType(oldVal, additionalVals.toArray());
            assertEquals(
                    "Old value of property " + property.getName() + " was wrong, value expected was  "
                            + oldConvertedType + " but is " + countingPersister.getLastOldValue(),
                    oldConvertedType, propertyChange.getOldValue());

            //Input streams from images are being compared by hash code not values
            if (Image.class.isAssignableFrom(property.getPropertyType())) {
                logger.debug(propertyChange.getNewValue().getClass());
                assertTrue(Arrays.equals(PersisterUtils.convertImageToStreamAsPNG((Image) newVal).toByteArray(),
                        PersisterUtils
                                .convertImageToStreamAsPNG((Image) converterFactory
                                        .convertToComplexType(propertyChange.getNewValue(), Image.class))
                                .toByteArray()));
            } else {
                assertEquals(converterFactory.convertToBasicType(newVal, additionalVals.toArray()),
                        propertyChange.getNewValue());
            }
            Class<? extends Object> classType;
            if (oldVal != null) {
                classType = oldVal.getClass();
            } else {
                classType = newVal.getClass();
            }
            assertEquals(PersisterUtils.getDataType(classType), propertyChange.getDataType());
        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + wo.getClass().getName());
        }
    }

}

From source file:com.mb.framework.util.property.PropertyUtilExt.java

/**
 * Resets the bean's <code>String</code> type properties to a specified
 * value.//from  w  w  w.j  a v  a2 s  .c om
 * 
 * @param orig
 *            Origin bean whose properties are retrieved.
 * @param value
 *            the value to set the bean properties to.
 */
public static void resetProperties(Object orig, String value) {
    PropertyDescriptor origDescriptors[] = null;

    try {
        origDescriptors = PropertyUtils.getPropertyDescriptors(orig);
    } catch (Exception e) {
        return;
    }

    if (origDescriptors != null) {
        for (int i = 0; i < origDescriptors.length; i++) {
            try {
                String name = origDescriptors[i].getName();
                Object orgValue = PropertyUtils.getSimpleProperty(orig, name);
                if ((orgValue != null) && (orgValue instanceof String)) {
                    PropertyUtils.setSimpleProperty(orig, name, value);
                }
            } catch (Exception e) {
                // skip it
            }
        }
    }
}

From source file:com.bstek.dorado.view.output.ClientOutputHelper.java

protected Map<String, PropertyConfig> doGetPropertyConfigs(Class<?> beanType) throws Exception {
    beanType = ProxyBeanUtils.getProxyTargetType(beanType);
    Map<String, PropertyConfig> propertyConfigs = new HashMap<String, PropertyConfig>();

    ClientObjectInfo clientObjectInfo = getClientObjectInfo(beanType);
    if (clientObjectInfo != null) {
        for (Map.Entry<String, ClientProperty> entry : clientObjectInfo.getPropertyConfigs().entrySet()) {
            String property = entry.getKey();
            ClientProperty clientProperty = entry.getValue();

            PropertyConfig propertyConfig = new PropertyConfig();
            if (clientProperty.ignored()) {
                propertyConfig.setIgnored(true);
            } else {
                if (StringUtils.isNotEmpty(clientProperty.outputter())) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(clientProperty.outputter(),
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                }// w w w.  j  a  v  a2  s .com

                if (clientProperty.alwaysOutput()) {
                    propertyConfig.setEscapeValue(FAKE_ESCAPE_VALUE);
                } else if (StringUtils.isNotEmpty(clientProperty.escapeValue())) {
                    propertyConfig.setEscapeValue(clientProperty.escapeValue());
                }
            }
            propertyConfigs.put(property, propertyConfig);
        }
    }

    boolean isAssembledComponent = (AssembledComponent.class.isAssignableFrom(beanType));
    Class<?> superComponentType = null;
    if (isAssembledComponent) {
        superComponentType = beanType;
        while (superComponentType != null && AssembledComponent.class.isAssignableFrom(superComponentType)) {
            superComponentType = superComponentType.getSuperclass();
            Assert.notNull(superComponentType);
        }
    }

    for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(beanType)) {
        String property = propertyDescriptor.getName();
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod.getDeclaringClass() != beanType) {
            try {
                readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes());
            } catch (NoSuchMethodException e) {
                // do nothing
            }
        }

        TypeInfo typeInfo;
        Class<?> propertyType = propertyDescriptor.getPropertyType();
        if (Collection.class.isAssignableFrom(propertyType)) {
            typeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true);
            if (typeInfo != null) {
                propertyType = typeInfo.getType();
            }
        } else if (propertyType.isArray()) {
            typeInfo = new TypeInfo(propertyType.getComponentType(), true);
        } else {
            typeInfo = new TypeInfo(propertyType, false);
        }

        PropertyConfig propertyConfig = null;
        ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class);
        if (clientProperty != null) {
            propertyConfig = new PropertyConfig();
            if (clientProperty.ignored()) {
                propertyConfig.setIgnored(true);
            } else {
                if (StringUtils.isNotEmpty(clientProperty.outputter())) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(clientProperty.outputter(),
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (Component.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (DataControl.class.isAssignableFrom(propertyType)
                        || FloatControl.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (DataType.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(DATA_TYPE_PROPERTY_OUTPUTTER,
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (Object.class.equals(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(DATA_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (!EntityUtils.isSimpleType(propertyType) && !propertyType.isArray()) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(OBJECT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                }

                if (!clientProperty.evaluateExpression()) {
                    propertyConfig.setEvaluateExpression(false);
                }

                if (clientProperty.alwaysOutput()) {
                    propertyConfig.setEscapeValue(FAKE_ESCAPE_VALUE);
                } else if (StringUtils.isNotEmpty(clientProperty.escapeValue())) {
                    propertyConfig.setEscapeValue(clientProperty.escapeValue());
                }
            }
        } else if (isAssembledComponent && readMethod.getDeclaringClass() == beanType
                && EntityUtils.isSimpleType(propertyType)) {
            if (BeanUtils.getPropertyDescriptor(superComponentType, property) == null) {
                propertyConfig = new PropertyConfig();
                propertyConfig.setIgnored(true);
            }
        }

        ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class);
        if (componentReference != null && String.class.equals(propertyType)) {
            if (propertyConfig == null) {
                propertyConfig = new PropertyConfig();
            }
            if (propertyConfig.getOutputter() == null) {
                BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_REFERENCE_OUTPUTTER,
                        Scope.instant);
                propertyConfig.setOutputter(beanWrapper.getBean());
            }
        }

        if (!propertyType.isPrimitive() && (Number.class.isAssignableFrom(propertyType)
                || Boolean.class.isAssignableFrom(propertyType))) {
            if (propertyConfig == null) {
                propertyConfig = new PropertyConfig();
            }
            if (propertyConfig.getEscapeValue() == PropertyConfig.NONE_VALUE) {
                propertyConfig.setEscapeValue(null);
            }
        }

        if (propertyConfig != null) {
            propertyConfigs.put(property, propertyConfig);
        }
    }
    return (propertyConfigs.isEmpty()) ? null : propertyConfigs;
}

From source file:com.googlecode.wicketwebbeans.model.BeanMetaData.java

private void init() {
    // Check if bean supports PropertyChangeListeners.
    hasAddPropertyChangeListenerMethod = getAddPropertyChangeListenerMethod() != null;
    hasRemovePropertyChangeListenerMethod = getRemovePropertyChangeListenerMethod() != null;

    String baseBeanClassName = getBaseClassName(beanClass);

    // Deduce actions from the component.
    List<Method> actionMethods = getActionMethods(component.getClass());
    for (Method method : actionMethods) {
        String name = method.getName();
        String prefixedName = ACTION_PROPERTY_PREFIX + name;
        String label = getLabelFromLocalizer(baseBeanClassName, prefixedName);
        if (label == null) {
            label = createLabel(name);//from   w  w w. ja  v  a2 s. co m
        }

        ElementMetaData actionMeta = new ElementMetaData(this, prefixedName, label, null);
        actionMeta.setAction(true);
        elements.add(actionMeta);
    }

    // Create defaults based on the bean itself.
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
    for (PropertyDescriptor descriptor : descriptors) {
        String name = descriptor.getName();

        // Skip getClass() and methods that are not readable or hidden.
        if (name.equals("class") || descriptor.getReadMethod() == null || descriptor.isHidden()) {
            continue;
        }

        String label = getLabelFromLocalizer(baseBeanClassName, name);
        if (label == null) {
            label = descriptor.getDisplayName();
        }

        if (label.equals(name)) {
            label = createLabel(name);
        }

        ElementMetaData propertyMeta = new ElementMetaData(this, name, label,
                descriptor.getReadMethod().getGenericReturnType());
        propertyMeta.setViewOnly(isViewOnly());
        elements.add(propertyMeta);

        if (descriptor.getWriteMethod() == null) {
            propertyMeta.setViewOnly(true);
        }

        deriveElementFromAnnotations(descriptor, propertyMeta);
    }

    // Collect various sources of metadata for the bean we're interested in. 
    collectAnnotations();
    collectFromBeanProps();
    collectBeansAnnotation(beansMetaData, false);

    // Process action annotations on component.
    for (Method method : getActionMethods(component.getClass())) {
        Action action = method.getAnnotation(Action.class);
        processActionAnnotation(action, method.getName());
    }

    // Determine the hierarchy of Bean contexts. I.e., the default Bean is always processed first, followed by those that
    // extend it, etc. This acts as a stack.
    List<Bean> beansHier = buildContextStack();

    // Apply beans in order from highest to lowest. The default context will always be first.
    boolean foundSpecifiedContext = false;
    for (Bean bean : beansHier) {
        if (context != null && context.equals(bean.context())) {
            foundSpecifiedContext = true;
        }

        processBeanAnnotation(bean);
    }

    // Ensure that if a context was specified, that we found one in the metadata. Otherwise it might have been a typo.
    if (context != null && !foundSpecifiedContext) {
        throw new RuntimeException("Could not find specified context '" + context + "' in metadata.");
    }

    // Post-process Bean-level parameters
    if (!getBooleanParameter(PARAM_DISPLAYED)) {
        elements.clear();
        tabs.clear();
    }

    // Configure tabs
    if (tabs.isEmpty()) {
        // Create single default tab.
        tabs.add(new TabMetaData(this, DEFAULT_TAB_ID, getParameter(PARAM_LABEL)));
    }

    String defaultTabId = tabs.get(0).getId();

    if (!getBooleanParameter(PARAM_EXPLICIT_ONLY) || defaultTabId.equals(DEFAULT_TAB_ID)) {
        // Post-process each property based on bean parameters
        for (ElementMetaData elementMeta : elements) {
            // If element is not on a tab, add it to the first. If it's an
            // action, it must have been assigned an order to
            // appear on a tab. Otherwise it is a global action.
            if (elementMeta.getTabId() == null && (!elementMeta.isAction()
                    || (elementMeta.isAction() && elementMeta.isActionSpecifiedInProps()))) {
                elementMeta.setTabId(defaultTabId);
            }
        }
    }

    // Remove elements not specified in props
    if (getBooleanParameter(PARAM_EXPLICIT_ONLY)) {
        for (Iterator<ElementMetaData> iter = elements.iterator(); iter.hasNext();) {
            ElementMetaData element = iter.next();
            if (!element.isSpecifiedInProps()) {
                iter.remove();
            }
        }
    }

    Collections.sort(elements, new Comparator<ElementMetaData>() {
        public int compare(ElementMetaData o1, ElementMetaData o2) {
            return (o1.getOrder() > o2.getOrder() ? 1 : (o1.getOrder() < o2.getOrder() ? -1 : 0));
        }
    });
}

From source file:it.geosolutions.geobatch.imagemosaic.ImageMosaicCommand.java

/**
 * set this instance null properties with the passed configuration
 * @param src/*from w  w  w  .j  a  va 2s.  c om*/
 */
public void copyConfigurationIntoCommand(final ImageMosaicConfiguration src) {

    final PropertyDescriptor[] srcProps = PropertyUtils.getPropertyDescriptors(src);
    for (PropertyDescriptor srcProp : srcProps) {
        final String name = srcProp.getName();
        if (RESERVED_PROPS.contains(name)) {
            continue;
        }
        final Object obj;
        try {
            obj = PropertyUtils.getProperty(this, name);
            if (obj == null) {
                // override
                PropertyUtils.setProperty(this, name, PropertyUtils.getProperty(src, name));
            }
        } catch (InvocationTargetException e) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(e.getMessage());
        } catch (NoSuchMethodException e) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(e.getMessage());
        } catch (IllegalAccessException e) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(e.getMessage());
        }
    }

    copyDomainAttributes(src, this);
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

private static Set<String> getProperties(Class<?> clss) {
    final Set<String> result = new TreeSet<>();
    final PropertyDescriptor[] map = PropertyUtils.getPropertyDescriptors(clss);

    for (PropertyDescriptor p : map) {
        if (p.getWriteMethod() != null) {
            result.add(p.getName());// ww  w  .  j a  va  2 s.c  o  m
        }
    }

    return result;
}

From source file:ca.sqlpower.sqlobject.BaseSQLObjectTestCase.java

/**
 * @throws IllegalArgumentException//from  ww w. j  a va 2s .com
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws SQLObjectException 
 */
public void testAllSettersAreUndoable() throws IllegalArgumentException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SQLObjectException {

    SQLObject so = getSQLObjectUnderTest();
    propertiesToIgnoreForUndo.add("referenceCount");
    propertiesToIgnoreForUndo.add("populated");
    propertiesToIgnoreForUndo.add("exportedKeysPopulated");
    propertiesToIgnoreForUndo.add("importedKeysPopulated");
    propertiesToIgnoreForUndo.add("columnsPopulated");
    propertiesToIgnoreForUndo.add("indicesPopulated");
    propertiesToIgnoreForUndo.add("SQLObjectListeners");
    propertiesToIgnoreForUndo.add("children");
    propertiesToIgnoreForUndo.add("parent");
    propertiesToIgnoreForUndo.add("parentDatabase");
    propertiesToIgnoreForUndo.add("class");
    propertiesToIgnoreForUndo.add("childCount");
    propertiesToIgnoreForUndo.add("undoEventListeners");
    propertiesToIgnoreForUndo.add("connection");
    propertiesToIgnoreForUndo.add("typeMap");
    propertiesToIgnoreForUndo.add("secondaryChangeMode");
    propertiesToIgnoreForUndo.add("zoomInAction");
    propertiesToIgnoreForUndo.add("zoomOutAction");
    propertiesToIgnoreForUndo.add("magicEnabled");
    propertiesToIgnoreForUndo.add("deleteRule");
    propertiesToIgnoreForUndo.add("updateRule");
    propertiesToIgnoreForUndo.add("tableContainer");
    propertiesToIgnoreForUndo.add("session");
    propertiesToIgnoreForUndo.add("workspaceContainer");
    propertiesToIgnoreForUndo.add("runnableDispatcher");
    propertiesToIgnoreForUndo.add("foregroundThread");

    if (so instanceof SQLDatabase) {
        // should be handled in the Datasource
        propertiesToIgnoreForUndo.add("name");
    }

    SPObjectUndoManager undoManager = new SPObjectUndoManager(so);
    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(so.getClass()));
    if (so instanceof SQLDatabase) {
        // should be handled in the Datasource
        settableProperties.remove("name");
    }
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForUndo.contains(property.getName()))
            continue;

        try {
            oldVal = PropertyUtils.getSimpleProperty(so, property.getName());
            if (property.getWriteMethod() == null) {
                continue;
            }
        } catch (NoSuchMethodException e) {
            System.out.println(
                    "Skipping non-settable property " + property.getName() + " on " + so.getClass().getName());
            continue;
        }
        Object newVal; // don't init here so compiler can warn if the following code doesn't always give it a value
        if (property.getPropertyType() == Integer.TYPE || property.getPropertyType() == Integer.class) {
            if (oldVal != null) {
                newVal = ((Integer) oldVal) + 1;
            } else {
                newVal = 1;
            }
        } else if (property.getPropertyType() == String.class) {
            // make sure it's unique
            newVal = "new " + oldVal;

        } else if (property.getPropertyType() == Boolean.TYPE || property.getPropertyType() == Boolean.class) {
            if (oldVal == null) {
                newVal = Boolean.TRUE;
            } else {
                newVal = new Boolean(!((Boolean) oldVal).booleanValue());
            }
        } else if (property.getPropertyType() == SQLCatalog.class) {
            newVal = new SQLCatalog(new SQLDatabase(), "This is a new catalog");
        } else if (property.getPropertyType() == SPDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1,tab2");
        } else if (property.getPropertyType() == JDBCDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1,tab2");
        } else if (property.getPropertyType() == SQLTable.class) {
            newVal = new SQLTable();
        } else if (property.getPropertyType() == SQLColumn.class) {
            newVal = new SQLColumn();
        } else if (property.getPropertyType() == SQLIndex.class) {
            newVal = new SQLIndex();
        } else if (property.getPropertyType() == SQLRelationship.SQLImportedKey.class) {
            SQLRelationship rel = new SQLRelationship();
            newVal = rel.getForeignKey();
        } else if (property.getPropertyType() == SQLRelationship.Deferrability.class) {
            if (oldVal == SQLRelationship.Deferrability.INITIALLY_DEFERRED) {
                newVal = SQLRelationship.Deferrability.NOT_DEFERRABLE;
            } else {
                newVal = SQLRelationship.Deferrability.INITIALLY_DEFERRED;
            }
        } else if (property.getPropertyType() == SQLIndex.AscendDescend.class) {
            if (oldVal == SQLIndex.AscendDescend.ASCENDING) {
                newVal = SQLIndex.AscendDescend.DESCENDING;
            } else {
                newVal = SQLIndex.AscendDescend.ASCENDING;
            }
        } else if (property.getPropertyType() == Throwable.class) {
            newVal = new Throwable();
        } else if (property.getPropertyType() == BasicSQLType.class) {
            if (oldVal != BasicSQLType.OTHER) {
                newVal = BasicSQLType.OTHER;
            } else {
                newVal = BasicSQLType.TEXT;
            }
        } else if (property.getPropertyType() == UserDefinedSQLType.class) {
            newVal = new UserDefinedSQLType();
        } else if (property.getPropertyType() == SQLTypeConstraint.class) {
            if (oldVal != SQLTypeConstraint.NONE) {
                newVal = SQLTypeConstraint.NONE;
            } else {
                newVal = SQLTypeConstraint.CHECK;
            }
        } else if (property.getPropertyType() == SQLCheckConstraint.class) {
            newVal = new SQLCheckConstraint("check constraint name", "check constraint condition");
        } else if (property.getPropertyType() == SQLEnumeration.class) {
            newVal = new SQLEnumeration("some enumeration");
        } else if (property.getPropertyType() == String[].class) {
            newVal = new String[3];
        } else if (property.getPropertyType() == PropertyType.class) {
            if (oldVal != PropertyType.NOT_APPLICABLE) {
                newVal = PropertyType.NOT_APPLICABLE;
            } else {
                newVal = PropertyType.VARIABLE;
            }
        } else {
            throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type "
                    + property.getPropertyType().getName() + ") from " + so.getClass());
        }

        int oldChangeCount = undoManager.getUndoableEditCount();

        try {
            BeanUtils.copyProperty(so, property.getName(), newVal);

            // some setters fire multiple events (they change more than one property)  but only register one as an undo
            assertEquals(
                    "Event for set " + property.getName() + " on " + so.getClass().getName()
                            + " added multiple (" + undoManager.printUndoVector() + ") undos!",
                    oldChangeCount + 1, undoManager.getUndoableEditCount());

        } catch (InvocationTargetException e) {
            System.out.println("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + so.getClass().getName());
        }
    }
}