Example usage for java.beans PropertyDescriptor getDisplayName

List of usage examples for java.beans PropertyDescriptor getDisplayName

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getDisplayName.

Prototype

public String getDisplayName() 

Source Link

Document

Gets the localized display name of this feature.

Usage

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

/**
 * Generate Tesla schema from Java class by reflection.
 * <p>//from   w  w w.  j  a v  a2 s.  co 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.matchmaker.MatchMakerTestCase.java

public void testDuplicate() throws Exception {
    MatchMakerObject mmo = getTarget();/*from  w  w  w .  ja  v a  2s  . co  m*/

    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(mmo.getClass()));
    propertiesToIgnoreForDuplication.add("defaultInputClass");
    propertiesToIgnoreForDuplication.add("parameters");
    propertiesToIgnoreForDuplication.add("MSOInputs");
    propertiesToIgnoreForDuplication.add("UUID");
    propertiesToIgnoreForDuplication.add("oid");
    propertiesToIgnoreForDuplication.add("parent");
    propertiesToIgnoreForDuplication.add("parentProject");
    propertiesToIgnoreForDuplication.add("session");
    propertiesToIgnoreForDuplication.add("allowedChildTypes");
    propertiesToIgnoreForDuplication.add("cachableTable");
    propertiesToIgnoreForDuplication.add("cachableColumn");
    propertiesToIgnoreForDuplication.add("importedCachableColumn");
    propertiesToIgnoreForDuplication.add("class");
    propertiesToIgnoreForDuplication.add("createDate");
    propertiesToIgnoreForDuplication.add("createAppUser");
    propertiesToIgnoreForDuplication.add("createOsUser");
    propertiesToIgnoreForDuplication.add("dependencies");
    propertiesToIgnoreForDuplication.add("children");
    propertiesToIgnoreForDuplication.add("lastUpdateDate");
    propertiesToIgnoreForDuplication.add("lastUpdateAppUser");
    propertiesToIgnoreForDuplication.add("lastUpdateOSUser");
    propertiesToIgnoreForDuplication.add("magicEnabled");
    propertiesToIgnoreForDuplication.add("mergingEngine");
    propertiesToIgnoreForDuplication.add("matchingEngine");
    propertiesToIgnoreForDuplication.add("cleansingEngine");
    propertiesToIgnoreForDuplication.add("addressCorrectionEngine");
    propertiesToIgnoreForDuplication.add("addressCommittingEngine");
    propertiesToIgnoreForDuplication.add("undoing");
    propertiesToIgnoreForDuplication.add("results");
    propertiesToIgnoreForDuplication.add("runningEngine");
    propertiesToIgnoreForDuplication.add("runnableDispatcher");
    propertiesToIgnoreForDuplication.add("workspaceContainer");
    propertiesToIgnoreForDuplication.add("tableMergeRules");
    propertiesToIgnoreForDuplication.add("resultStep");
    propertiesToIgnoreForDuplication.add("inputSteps");
    propertiesToIgnoreForDuplication.add("mungeSteps");
    propertiesToIgnoreForDuplication.add("projects");
    propertiesToIgnoreForDuplication.add("JDBCDataSource");
    propertiesToIgnoreForDuplication.add("table");
    propertiesToIgnoreForDuplication.add("tableIndex");
    propertiesToIgnoreForDuplication.add("columnMergeRules");
    propertiesToIgnoreForDuplication.add("inputs");
    propertiesToIgnoreForDuplication.add("mungeStepOutputs");
    propertiesToIgnoreForDuplication.add("parameterNames");
    propertiesToIgnoreForDuplication.add("project");
    propertiesToIgnoreForDuplication.add("addressStatus");
    propertiesToIgnoreForDuplication.add("addressDB");
    propertiesToIgnoreForDuplication.add("open");
    propertiesToIgnoreForDuplication.add("expanded");
    propertiesToIgnoreForDuplication.add("position");
    propertiesToIgnoreForDuplication.add("inputCount");
    propertiesToIgnoreForDuplication.add("matchPool");
    propertiesToIgnoreForDuplication.add("resultTableCatalog");
    propertiesToIgnoreForDuplication.add("resultTableName");
    propertiesToIgnoreForDuplication.add("resultTableSchema");
    propertiesToIgnoreForDuplication.add("resultTableSPDataSource");
    propertiesToIgnoreForDuplication.add("sourceTableCatalog");
    propertiesToIgnoreForDuplication.add("sourceTableName");
    propertiesToIgnoreForDuplication.add("sourceTableSchema");
    propertiesToIgnoreForDuplication.add("sourceTableSPDataSource");
    propertiesToIgnoreForDuplication.add("xrefTableCatalog");
    propertiesToIgnoreForDuplication.add("xrefTableName");
    propertiesToIgnoreForDuplication.add("xrefTableSchema");
    propertiesToIgnoreForDuplication.add("xrefTableSPDataSource");

    //this throws an exception if the DS does not exist
    propertiesToIgnoreForDuplication.add("spDataSource");

    // 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 (propertiesToIgnoreForDuplication.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(mmo, property.getName());
            // check for a setter
            if (property.getWriteMethod() != null && !property.getName().equals("children")) {
                Object newVal = getNewDifferentValue(mmo, property, oldVal);
                BeanUtils.copyProperty(mmo, property.getName(), newVal);
            }
        } catch (NoSuchMethodException e) {
            System.out.println(
                    "Skipping non-settable property " + property.getName() + " on " + mmo.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. 
    MatchMakerObject duplicate = mmo.duplicate((MatchMakerObject) mmo.getParent());
    for (PropertyDescriptor property : settableProperties) {
        if (propertiesToIgnoreForDuplication.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(mmo, property.getName());
            /*
             * If this value is an unmodifiable list, it is then going to be a property
             * we do not wish to test duplication for, like the children lists. This
             * is a way to catch them all at once.
             */
            boolean listIsModifiable = true;
            if (oldVal instanceof List) {
                List l = (List) oldVal;
                try {
                    l.add("test");
                    l.remove("test");
                } catch (UnsupportedOperationException e) {
                    listIsModifiable = false;
                }
            }
            if (listIsModifiable) {
                Object copyVal = PropertyUtils.getSimpleProperty(duplicate, property.getName());
                if (oldVal == null) {
                    throw new NullPointerException("We forgot to set " + property.getName());
                } else {
                    if (oldVal instanceof MungeStep) {
                        MungeStep oldStep = (MungeStep) oldVal;
                        MungeStep copyStep = (MungeStep) copyVal;
                        assertNotSame("The two MungeStep's share the same instance.", oldVal, copyVal);

                        assertEquals("The two names are different.", oldStep.getName(), copyStep.getName());
                        assertEquals("The two visible properties are different.", oldStep.isVisible(),
                                copyStep.isVisible());

                    } else {
                        assertEquals("The two values for property " + property.getDisplayName() + " in "
                                + mmo.getClass().getName() + " should be equal", oldVal, copyVal);

                        if (propertiesShareInstanceForDuplication.contains(property.getName()))
                            return;

                        /*
                         * Ok, the duplicate object's property value compared equal.
                         * Now we want to make sure if we modify that property on the original,
                         * it won't affect the copy.
                         */
                        Object newCopyVal = modifyObject(mmo, property, copyVal);

                        assertFalse(
                                "The two values are the same mutable object for property "
                                        + property.getDisplayName() + " was " + oldVal + " and " + copyVal,
                                oldVal.equals(newCopyVal));
                    }
                }
            }
        } catch (NoSuchMethodException e) {
            System.out.println(
                    "Skipping non-settable property " + property.getName() + " on " + mmo.getClass().getName());
        }
    }
}

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

/**
 * XXX This test should use the {@link GenericNewValueMaker} as it has it's own mini
 * version inside it. This test should also be using the annotations to decide which 
 * setters can fire events.//  www .j a  va  2  s  . c  o  m
 * 
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws SQLObjectException
 */
public void testAllSettersGenerateEvents() throws IllegalArgumentException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SQLObjectException {
    SQLObject so = getSQLObjectUnderTest();
    so.populate();

    propertiesToIgnoreForEventGeneration.addAll(getPropertiesToIgnoreForEvents());

    //Ignored because we expect the object to be populated.
    propertiesToIgnoreForEventGeneration.add("exportedKeysPopulated");
    propertiesToIgnoreForEventGeneration.add("importedKeysPopulated");
    propertiesToIgnoreForEventGeneration.add("columnsPopulated");
    propertiesToIgnoreForEventGeneration.add("indicesPopulated");

    CountingSQLObjectListener listener = new CountingSQLObjectListener();
    SQLPowerUtils.listenToHierarchy(so, listener);

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

    List<PropertyDescriptor> settableProperties;

    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(so.getClass()));

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForEventGeneration.contains(property.getName()))
            continue;

        try {
            oldVal = PropertyUtils.getSimpleProperty(so, property.getName());
            // check for a setter
            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");
        } 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");
        } 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() == SQLRelationship.UpdateDeleteRule.class) {
            if (oldVal == SQLRelationship.UpdateDeleteRule.CASCADE) {
                newVal = SQLRelationship.UpdateDeleteRule.RESTRICT;
            } else {
                newVal = SQLRelationship.UpdateDeleteRule.CASCADE;
            }
        } 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() == 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 if (property.getPropertyType() == List.class) {
            newVal = Arrays.asList("one", "two");
        } else {
            throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type "
                    + property.getPropertyType().getName() + ") from " + so.getClass() + " on property "
                    + property.getDisplayName());
        }

        int oldChangeCount = listener.getChangedCount();

        try {
            System.out.println("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(so, property.getName(), newVal);

            // some setters fire multiple events (they change more than one property)
            assertTrue(
                    "Event for set " + property.getName() + " on " + so.getClass().getName() + " didn't fire!",
                    listener.getChangedCount() > oldChangeCount);
            if (listener.getChangedCount() == oldChangeCount + 1) {
                assertEquals("Property name mismatch for " + property.getName() + " in " + so.getClass(),
                        property.getName(), ((PropertyChangeEvent) listener.getLastEvent()).getPropertyName());
                assertEquals("New value for " + property.getName() + " was wrong", newVal,
                        ((PropertyChangeEvent) listener.getLastEvent()).getNewValue());
            }
        } catch (InvocationTargetException e) {
            System.out.println("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + so.getClass().getName());
        }
    }
}

