Example usage for java.beans BeanInfo getPropertyDescriptors

List of usage examples for java.beans BeanInfo getPropertyDescriptors

Introduction

In this page you can find the example usage for java.beans BeanInfo getPropertyDescriptors.

Prototype

PropertyDescriptor[] getPropertyDescriptors();

Source Link

Document

Returns descriptors for all properties of the bean.

Usage

From source file:com.manydesigns.elements.reflection.JavaClassAccessor.java

protected List<PropertyAccessor> setupPropertyAccessors() {
    List<PropertyAccessor> accessorList = new ArrayList<PropertyAccessor>();

    // handle properties through introspection
    try {//from   w  ww. ja va 2 s .  co m
        BeanInfo beanInfo = Introspector.getBeanInfo(javaClass);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor current : propertyDescriptors) {
            accessorList.add(new JavaPropertyAccessor(current));
        }
    } catch (IntrospectionException e) {
        logger.error(e.getMessage(), e);
    }

    // handle public fields
    for (Field field : javaClass.getFields()) {
        if (isPropertyPresent(accessorList, field.getName())) {
            continue;
        }
        accessorList.add(new JavaFieldAccessor(field));
    }

    return accessorList;
}

From source file:com.twinsoft.convertigo.engine.admin.services.database_objects.Set.java

protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    Element root = document.getDocumentElement();
    Document post = null;/*  ww  w .ja  v a  2s.c  om*/
    Element response = document.createElement("response");

    try {
        Map<String, DatabaseObject> map = com.twinsoft.convertigo.engine.admin.services.projects.Get
                .getDatabaseObjectByQName(request);

        xpath = new TwsCachedXPathAPI();
        post = XMLUtils.parseDOM(request.getInputStream());
        postElt = document.importNode(post.getFirstChild(), true);

        String objectQName = xpath.selectSingleNode(postElt, "./@qname").getNodeValue();
        DatabaseObject object = map.get(objectQName);

        //         String comment = getPropertyValue(object, "comment").toString();
        //         object.setComment(comment);

        if (object instanceof Project) {
            Project project = (Project) object;

            String objectNewName = getPropertyValue(object, "name").toString();

            Engine.theApp.databaseObjectsManager.renameProject(project, objectNewName);

            map.remove(objectQName);
            map.put(project.getQName(), project);
        }

        BeanInfo bi = CachedIntrospector.getBeanInfo(object.getClass());

        PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors();

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();

            Method setter = propertyDescriptor.getWriteMethod();

            Class<?> propertyTypeClass = propertyDescriptor.getReadMethod().getReturnType();
            if (propertyTypeClass.isPrimitive()) {
                propertyTypeClass = ClassUtils.primitiveToWrapper(propertyTypeClass);
            }

            try {
                String propertyValue = getPropertyValue(object, propertyName).toString();

                Object oPropertyValue = createObject(propertyTypeClass, propertyValue);

                if (object.isCipheredProperty(propertyName)) {

                    Method getter = propertyDescriptor.getReadMethod();
                    String initialValue = (String) getter.invoke(object, (Object[]) null);

                    if (oPropertyValue.equals(initialValue)
                            || DatabaseObject.encryptPropertyValue(initialValue).equals(oPropertyValue)) {
                        oPropertyValue = initialValue;
                    } else {
                        object.hasChanged = true;
                    }
                }

                if (oPropertyValue != null) {
                    Object args[] = { oPropertyValue };
                    setter.invoke(object, args);
                }

            } catch (IllegalArgumentException e) {
            }
        }

        Engine.theApp.databaseObjectsManager.exportProject(object.getProject());
        response.setAttribute("state", "success");
        response.setAttribute("message", "Project have been successfully updated!");
    } catch (Exception e) {
        Engine.logAdmin.error("Error during saving the properties!\n" + e.getMessage());
        response.setAttribute("state", "error");
        response.setAttribute("message", "Error during saving the properties!");
        Element stackTrace = document.createElement("stackTrace");
        stackTrace.setTextContent(e.getMessage());
        root.appendChild(stackTrace);
    } finally {
        xpath.resetCache();
    }

    root.appendChild(response);
}

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 {/*w  ww. ja va 2  s . c o  m*/
        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:org.bibsonomy.database.validation.DatabaseModelValidator.java

/**
 * checks if the string attributes of the model respect the field lengths of
 * the database/*from   w  w  w. jav a  2s  . c  om*/
 * 
 * @param model    the model to validate
 * @param id       the id of the model (used for the errormessage)
 * @param session   the session
 */
public void validateFieldLength(final T model, final String id, final DBSession session) {
    final Class<? extends Object> clazz = model.getClass();
    final FieldLengthErrorMessage fieldLengthError = new FieldLengthErrorMessage();
    try {
        final BeanInfo bi = Introspector.getBeanInfo(clazz);

        /*
         * loop through all properties
         * if there are any performance issues, their cause might be here
         */
        for (final PropertyDescriptor d : bi.getPropertyDescriptors()) {
            final Method getter = d.getReadMethod();

            if (present(getter)) {
                final Object value = getter.invoke(model, (Object[]) null);

                /*
                 * check max length
                 */
                if (value instanceof String) {
                    final String stringValue = (String) value;

                    final int length = stringValue.length();
                    final String propertyName = d.getName();
                    final int maxLength = DatabaseSchemaInformation.getInstance()
                            .getMaxColumnLengthForProperty(clazz, propertyName);

                    if ((maxLength > 0) && (length > maxLength)) {
                        fieldLengthError.addToFields(propertyName, maxLength);
                    }
                }
            }
        }

        if (fieldLengthError.hasErrors()) {
            session.addError(id, fieldLengthError);
            log.warn("Added fieldlengthError");
        }
    } catch (final Exception ex) {
        log.error("could not introspect object of class 'user'", ex);
    }
}

From source file:egovframework.com.ext.ldapumt.service.impl.ObjectMapper.java

/**
 * ContextAdapter?  ? vo ./*from  w  w  w  .  ja v a  2s.c  o  m*/
 */
public Object mapFromContext(Object arg0) throws NamingException {
    DirContextAdapter adapter = (DirContextAdapter) arg0;
    Attributes attrs = adapter.getAttributes();

    LdapObject vo = null;

    try {
        vo = (LdapObject) type.newInstance();
    } catch (Exception e2) {
        throw new RuntimeException(e2);
    }

    vo.setDn(adapter.getDn().toString());

    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(type);
    } catch (IntrospectionException e1) {
        throw new RuntimeException(e1);
    }

    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

    for (PropertyDescriptor descriptor : propertyDescriptors) {
        if (attrs.get(descriptor.getName()) != null)
            try {
                Class<?> o = descriptor.getPropertyType();
                if (o == int.class)
                    PropertyUtils.setProperty(vo, descriptor.getName(),
                            Integer.valueOf((String) attrs.get(descriptor.getName()).get()));
                if (o == String.class)
                    PropertyUtils.setProperty(vo, descriptor.getName(),
                            (String) attrs.get(descriptor.getName()).get());
                if (o == Boolean.class)
                    PropertyUtils.setProperty(vo, descriptor.getName(),
                            ((String) attrs.get(descriptor.getName()).get()).equals("Y"));

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
    }

    return vo;
}

From source file:org.fhcrc.cpl.toolbox.datastructure.BoundMap.java

private void initialize(Class beanClass) {
    synchronized (_savedPropertyMaps) {
        HashMap<String, BoundProperty> props = _savedPropertyMaps.get(beanClass);
        if (props == null) {
            try {
                props = new HashMap<String, BoundProperty>();
                BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                if (propertyDescriptors != null) {
                    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                        if (propertyDescriptor != null) {
                            String name = propertyDescriptor.getName();
                            if ("class".equals(name))
                                continue;
                            Method readMethod = propertyDescriptor.getReadMethod();
                            Method writeMethod = propertyDescriptor.getWriteMethod();
                            Class aType = propertyDescriptor.getPropertyType();
                            props.put(name, new BoundProperty(readMethod, writeMethod, aType));
                        }/*from  w ww.j a v  a  2s. c  o  m*/
                    }
                }
            } catch (IntrospectionException e) {
                Logger.getLogger(this.getClass()).error("error creating BoundMap", e);
                throw new RuntimeException(e);
            }
            _savedPropertyMaps.put(beanClass, props);
        }
        _properties = props;
    }
}

From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSWebFaultHandler.java

@Override
protected Object getFaultBean(Throwable fault, MessagePartInfo faultPart, MessageContext context) {
    Class<? extends Throwable> faultClass = fault.getClass();

    boolean conformsToJAXWSFaultPattern = conformsToJAXWSFaultPattern(faultClass);
    if (conformsToJAXWSFaultPattern) {
        try {//from www.ja  v  a 2  s .  c om
            return faultClass.getMethod("getFaultInfo").invoke(fault);
        } catch (NoSuchMethodException e) {
            //fall through.  doesn't conform to the spec pattern.
        } catch (IllegalAccessException e) {
            throw new XFireRuntimeException("Couldn't invoke getFaultInfo method.", e);
        } catch (InvocationTargetException e) {
            throw new XFireRuntimeException("Couldn't invoke getFaultInfo method.", e);
        }
    }

    //doesn't conform to the spec pattern, use the generated fault bean class.
    Class faultBeanClass = getFaultBeanClass(faultClass);

    if (faultBeanClass == null) {
        return null;
    }

    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(faultBeanClass, Object.class);
        Object faultBean = faultBeanClass.newInstance();
        for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
            if ((property.getWriteMethod() != null) && (property.getReadMethod() != null)) {
                Method getter = faultClass.getMethod(property.getReadMethod().getName());
                property.getWriteMethod().invoke(faultBean, getter.invoke(fault));
            }
        }
        return faultBean;
    } catch (IntrospectionException e) {
        throw new XFireRuntimeException("Unable to introspect fault bean class.", e);
    } catch (IllegalAccessException e) {
        throw new XFireRuntimeException("Unable to create fault bean.", e);
    } catch (InstantiationException e) {
        throw new XFireRuntimeException("Unable to create fault bean.", e);
    } catch (NoSuchMethodException e) {
        throw new XFireRuntimeException("The fault " + faultClass.getName()
                + " doesn't have a needed getter method used to fill in its fault bean.", e);
    } catch (InvocationTargetException e) {
        throw new XFireRuntimeException("Unable to create fault bean.", e);
    }
}

