Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:name.ikysil.beanpathdsl.codegen.CodeGen.java

private void generateBeanPathSource(Context context, Map<Class<?>, IncludedClass> transitiveClosure,
        Class<?> clazz, ClassName targetClassName) {
    logger.info("Generating {} for {}", targetClassName, clazz.getName());

    AnnotationSpec generatedSpec = AnnotationSpec.builder(Generated.class).addMember("value", "$S",
            String.format("Generated by beanpath-codegen for %s", ClassName.get(clazz))).build();

    AnnotationSpec navigatorSpec = AnnotationSpec.builder(Navigator.class).addMember("value", "$T.class", clazz)
            .build();/*from  w w  w .  j  ava 2 s.  co  m*/

    PropertyDescriptor[] pds = context.getPropertyDescriptors(clazz);
    Arrays.sort(pds, new Comparator<PropertyDescriptor>() {

        @Override
        public int compare(PropertyDescriptor o1, PropertyDescriptor o2) {
            return o1.getName().compareTo(o2.getName());
        }

    });

    Collection<FieldSpec> fieldSpecs = new ArrayList<>();
    Collection<MethodSpec> methodSpecs = new ArrayList<>();

    FieldSpec fieldSpec = FieldSpec.builder(targetClassName, getInstanceAccessor(clazz))
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
            .initializer("new $T()", targetClassName).build();
    fieldSpecs.add(fieldSpec);

    final ParameterizedTypeName fieldTypeName = ParameterizedTypeName.get(ClassName.get(Class.class),
            ClassName.get(clazz));
    fieldSpec = FieldSpec.builder(fieldTypeName, SOURCE_CLASS_FIELD_NAME)
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("$T.class", clazz)
            .build();
    fieldSpecs.add(fieldSpec);

    for (PropertyDescriptor pd : pds) {
        final String name = getNavigationMethodName(pd);
        Class<?> pdClass = pd.getPropertyType();
        if ((pdClass == null) && (pd instanceof IndexedPropertyDescriptor)) {
            pdClass = ((IndexedPropertyDescriptor) pd).getIndexedPropertyType();
        }
        ClassName bpAccessorClassName = classNames.get(pdClass);
        if (bpAccessorClassName == null) {
            pdClass = BaseNavigator.class;
            bpAccessorClassName = ClassName.get(pdClass);
        }
        MethodSpec pdMethodSpec = MethodSpec.methodBuilder(name).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .returns(bpAccessorClassName)
                .addCode(CodeBlock.builder().addStatement("navigate($S)", pd.getName())
                        .addStatement("return $T.$N", bpAccessorClassName, getInstanceAccessor(pdClass))
                        .build())
                .build();
        methodSpecs.add(pdMethodSpec);

        pdMethodSpec = MethodSpec.methodBuilder(name).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addParameter(ClassName.get(String.class), "propertyName", Modifier.FINAL)
                .returns(bpAccessorClassName)
                .addCode(CodeBlock.builder().addStatement("navigate($N)", "propertyName")
                        .addStatement("return $T.$N", bpAccessorClassName, getInstanceAccessor(pdClass))
                        .build())
                .build();
        methodSpecs.add(pdMethodSpec);
    }

    MethodSpec constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build();
    methodSpecs.add(constructor);

    TypeSpec typeSpec = TypeSpec.classBuilder(targetClassName).superclass(ClassName.get(BaseNavigator.class))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addAnnotation(generatedSpec)
            .addAnnotation(navigatorSpec).addFields(fieldSpecs).addMethods(methodSpecs).build();

    JavaFile javaFile = JavaFile.builder(targetClassName.packageName(), typeSpec).skipJavaLangImports(true)
            .indent("    ").build();

    try {
        javaFile.writeTo(Paths.get(configuration.getOutputDirectory()));
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java

/**
 * Build a JSP tag model object from an annotated tag class
 * @param type tag class/*from   w  ww.ja v  a  2s.  c  o  m*/
 * @return JSP tag model
 */
public JspTagModel getTagMetadata(Class<?> type) {
    JspTagModel metadata = new JspTagModel();
    JspTag jspTagAnnotation = type.getAnnotation(JspTag.class);
    metadata.bodyContent = jspTagAnnotation.bodyContent();
    metadata.name = jspTagAnnotation.name();
    metadata.tagClass = type.getName();
    metadata.dynamicAttributes = jspTagAnnotation.dynamicAttributes();

    for (JspVariable jspVariableAnnotation : jspTagAnnotation.variables()) {
        JspVariableModel variable = new JspVariableModel();
        variable.declare = jspVariableAnnotation.declare();

        variable.nameFromAttribute = StringUtils.stripToNull(jspVariableAnnotation.nameFromAttribute());
        variable.nameGiven = StringUtils.stripToNull(jspVariableAnnotation.nameGiven());

        variable.scope = jspVariableAnnotation.scope();
        variable.variableClass = jspVariableAnnotation.variableClass().getName();
        metadata.variables.add(variable);
    }

    for (PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors(type)) {
        s_log.debug("processing property {}", pd.getName());
        if (pd.getWriteMethod() != null && pd.getWriteMethod().isAnnotationPresent(JspAttribute.class)) {
            s_log.debug("attribute metadata present on {}", pd.getName());
            JspAttributeModel attr = new JspAttributeModel();
            attr.name = pd.getName();
            attr.type = pd.getPropertyType().getName();
            JspAttribute jspAttributeAnnotation = pd.getWriteMethod().getAnnotation(JspAttribute.class);
            attr.required = jspAttributeAnnotation.required();
            attr.rtExprValue = jspAttributeAnnotation.rtExprValue();
            attr.fragment = jspAttributeAnnotation.fragment();

            attr.deferredMethod = jspAttributeAnnotation.deferredMethod() ? true : null;
            attr.deferredValue = jspAttributeAnnotation.deferredValue() ? true : null;

            metadata.attributes.add(attr);
        }
    }

    return metadata;
}

From source file:com.gisgraphy.helper.BeanHelper.java

public boolean equals(final Object other, final Object current) {
    if (!current.getClass().isAssignableFrom(other.getClass())) {
        return false;
    }/*from   w w w  . j a  va2  s . c  om*/
    final String thisName = current.getClass().getSimpleName();
    final String objectName = other.getClass().getSimpleName();
    String propertyName;
    Exception exception;
    try {
        for (final PropertyDescriptor thisPropertyDescriptor : Introspector
                .getBeanInfo(current.getClass(), Object.class).getPropertyDescriptors()) {
            exception = null;
            propertyName = thisPropertyDescriptor.getName();
            logger.debug("propertyName=" + propertyName);
            try {
                if (!compareProperty(current, other, propertyName)) {
                    return false;
                }
            } catch (final IllegalAccessException e) {
                exception = e;
            } catch (final InvocationTargetException e) {
                exception = e;
            } catch (final NoSuchMethodException e) {
                exception = e;
            }
            if (exception != null) {
                logger.debug("impossible to compare property " + propertyName + " for beans " + thisName
                        + " and " + objectName, exception);
                continue;
            }
        }
    } catch (final IntrospectionException e) {
        logger.debug("impossible to get properties for bean " + thisName, e);
    }
    return true;
}

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

private void buildChildren(SPObject parent) {

    for (Class c : parent.getAllowedChildTypes()) {
        try {//from  w  ww .ja va 2 s  . com
            if (parent.getChildren(c).size() > 0) {
                logger.debug("It already had a " + c.getSimpleName() + "!");
                continue;
            }
            SPObject child;
            child = ((SPObject) valueMaker.makeNewValue(c, null, "child"));
            parent.addChild(child, parent.getChildren(c).size());
        } catch (Exception e) {
            logger.warn("Could not add a " + c.getSimpleName() + " to a " + parent.getClass().getSimpleName()
                    + " because of a " + e.getClass().getName());
        }
        try {
            Set<String> s = TestUtils.findPersistableBeanProperties(parent, false, false);

            List<PropertyDescriptor> settableProperties = Arrays
                    .asList(PropertyUtils.getPropertyDescriptors(parent.getClass()));
            TableMergeRules testParent = null; // special case- the parent of all others

            //set all properties of the object
            for (PropertyDescriptor property : settableProperties) {
                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(parent, property.getName());

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

                } catch (NoSuchMethodException e) {
                    logger.debug("Skipping non-settable property " + property.getName() + " on "
                            + parent.getClass().getName());
                    continue;
                }
                Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());
                if (property.getName().equals("parentMergeRule")) {
                    if (testParent == null) {
                        newVal = null;
                        testParent = (TableMergeRules) parent;
                    } else {
                        newVal = testParent;
                    }
                }
                try {
                    logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                            + (newVal == null ? "null" : newVal.getClass().getName()) + ")");
                    BeanUtils.copyProperty(parent, property.getName(), newVal);

                } catch (InvocationTargetException e) {
                    logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                            + parent.getClass().getName());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    for (SPObject spo : parent.getChildren()) {
        buildChildren(spo);
    }
}

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

protected void populateEntity(final Session session, final Class entityClass, final String[] propertyList,
        final Object[][] data) throws HibernateException {
    try {/*from   www. ja  va 2s.c  om*/
        final Hashtable pdsByName = new Hashtable();
        final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass);
        final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < descriptors.length; i++) {
            final PropertyDescriptor descriptor = descriptors[i];
            if (descriptor.getWriteMethod() != null)
                pdsByName.put(descriptor.getName(), descriptor.getWriteMethod());
        }

        for (int i = 0; i < data.length; i++) {
            final Object entityObject = entityClass.newInstance();
            for (int j = 0; j < propertyList.length; j++) {
                final Method setter = (Method) pdsByName.get(propertyList[j]);
                if (setter != null)
                    setter.invoke(entityObject, new Object[] { data[i][j] });
            }
            session.save(entityObject);
        }
    } catch (Exception e) {
        log.error(e);
        throw new HibernateException(e);
    }
}