From source file:net.sourceforge.vulcan.web.struts.forms.PluginConfigForm.java

public void introspect(HttpServletRequest request) throws IntrospectionException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, InstantiationException {
    Class<?> cls = null;//from   www.j  a va  2 s  . co  m

    if ("pluginConfig".equals(focus)) {
        cls = pluginConfig.getClass();
        this.breadCrumbs.clear();
        this.breadCrumbs.add("Setup");

        if (isProjectPlugin()) {
            this.breadCrumbs.add("Projects");
            this.breadCrumbs.add(projectName);
            this.breadCrumbs.add(this.pluginConfig.getPluginName());
        } else {
            this.breadCrumbs.add("Plugins");
            this.breadCrumbs.add(this.pluginConfig.getPluginName());
        }
    } else {
        cls = PropertyUtils.getPropertyType(this, focus);
        if (cls.isArray()) {
            cls = cls.getComponentType();
        }
    }

    final String prefix = focus + ".";
    final PropertyDescriptor[] pds;

    if (PluginConfigDto.class.isAssignableFrom(cls)) {
        final PluginConfigDto pluginConfig = (PluginConfigDto) getFocusObject();
        final List<PropertyDescriptor> tmp = pluginConfig.getPropertyDescriptors(request.getLocale());
        pds = tmp.toArray(new PropertyDescriptor[tmp.size()]);

        if (pluginConfig instanceof PluginProfileDto) {
            ((PluginProfileDto) pluginConfig).checkPoint();
        }
    } else {
        final BeanInfo beanInfo = Introspector.getBeanInfo(cls);
        Introspector.flushFromCaches(cls);
        pds = beanInfo.getPropertyDescriptors();
    }

    if (isNested()) {
        for (PropertyDescriptor pd : propertyDescriptors) {
            if (focus.startsWith(pd.getName())) {
                breadCrumbs.add(pd.getDisplayName());
            }
        }
    }

    types.clear();
    choices.clear();
    propertyDescriptors.clear();
    hiddenPasswords.clear();

    for (PropertyDescriptor pd : pds) {
        final String name = prefix + pd.getName();
        final PropertyDescriptor cp = new PropertyDescriptor(pd.getName(), pd.getReadMethod(),
                pd.getWriteMethod());
        cp.setShortDescription(pd.getShortDescription());
        cp.setDisplayName(pd.getDisplayName());
        cp.setName(name);
        propertyDescriptors.add(cp);
        types.put(name, getTypeAndPrepare(name, pd));
    }

    putBreadCrumbsInRequest(request);
}

