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:com.github.dactiv.common.bundle.BeanResourceBundle.java

/**
 * ?bean?mapkey/*w  w w .  jav a 2s  .c o m*/
 */
@Override
public Enumeration<String> getKeys() {

    Vector<String> vector = new Vector<String>();
    PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(bean.getClass());
    //???bean
    for (PropertyDescriptor pd : propertyDescriptors) {
        //get/set???
        if ((pd.getWriteMethod() == null) || pd.getReadMethod() == null) {
            continue;
        }

        String key = pd.getName();

        /*
         * ?map?:
         * 1.include
         * 2.?exclude
         * 3.ignoreNullValuetrue,?null
         */
        if (isIncludeProperty(key) && !isExcludeProperty(key)) {

            if (ignoreNullValue && ReflectionUtils.invokeGetterMethod(bean, key) == null) {
                continue;
            }

            vector.addElement(key);
        }
    }

    //?mapkey
    return vector.elements();
}

From source file:io.github.moosbusch.lumpi.gui.form.spi.AbstractDynamicForm.java

protected final Form.Section createSection(Class<?> beanClass, PropertyDescriptor[] propDescs)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    Form.Section result = new Form.Section();
    String sectHeading = getSectionHeading();
    Map<String, Class<?>> propertyMap = new HashMap<>();
    propertyMap.setComparator(Comparator.naturalOrder());

    if ((isShowSectionHeading()) && (StringUtils.isNotBlank(sectHeading))) {
        result.setHeading(sectHeading);/*from   w  w w .  j  a  va2  s . c  o m*/
    }

    for (PropertyDescriptor propDesc : propDescs) {
        propertyMap.put(propDesc.getName(), propDesc.getPropertyType());
    }

    for (String propertyName : propertyMap) {
        Class<?> propertyClass = ClassUtils.primitiveToWrapper(propertyMap.get(propertyName));

        FormEditor<? extends Component> editor;

        if (!isExcludedProperty(beanClass, propertyName)) {
            editor = getEditor(beanClass.getName(), propertyClass.getName(), propertyName);

            if (editor != null) {
                Component cmp = editor.getComponent();
                PropertyUtils.setProperty(cmp, editor.getDataBindingKeyPropertyName(), propertyName);
                setLabel(cmp, StringUtils.capitalize(propertyName));

                if (editor.isScrollable()) {
                    ScrollPane scroll = Objects.requireNonNull(createScrollPane());
                    scroll.setView(cmp);
                    result.add(scroll);
                } else {
                    result.add(cmp);
                }
            }
        }
    }

    return result;
}

From source file:com.emc.ecs.sync.config.ConfigWrapper.java