From source file:net.solarnetwork.web.support.SimpleCsvView.java

private List<String> getCSVFields(Object row, final Collection<String> fieldOrder) {
    assert row != null;
    List<String> result = new ArrayList<String>();
    if (row instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) row;
        if (fieldOrder != null) {
            for (String key : fieldOrder) {
                result.add(key);//w w w. ja v  a 2  s .  co  m
            }
        } else {
            for (Object key : map.keySet()) {
                result.add(key.toString());
            }
        }
    } else {
        // use bean properties
        if (getPropertySerializerRegistrar() != null) {
            // try whole-bean serialization first
            Object o = getPropertySerializerRegistrar().serializeProperty("row", row.getClass(), row, row);
            if (o != row) {
                if (o != null) {
                    result = getCSVFields(o, fieldOrder);
                    return result;
                }
            }
        }
        BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(row);
        PropertyDescriptor[] props = wrapper.getPropertyDescriptors();
        Set<String> resultSet = new LinkedHashSet<String>();
        for (PropertyDescriptor prop : props) {
            String name = prop.getName();
            if (getJavaBeanIgnoreProperties() != null && getJavaBeanIgnoreProperties().contains(name)) {
                continue;
            }
            if (wrapper.isReadableProperty(name)) {
                // test for SerializeIgnore
                Method getter = prop.getReadMethod();
                if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                    continue;
                }
                resultSet.add(name);
            }
        }
        if (fieldOrder != null && fieldOrder.size() > 0) {
            for (String key : fieldOrder) {
                if (resultSet.contains(key)) {
                    result.add(key);
                }
            }
        } else {
            result.addAll(resultSet);
        }

    }
    return result;
}