From source file:net.zcarioca.zcommons.config.data.BeanPropertySetterFactory.java

/**
 * Gets a collection of {@link BeanPropertySetter} to configure the bean.
 *
 * @param bean The bean to configure.//from ww  w.j a v a2s .  c om
 * @return Returns a collection of {@link BeanPropertySetter}.
 * @throws ConfigurationException
 */
public Collection<BeanPropertySetter> getPropertySettersForBean(Object bean) throws ConfigurationException {
    List<BeanPropertySetter> setters = new ArrayList<BeanPropertySetter>();
    Map<String, PropertyDescriptor> descriptors = new HashMap<String, PropertyDescriptor>();

    Class<?> beanClass = bean.getClass();

    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
            Method reader = desc.getReadMethod();
            Method writer = desc.getWriteMethod();
            Field field = getField(beanClass, desc);

            if (reader != null) {
                descriptors.put(desc.getDisplayName(), desc);
            }

            if (writer != null) {
                if (writer.isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            writer.getAnnotation(ConfigurableAttribute.class)));
                    descriptors.remove(desc.getDisplayName());
                }
                if (reader != null && reader.isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            reader.getAnnotation(ConfigurableAttribute.class)));
                    descriptors.remove(desc.getDisplayName());
                }
            }
        }
    } catch (Throwable t) {
        throw new ConfigurationException("Could not introspect bean class", t);
    }
    do {
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ConfigurableAttribute.class)) {
                if (descriptors.containsKey(field.getName())
                        && descriptors.get(field.getName()).getWriteMethod() != null) {
                    PropertyDescriptor desc = descriptors.get(field.getName());
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            field.getAnnotation(ConfigurableAttribute.class)));
                } else {
                    setters.add(new FieldBeanPropertySetter(bean, null, field,
                            field.getAnnotation(ConfigurableAttribute.class)));
                }
            } else if (descriptors.containsKey(field.getName())) {
                // the annotation may have been set on the getter, not the field
                PropertyDescriptor desc = descriptors.get(field.getName());
                if (desc.getReadMethod().isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new FieldBeanPropertySetter(bean, desc, field,
                            desc.getReadMethod().getAnnotation(ConfigurableAttribute.class)));
                }
            }
        }
    } while ((beanClass = beanClass.getSuperclass()) != null);
    return setters;
}

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

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

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

    }
}

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