public ConfigWrapper(Class<C> targetClass) {
    try {/*w  ww  .ja v a2  s  .c  om*/
        this.targetClass = targetClass;
        if (targetClass.isAnnotationPresent(StorageConfig.class))
            this.uriPrefix = targetClass.getAnnotation(StorageConfig.class).uriPrefix();
        if (targetClass.isAnnotationPresent(FilterConfig.class))
            this.cliName = targetClass.getAnnotation(FilterConfig.class).cliName();
        if (targetClass.isAnnotationPresent(Label.class))
            this.label = targetClass.getAnnotation(Label.class).value();
        if (targetClass.isAnnotationPresent(Documentation.class))
            this.documentation = targetClass.getAnnotation(Documentation.class).value();
        BeanInfo beanInfo = Introspector.getBeanInfo(targetClass);
        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            if (descriptor.getReadMethod().isAnnotationPresent(Option.class)) {
                propertyMap.put(descriptor.getName(), new ConfigPropertyWrapper(descriptor));
            }
        }
        for (MethodDescriptor descriptor : beanInfo.getMethodDescriptors()) {
            Method method = descriptor.getMethod();
            if (method.isAnnotationPresent(UriParser.class)) {
                if (method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length == 1
                        && method.getParameterTypes()[0].equals(String.class)) {
                    uriParser = method;
                } else {
                    log.warn("illegal signature for @UriParser method {}.{}", targetClass.getSimpleName(),
                            method.getName());
                }
            } else if (method.isAnnotationPresent(UriGenerator.class)) {
                if (method.getReturnType().equals(String.class) && method.getParameterTypes().length == 0) {
                    uriGenerator = method;
                } else {
                    log.warn("illegal signature for @UriGenerator method {}.{}", targetClass.getSimpleName(),
                            method.getName());
                }
            }
        }
        if (propertyMap.isEmpty())
            log.info("no @Option annotations found in {}", targetClass.getSimpleName());
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.knightsoftnet.validators.rebind.GwtReflectGetterGenerator.java

@Override
public final String generate(final TreeLogger plogger, final GeneratorContext pcontext, final String ptypeName)
        throws UnableToCompleteException {
    try {//ww w . j  a va2s .co m
        plogger.log(TreeLogger.DEBUG, "Start generating for " + ptypeName + ".");

        final JClassType classType = pcontext.getTypeOracle().getType(ptypeName);
        final TypeOracle typeOracle = pcontext.getTypeOracle();
        assert typeOracle != null;
        final JClassType reflectorType = this.findType(plogger, typeOracle, ptypeName);

        // here you would retrieve the metadata based on typeName for this class
        final SourceWriter src = this.getSourceWriter(classType, pcontext, plogger);

        // generator is called more then once in a build, with second call, we don't get
        // a writer and needn't generate the class once again
        if (src != null) {
            final Class<?>[] classes = this.getBeans(plogger, reflectorType);

            src.println("@Override");
            src.println("public final Object getProperty(final Object pbean, final String pname)"
                    + " throws NoSuchMethodException, ReflectiveOperationException {");

            src.println("  if (pbean == null) {");
            src.println("    throw new NoSuchMethodException(\"A null object has no getters\");");
            src.println("  }");
            src.println("  if (pname == null) {");
            src.println("    throw new NoSuchMethodException(\"No method to get property for null\");");
            src.println("  }");
            src.println(StringUtils.EMPTY);

            for (final Class<?> clazz : classes) {
                final String className = clazz.getName();
                plogger.log(TreeLogger.DEBUG, "Generating getter reflections for class " + className);

                // Describe the bean properties
                final PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(clazz);

                src.println("  if (pbean.getClass() == " + className + ".class) {");
                src.println("    switch (pname) {");

                // for all getters generate a case and return entry
                for (final PropertyDescriptor property : properties) {

                    final Method readMethod = property.getReadMethod();
                    final String name = property.getName();
                    if (readMethod == null) {
                        continue; // If the property cannot be read
                    }
                    plogger.log(TreeLogger.DEBUG, "Add getter for property " + name);

                    // Invoke the getter on the bean
                    src.println("      case \"" + name + "\":");
                    src.println("        return ((" + className + ") pbean)." + readMethod.getName() + "();");
                }

                src.println("      default:");
                src.println("        throw new NoSuchMethodException(\"Class " + className
                        + " has no getter for porperty \" + pname);");
                src.println("    }");
                src.println("  }");
            }
            src.println("  throw new ReflectiveOperationException(\"Class \" + "
                    + "pbean.getClass().getName() + \" is not reflected\");");
            src.println("}");

            plogger.log(TreeLogger.DEBUG, "End of generating reached");

            src.commit(plogger);
        }
        return this.getClassPackage(classType) + "." + this.getClassName(classType);
    } catch (final NotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.fmguler.ven.QueryMapper.java

protected void mapRecursively(ResultSet rs, Set columns, String tableName, Class objectClass, List parentList) {
    try {// ww w .ja  va2  s.  co  m
        if (!columns.contains(tableName + "_id"))
            return; //this object does not exist in the columns
        Object id = rs.getObject(tableName + "_id");
        if (id == null)
            return; //this object exists in the columns but null, probably because of left join

        //create bean wrapper for the object class
        BeanWrapperImpl wr = new BeanWrapperImpl(objectClass); //already caches class introspection (CachedIntrospectionResults.forClass())
        wr.setPropertyValue("id", id); //set the id property
        Object object = wr.getWrappedInstance();
        boolean map = true;

        //check if this object exists in the parent list (since SQL joins are cartesian products, do not create new object if this row is just the same as previous)
        for (Iterator it = parentList.iterator(); it.hasNext();) {
            Object objectInList = (Object) it.next();
            if (objectIdEquals(objectInList, id)) {
                wr.setWrappedInstance(objectInList); //already exists in the list, use that instance
                map = false; // and do not map again
                break;
            }
        }
        if (map)
            parentList.add(object); //could not find in the parent list, add the new object

        PropertyDescriptor[] pdArr = wr.getPropertyDescriptors();
        for (int i = 0; i < pdArr.length; i++) {
            PropertyDescriptor pd = pdArr[i];
            Class fieldClass = pd.getPropertyType(); //field class
            String fieldName = Convert.toDB(pd.getName()); //field name
            Object fieldValue = wr.getPropertyValue(pd.getName());
            String columnName = tableName + "_" + fieldName;

            //database class (primitive property)
            if (map && dbClasses.contains(fieldClass)) {
                if (columns.contains(columnName)) {
                    if (debug)
                        System.out.println(">>field is found: " + columnName);
                    wr.setPropertyValue(pd.getName(), rs.getObject(columnName));
                } else {
                    if (debug)
                        System.out.println("--field not found: " + columnName);
                }
                continue; //if this is a primitive property, it cannot be an object or list
            }

            //many to one association (object property)
            if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) {
                if (columns.contains(columnName + "_id")) {
                    if (debug)
                        System.out.println(">>object is found " + columnName);
                    List list = new ArrayList(1); //we know there will be single result
                    if (!map)
                        list.add(fieldValue); //otherwise we cannot catch one to many assc. (lists) of many to one (object) assc.
                    mapRecursively(rs, columns, columnName, fieldClass, list);
                    if (list.size() > 0)
                        wr.setPropertyValue(pd.getName(), list.get(0));
                } else {
                    if (debug)
                        System.out.println("--object not found: " + columnName);
                }
            }

            //one to many association (list property)
            if (fieldValue instanceof List) { //Note: here recurring row's list property is mapped and add to parent's list
                if (columns.contains(columnName + "_id")) {
                    Class elementClass = VenList.findElementClass((List) fieldValue);
                    if (debug)
                        System.out.println(">>list is found " + columnName);
                    mapRecursively(rs, columns, columnName, elementClass, (List) fieldValue);
                } else {
                    if (debug)
                        System.out.println("--list not found: " + columnName);
                }
            }
        }
    } catch (Exception ex) {
        System.out.println("Ven - error while mapping row, table: " + tableName + " object class: "
                + objectClass + " error: " + ex.getMessage());
        if (debug) {
            ex.printStackTrace();
        }
    }
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * Converts a JavaBean to a collection of properties
 * /*from w w  w.  j a  va 2s  .c o m*/
 * @param bean The JavaBean to convert
 * @return A map of properties
 */
public Map<String, Object> convertBeanToProperties(Object bean) throws IntrospectionException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Map<String, Object> properties = new HashMap<String, Object>();
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
    for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) {
        String name = p.getName();
        Method reader = p.getReadMethod();
        if (reader != null) {
            Object value = reader.invoke(bean);
            if (null != value) {
                if (value instanceof Timestamp) {
                    properties.put(name, value.toString());
                } else if (isBean(value.getClass())) {
                    if (value.getClass().isArray()) {
                        Object[] valueArray = (Object[]) value;
                        if (valueArray.length == 0) {
                            properties.put(name, null);
                        } else {
                            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                            for (Object object : (Object[]) value) {
                                list.add(convertBeanToProperties(object));
                            }
                            properties.put(name, list.toArray(new Map[0]));
                        }
                    } else {
                        properties.put(name, convertBeanToProperties(value));
                    }
                } else {
                    properties.put(name, value);
                }
            }
        }
    }
    return properties;
}

From source file:com.panemu.tiwulfx.control.LookupFieldController.java

/**
 * Show lookup dialog.//from   w w w . j av a 2  s  . c o  m
 *
 * @param stage parent
 * @param initialValue this value will be returned if user clik the close
 * button instead of double clicking a row or click Select button
 * @param propertyName propertyName corresponds to searchCriteria
 * @param searchCriteria searchCriteria (nullable)
 * @return selected object or the initialValue
 */
public T show(final Window stage, T initialValue, String propertyName, String searchCriteria) {
    if (dialogStage == null) {
        PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(recordClass);
        lookupWindow = new LookupWindow();
        for (String clm : getColumns()) {
            for (PropertyDescriptor prop : props) {
                if (prop.getName().equals(clm)) {
                    Class type = prop.getPropertyType();
                    if (type.equals(Boolean.class)) {
                        lookupWindow.table.addColumn(new CheckBoxColumn<T>(clm));
                    } else if (type.equals(String.class)) {
                        lookupWindow.table.addColumn(new TextColumn<T>(clm));
                    } else if (type.equals(Date.class)) {
                        lookupWindow.table.addColumn(new LocalDateColumn<T>(clm));
                    } else if (Number.class.isAssignableFrom(type)) {

                        if (Long.class.isAssignableFrom(type)) {
                            lookupWindow.table.addColumn(new NumberColumn<T, Long>(clm, type));
                        } else {
                            lookupWindow.table.addColumn(new NumberColumn<T, Double>(clm, type));
                        }
                    } else {
                        TableColumn column = new TableColumn();
                        column.setCellValueFactory(new PropertyValueFactory(clm));
                        lookupWindow.table.addColumn(column);
                    }
                    break;
                }
            }

        }
        dialogStage = new Stage();
        if (stage instanceof Stage) {
            dialogStage.initOwner(stage);
            dialogStage.initModality(Modality.WINDOW_MODAL);
        } else {
            dialogStage.initOwner(null);
            dialogStage.initModality(Modality.APPLICATION_MODAL);
        }
        dialogStage.initStyle(StageStyle.UTILITY);
        dialogStage.setResizable(true);
        dialogStage.setScene(new Scene(lookupWindow));
        dialogStage.getIcons().add(new Image(
                LookupFieldController.class.getResourceAsStream("/com/panemu/tiwulfx/res/image/lookup.png")));
        dialogStage.setTitle(getWindowTitle());
        dialogStage.getScene().getStylesheets()
                .add(getClass().getResource("/com/panemu/tiwulfx/res/tiwulfx.css").toExternalForm());
        initCallback(lookupWindow, lookupWindow.table);
    }

    for (TableColumn column : lookupWindow.table.getTableView().getColumns()) {
        if (column instanceof BaseColumn && ((BaseColumn) column).getPropertyName().equals(propertyName)) {
            if (searchCriteria != null && !searchCriteria.isEmpty()) {
                TableCriteria tc = new TableCriteria(propertyName, TableCriteria.Operator.ilike_anywhere,
                        searchCriteria);
                ((BaseColumn) column).setTableCriteria(tc);
            } else {
                ((BaseColumn) column).setTableCriteria(null);
            }

            break;
        }
    }
    selectedValue = initialValue;
    beforeShowCallback(lookupWindow.table);
    lookupWindow.table.reloadFirstPage();

    if (stage != null) {
        /**
         * Since we support multiple monitors, ensure that the stage is
         * located in the center of parent stage. But we don't know the
         * dimension of the stage for the calculation, so we defer the
         * relocation after the stage is actually displayed.
         */
        Runnable runnable = new Runnable() {
            public void run() {
                dialogStage.setX(stage.getX() + stage.getWidth() / 2 - dialogStage.getWidth() / 2);
                dialogStage.setY(stage.getY() + stage.getHeight() / 2 - dialogStage.getHeight() / 2);

                //set the opacity back to fully opaque
                dialogStage.setOpacity(1);
            }
        };

        Platform.runLater(runnable);

        //set the opacity to 0 to minimize flicker effect
        dialogStage.setOpacity(0);
    }

    dialogStage.showAndWait();
    return selectedValue;
}

From source file:com.avanza.ymer.MongoQueryFactory.java

/**
 * @param template Template object// w w w. j ava  2s .c  o m
 * @return A Spring mongo {@link Query}
 */
public Query createMongoQueryFromTemplate(Object template) {
    try {
        Criteria criteria = null;
        BasicMongoPersistentEntity<?> pe = mongoMappingContext.getPersistentEntity(template.getClass());
        for (PropertyDescriptor pd : getTemplatablePropertyDescriptors(template.getClass())) {
            Object objectValue = pd.getReadMethod().invoke(template);
            if (objectValue == null) {
                continue; // null == accept any value
            }

            String fieldName = pe.getPersistentProperty(pd.getName()).getFieldName();
            Object mongoValue = mongoConverter.convertToMongoType(objectValue);
            criteria = addCriteria(criteria, fieldName, mongoValue);
        }

        return criteria != null ? new Query(criteria) : new Query();
    } catch (Exception e) {
        throw new CouldNotCreateMongoQueryException(e);
    }
}

From source file:org.apache.james.container.spring.lifecycle.osgi.AbstractOSGIAnnotationBeanPostProcessor.java

@Override
@SuppressWarnings("rawtypes")
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        A s = hasAnnotatedProperty(pd);//from   w w w.  j a v a  2  s.  c  o  m
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that
                // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setCardinality(importer, Cardinality.C_0__1);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}

From source file:com.urbanmania.spring.beans.factory.config.annotations.PropertyAnnotationAndPlaceholderConfigurer.java

private void processAnnotatedProperties(Properties properties, String name, MutablePropertyValues mpv,
        Class<?> clazz) {// w  w  w  .  ja v  a 2  s  . c  o  m
    // TODO support proxies
    if (clazz != null && clazz.getPackage() != null) {
        if (basePackage != null && !clazz.getPackage().getName().startsWith(basePackage)) {
            return;
        }

        log.info("Configuring properties for bean=" + name + "[" + clazz + "]");

        for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
            if (log.isLoggable(Level.FINE))
                log.fine("examining property=[" + clazz.getName() + "." + property.getName() + "]");
            Method setter = property.getWriteMethod();
            Method getter = property.getReadMethod();
            Property annotation = null;
            if (setter != null && setter.isAnnotationPresent(Property.class)) {
                annotation = setter.getAnnotation(Property.class);
            } else if (setter != null && getter != null && getter.isAnnotationPresent(Property.class)) {
                annotation = getter.getAnnotation(Property.class);
            } else if (setter == null && getter != null && getter.isAnnotationPresent(Property.class)) {
                throwBeanConfigurationException(clazz, property.getName());
            }
            if (annotation != null) {
                setProperty(properties, name, mpv, clazz, property, annotation);
            }
        }

        for (Field field : clazz.getDeclaredFields()) {
            if (log.isLoggable(Level.FINE))
                log.fine("examining field=[" + clazz.getName() + "." + field.getName() + "]");
            if (field.isAnnotationPresent(Property.class)) {
                Property annotation = field.getAnnotation(Property.class);
                PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

                if (property == null || property.getWriteMethod() == null) {
                    throwBeanConfigurationException(clazz, field.getName());
                }

                setProperty(properties, name, mpv, clazz, property, annotation);
            }
        }
    }
}