From source file:com.google.code.pathlet.web.ognl.impl.OgnlUtil.java

/**
 * Copies the properties in the object "from" and sets them in the object "to"
 * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none
 * is specified./*from   w  w w  .ja  v  a  2 s. c  o m*/
 *
 * @param from       the source object
 * @param to         the target object
 * @param context    the action context we're running under
 * @param exclusions collection of method names to excluded from copying ( can be null)
 * @param inclusions collection of method names to included copying  (can be null)
 *                   note if exclusions AND inclusions are supplied and not null nothing will get copied.
 */
public void copy(Object from, Object to, Map<String, Object> context, Collection<String> exclusions,
        Collection<String> inclusions) {
    if (from == null || to == null) {
        log.warn(
                "Attempting to copy from or to a null source. This is illegal and is bein skipped. This may be due to an error in an OGNL expression, action chaining, or some other event.");

        return;
    }

    TypeConverter conv = defaultConverter;
    Map contextFrom = Ognl.createDefaultContext(from);
    Ognl.setTypeConverter(contextFrom, conv);
    Map contextTo = Ognl.createDefaultContext(to);
    Ognl.setTypeConverter(contextTo, conv);

    PropertyDescriptor[] fromPds;
    PropertyDescriptor[] toPds;

    try {
        fromPds = this.reflectionProvider.getPropertyDescriptors(from);
        toPds = this.reflectionProvider.getPropertyDescriptors(to);
    } catch (IntrospectionException e) {
        log.error("An error occured", e);

        return;
    }

    Map<String, PropertyDescriptor> toPdHash = new HashMap<String, PropertyDescriptor>();

    for (PropertyDescriptor toPd : toPds) {
        toPdHash.put(toPd.getName(), toPd);
    }

    for (PropertyDescriptor fromPd : fromPds) {
        if (fromPd.getReadMethod() != null) {
            boolean copy = true;
            if (exclusions != null && exclusions.contains(fromPd.getName())) {
                copy = false;
            } else if (inclusions != null && !inclusions.contains(fromPd.getName())) {
                copy = false;
            }

            if (copy == true) {
                PropertyDescriptor toPd = toPdHash.get(fromPd.getName());
                if ((toPd != null) && (toPd.getWriteMethod() != null)) {
                    try {
                        Object expr = compile(fromPd.getName());
                        Object value = Ognl.getValue(expr, contextFrom, from);
                        Ognl.setValue(expr, contextTo, to, value);
                    } catch (OgnlException e) {
                        // ignore, this is OK
                    }
                }

            }

        }

    }
}