/**
 * @param superClass/* ww w  . j  ava2  s.  c  o m*/
 */
private void checkPropertiesForClass(Class<?> superClass) {
    getLog().debug("Check properties for class " + superClass.getName());
    // get all property descriptors
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(superClass);
    // for all properties, add it to component. If property have not abstract getter/setter ,
    // add it with exist = true . If property in list of hidden names, set hidden = true.
    PropertyBean property;
    for (int i = 0; i < properties.length; i++) {
        PropertyDescriptor descriptor = properties[i];
        if (!containProperty(descriptor.getName())) {
            if (isIgnorableProperty(superClass, descriptor.getName())) {
                continue;
            }
            Class<?> type = descriptor.getPropertyType();
            getLog().debug("Register property  " + descriptor.getName() + " with type name "
                    + type.getCanonicalName());
            property = new PropertyBean();
            property.setName(descriptor.getName());
            property.setDescription(descriptor.getShortDescription());
            property.setDisplayname(descriptor.getDisplayName());
            property.setClassname(descriptor.getPropertyType().getCanonicalName());
            property.setExist(true);
            addProperty(property);
        } else {
            // Load and check property.
            getLog().debug("Check  property  " + descriptor.getName());
            property = (PropertyBean) this.properties.get(descriptor.getName());
            if (property.getClassname() == null) {
                property.setClassname(descriptor.getPropertyType().getCanonicalName());
            } else {
                if (!property.getClassname().equals(descriptor.getPropertyType().getCanonicalName())) {
                    String message = "Class " + property.getClassname() + " for property " + property.getName()
                            + " not equals with real bean property type: "
                            + descriptor.getPropertyType().getCanonicalName();
                    getLog().error(message);
                    //throw new IllegalArgumentException(message);
                }
            }
            if (property.getDescription() == null) {
                property.setDescription(descriptor.getShortDescription());
            }
            if (property.getDisplayname() == null) {
                property.setDisplayname(descriptor.getDisplayName());
            }
            property.setExist(true);
        }
        Method getter = descriptor.getReadMethod();
        Method setter = descriptor.getWriteMethod();
        // Abstract methods
        if (null != setter && null != getter) {
            if ((Modifier.isAbstract(getter.getModifiers()) && Modifier.isAbstract(setter.getModifiers()))
                    || superClass.isInterface()) {
                getLog().debug("Detect as abstract property  " + descriptor.getName());
                property.setExist(false);
            }
        }

        if (null == setter || (!Modifier.isPublic(setter.getModifiers()))) {
            getLog().debug("Detect as hidden property  " + descriptor.getName());
            property.setHidden(true);
        }
        if (isAttachedProperty(property)) {
            property.setAttachedstate(true);
        }
        if (property.isInstanceof("javax.faces.el.MethodBinding")
                || property.isInstanceof("javax.faces.el.ValueBinding")) {
            property.setElonly(true);
        }

    }
}