From source file:org.snaker.engine.access.jdbc.BeanPropertyHandler.java

/**
 * IntrospectorBeanInfo????PropertyDescriptor[]
 * @param c//from  w  w  w . jav  a  2  s.  c om
 * @return PropertyDescriptor[]
 * @throws SQLException
 */
private PropertyDescriptor[] propertyDescriptors(Class<?> c) throws SQLException {
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(c);
    } catch (IntrospectionException e) {
        throw new SQLException("Bean introspection failed: " + e.getMessage());
    }

    return beanInfo.getPropertyDescriptors();
}

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

/**
 * Display the properties of this JavaBean in XML format.
 *
 * @param source Javabean who's contents should be printed
 * @return XML formatted string of this beans properties and their values
 *//*from w w w .j  a v  a 2s . co m*/
public static String printXMLGraph(Object source) {

    StringBuffer out = new StringBuffer();
    out.append("<" + source.getClass().getSimpleName() + ">");

    try {
        BeanInfo sInfo = Introspector.getBeanInfo(source.getClass());
        PropertyDescriptor[] sDescriptors = sInfo.getPropertyDescriptors();
        if (sDescriptors != null && sDescriptors.length != 0) {
            for (int i = 0; i < sDescriptors.length; i++) {
                PropertyDescriptor sDesc = sDescriptors[i];
                Method sm = sDesc.getReadMethod();
                if (sm != null && sDesc.getWriteMethod() != null) {
                    if (!sm.isAccessible())
                        sm.setAccessible(true);
                    Object sValue = sm.invoke(source, (Object[]) null);

                    out.append("<" + sDesc.getName() + ">");

                    if (sValue != null && !sm.getReturnType().isArray()
                            && !GraphDataObject.class.isAssignableFrom(sValue.getClass())) {
                        out.append(sValue.toString().trim());
                    }
                    out.append("</" + sDesc.getName() + ">");
                }
            }
        }
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, "???", e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    } catch (InvocationTargetException e) {
        TransformException me = new TransformException(TransformException.INVOCATION_ERROR, "???", e);
        log.error(me.getLocalizedMessage(), me.getCause());
        //throw me;
    } catch (IntrospectionException e) {
        TransformException me = new TransformException(TransformException.INTROSPECT_ERROR, "???",
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    }
    out.append("</" + source.getClass().getSimpleName() + ">");
    return out.toString();
}

From source file:be.fgov.kszbcss.rhq.websphere.component.jdbc.db2.pool.ConnectionContextImpl.java

ConnectionContextImpl(Map<String, Object> properties) {
    dataSource = new DB2SimpleDataSource();
    BeanInfo beanInfo;
    try {//from  w  w w.  j  av a  2 s  .c  om
        beanInfo = Introspector.getBeanInfo(DB2SimpleDataSource.class);
    } catch (IntrospectionException ex) {
        throw new Error(ex);
    }
    for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
        String name = descriptor.getName();
        if (properties.containsKey(name)) {
            Object value = properties.get(name);
            Class<?> propertyType = descriptor.getPropertyType();
            if (log.isDebugEnabled()) {
                log.debug("Setting property " + name + ": propertyType=" + propertyType.getName() + ", value="
                        + value + " (class=" + (value == null ? "<N/A>" : value.getClass().getName()) + ")");
            }
            if (propertyType != String.class && value instanceof String) {
                // Need to convert value to correct type
                if (propertyType == Integer.class || propertyType == Integer.TYPE) {
                    value = Integer.valueOf((String) value);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Converted value to " + value + " (class=" + value.getClass().getName() + ")");
                }
            }
            try {
                descriptor.getWriteMethod().invoke(dataSource, value);
            } catch (IllegalArgumentException ex) {
                throw new RuntimeException("Failed to set '" + name + "' property", ex);
            } catch (IllegalAccessException ex) {
                throw new IllegalAccessError(ex.getMessage());
            } catch (InvocationTargetException ex) {
                Throwable cause = ex.getCause();
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                } else if (cause instanceof Error) {
                    throw (Error) cause;
                } else {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
}