From source file:gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportTreeTest.java

private List<String> listNames(PropertyDescriptor[] propertyDescriptors) {
    List<String> names = new ArrayList<String>(propertyDescriptors.length);
    for (PropertyDescriptor descriptor : propertyDescriptors) {
        names.add(descriptor.getName());
    }/*  w ww.j  a  v a  2  s  . co m*/
    return names;
}

From source file:org.springjutsu.validation.rules.ValidationRulesContainer.java

/**
 * Read from exclude annotations to further 
 * populate exclude paths already parsed from XML.
 *//*  w  w  w .j a  v a2  s. c o m*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initExcludePaths() {
    for (ValidationEntity entity : validationEntityMap.values()) {
        // no paths to check on an interface.
        if (entity.getValidationClass().isInterface()) {
            continue;
        }
        BeanWrapper entityWrapper = new BeanWrapperImpl(entity.getValidationClass());
        for (PropertyDescriptor descriptor : entityWrapper.getPropertyDescriptors()) {
            if (!entityWrapper.isReadableProperty(descriptor.getName())
                    || !entityWrapper.isWritableProperty(descriptor.getName())) {
                continue;
            }
            for (Class excludeAnnotation : excludeAnnotations) {
                try {
                    if (ReflectionUtils.findField(entity.getValidationClass(), descriptor.getName())
                            .getAnnotation(excludeAnnotation) != null) {
                        entity.getExcludedPaths().add(descriptor.getName());
                    }
                } catch (SecurityException se) {
                    throw new IllegalStateException("Unexpected error while checking for excluded properties",
                            se);
                }
            }
        }
    }
}

From source file:org.springjutsu.validation.rules.ValidationRulesContainer.java

/**
 * Read from include annotations to further 
 * populate include paths already parsed from XML.
 *//*  w  w w  . ja v  a 2  s .c o  m*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initIncludePaths() {
    for (ValidationEntity entity : validationEntityMap.values()) {
        // no paths to check on an interface.
        if (entity.getValidationClass().isInterface()) {
            continue;
        }
        BeanWrapper entityWrapper = new BeanWrapperImpl(entity.getValidationClass());
        for (PropertyDescriptor descriptor : entityWrapper.getPropertyDescriptors()) {
            if (!entityWrapper.isReadableProperty(descriptor.getName())
                    || !entityWrapper.isWritableProperty(descriptor.getName())) {
                continue;
            }
            for (Class includeAnnotation : includeAnnotations) {
                try {
                    if (ReflectionUtils.findField(entity.getValidationClass(), descriptor.getName())
                            .getAnnotation(includeAnnotation) != null) {
                        entity.getIncludedPaths().add(descriptor.getName());
                    }
                } catch (SecurityException se) {
                    throw new IllegalStateException("Unexpected error while checking for included properties",
                            se);
                }
            }
        }
    }
}