From source file:org.androidtransfuse.processor.Merger.java

private <T extends Mergeable> T mergeMergeable(Class<? extends T> targetClass, T target, T source)
        throws MergerException {

    try {//from  w w  w. jav a 2  s .c  o  m

        BeanInfo beanInfo = Introspector.getBeanInfo(targetClass);

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            Method getter = propertyDescriptor.getReadMethod();
            Method setter = propertyDescriptor.getWriteMethod();

            String propertyName = propertyDescriptor.getDisplayName();

            if (PropertyUtils.isWriteable(target, propertyName)) {

                //check for mergeCollection
                MergeCollection mergeCollection = findAnnotation(MergeCollection.class, getter, setter);
                if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                    PropertyUtils.setProperty(target, propertyName,
                            mergeList(mergeCollection, propertyName, target, source));
                }

                //check for merge
                Merge mergeAnnotation = findAnnotation(Merge.class, getter, setter);
                PropertyUtils.setProperty(target, propertyName,
                        mergeProperties(mergeAnnotation, propertyName, target, source));
            }
        }
    } catch (NoSuchMethodException e) {
        throw new MergerException("NoSuchMethodException while trying to merge", e);
    } catch (IntrospectionException e) {
        throw new MergerException("IntrospectionException while trying to merge", e);
    } catch (IllegalAccessException e) {
        throw new MergerException("IllegalAccessException while trying to merge", e);
    } catch (InvocationTargetException e) {
        throw new MergerException("InvocationTargetException while trying to merge", e);
    }

    return target;
}

From source file:org.apache.axis2.jaxws.utility.XMLRootElementUtil.java

/**
 * The JAXBClass has a set of bean properties each represented by a PropertyDescriptor Each of
 * the fields of the class has an associated xml name. The method returns a map where the key is
 * the xml name and value is the PropertyDescriptor
 *
 * @param jaxbClass/*ww  w. j a  v a2  s .c o m*/
 * @return map
 */
public static Map<String, PropertyDescriptorPlus> createPropertyDescriptorMap(Class jaxbClass)
        throws NoSuchFieldException, IntrospectionException {

    if (log.isDebugEnabled()) {
        log.debug("Get the PropertyDescriptor[] for " + jaxbClass);
    }

    PropertyDescriptor[] pds = Introspector.getBeanInfo(jaxbClass).getPropertyDescriptors();
    Map<String, PropertyDescriptorPlus> map = new HashMap<String, PropertyDescriptorPlus>();

    // Unfortunately the element names are stored on the fields.
    // Get all of the fields in the class and super classes

    List<Field> fields = getFields(jaxbClass);

    // Now match up the fields with the property descriptors...Sigh why didn't JAXB put the @XMLElement annotations on the 
    // property methods!
    for (PropertyDescriptor pd : pds) {

        // Skip over the class property..it is never represented as an xml element
        if (pd.getName().equals("class")) {
            continue;
        }

        // For the current property, find a matching field...so that we can get the xml name
        boolean found = false;
        if (log.isDebugEnabled()) {
            log.debug("  Start: Find xmlname for property:" + pd.getName());
        }
        for (Field field : fields) {
            String fieldName = field.getName();

            // Use the name of the field and property to find the match
            if (fieldName.equalsIgnoreCase(pd.getDisplayName()) || fieldName.equalsIgnoreCase(pd.getName())) {
                // Get the xmlElement name for this field
                QName xmlName = getXmlElementRefOrElementQName(field.getDeclaringClass(), field);
                found = true;
                if (log.isDebugEnabled()) {
                    log.debug("    Found field " + field.getName() + " which has xmlname=" + xmlName);
                }
                if (map.get(xmlName) != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("    ALERT: property " + map.get(xmlName).getPropertyName()
                                + " already has this same xmlName..this may cause problems.");
                    }
                }
                map.put(xmlName.getLocalPart(), new PropertyDescriptorPlus(pd, xmlName));
                break;
            }

            // Unfortunately, sometimes the field name is preceeded by an underscore
            if (fieldName.startsWith("_")) {
                fieldName = fieldName.substring(1);
                if (fieldName.equalsIgnoreCase(pd.getDisplayName())
                        || fieldName.equalsIgnoreCase(pd.getName())) {
                    // Get the xmlElement name for this field
                    QName xmlName = getXmlElementRefOrElementQName(field.getDeclaringClass(), field);
                    found = true;
                    if (log.isDebugEnabled()) {
                        log.debug("    Found field " + field.getName() + " which has xmlname=" + xmlName);
                    }
                    if (map.get(xmlName) != null) {
                        if (log.isDebugEnabled()) {
                            log.debug("    ALERT: property " + map.get(xmlName).getPropertyName()
                                    + " already has this same xmlName..this may cause problems.");
                        }
                    }
                    map.put(xmlName.getLocalPart(), new PropertyDescriptorPlus(pd, xmlName));
                    break;
                }
            }
        }

        // We didn't find a field.  Default the xmlname to the property name
        if (!found) {
            String xmlName = pd.getName();
            if (log.isDebugEnabled()) {
                log.debug("    A matching field was not found.  Defaulting xmlname to " + xmlName);
            }
            if (map.get(xmlName) != null) {
                if (log.isDebugEnabled()) {
                    log.debug("    ALERT: property " + map.get(xmlName).getPropertyName()
                            + " already has this same xmlName..this may cause problems.");
                }
            }
            map.put(xmlName, new PropertyDescriptorPlus(pd, xmlName));
        }
        if (log.isDebugEnabled()) {
            log.debug("  End: Find xmlname for property:" + pd.getName());
        }
    }
    return map;
}

From source file:org.apache.jmeter.testbeans.gui.GenericTestBeanCustomizer.java

private JLabel createLabel(PropertyDescriptor desc) {
    String text = desc.getDisplayName();
    if (!"".equals(text)) {
        text = propertyFieldLabelMessage.format(new Object[] { desc.getDisplayName() });
    }//from  w  ww . j  a  v  a2 s .  c o m
    // if the displayName is the empty string, leave it like that.
    JLabel label = new JLabel(text);
    label.setHorizontalAlignment(SwingConstants.TRAILING);
    label.setToolTipText(propertyToolTipMessage.format(new Object[] { desc.getShortDescription() }));

    return label;
}