Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

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

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

Gets the method that should be used to read the property value.

Usage

From source file:org.obiba.onyx.jade.instrument.gehealthcare.CardiosoftInstrumentRunner.java

/**
 * Place the results and xml and pdf files into a map object to send them to the server for persistence
 * @param resultParser//from w ww . j  a v  a2s  .  c o m
 * @throws Exception
 */
public void sendDataToServer(CardiosoftInstrumentResultParser resultParser) {
    Map<String, Data> outputToSend = new HashMap<String, Data>();

    try {
        for (PropertyDescriptor pd : Introspector.getBeanInfo(CardiosoftInstrumentResultParser.class)
                .getPropertyDescriptors()) {
            if (!pd.getName().equalsIgnoreCase("doc") && !pd.getName().equalsIgnoreCase("xpath")
                    && !pd.getName().equalsIgnoreCase("xmldocument")
                    && !pd.getName().equalsIgnoreCase("class")) {
                Object value = pd.getReadMethod().invoke(resultParser);
                if (value != null) {
                    if (value instanceof Long) {

                        // We need to subtract one to the birthday month since the month of January is represented by "0" in
                        // java.util.Calendar (January is represented by "1" in Cardiosoft).
                        if (pd.getName().equals("participantBirthMonth")) {
                            outputToSend.put(pd.getName(), DataBuilder.buildInteger(((Long) value) - 1));
                        } else {
                            outputToSend.put(pd.getName(), DataBuilder.buildInteger((Long) value));
                        }

                    } else if (value instanceof Double) {
                        outputToSend.put(pd.getName(), DataBuilder.buildDecimal((Double) value));
                    } else {
                        outputToSend.put(pd.getName(), DataBuilder.buildText(value.toString()));
                    }
                } else { // send null values as well (ONYX-585)
                    log.info("Output parameter " + pd.getName() + " was null; will send null to server");

                    if (pd.getPropertyType().isAssignableFrom(Long.class)) {
                        log.info("Output parameter " + pd.getName() + " is of type INTEGER");
                        outputToSend.put(pd.getName(), new Data(DataType.INTEGER, null));
                    } else if (pd.getPropertyType().isAssignableFrom(Double.class)) {
                        log.info("Output parameter " + pd.getName() + " is of type DECIMAL");
                        outputToSend.put(pd.getName(), new Data(DataType.DECIMAL, null));
                    } else {
                        log.info("Output parameter " + pd.getName() + " is of type TEXT");
                        outputToSend.put(pd.getName(), new Data(DataType.TEXT, null));
                    }
                }
            }
        }

        // Save the xml and pdf files
        File xmlFile = new File(getExportPath(), getXmlFileName());
        outputToSend.put("xmlFile", DataBuilder.buildBinary(xmlFile));

        File pdfRestingEcgFile = new File(getExportPath(), getPdfFileNameRestingEcg());
        outputToSend.put("pdfFile", DataBuilder.buildBinary(pdfRestingEcgFile));

        File pdfFullEcgFile = new File(getExportPath(), getPdfFileNameFullEcg());
        outputToSend.put("pdfFileFull", DataBuilder.buildBinary(pdfFullEcgFile));

        instrumentExecutionService.addOutputParameterValues(outputToSend);

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

From source file:org.firebrandocm.dao.ClassMetadata.java

/**
 * Private helper that caches information for a property for further persistence consideration
 *
 * @param colAnnotation   the column annotation
 * @param propertyName    the property name
 * @param type            the property type
 * @param indexed         whether the property should be indexed in the data store
 * @param lazy            if access to this property should be loaded on demand
 * @param counter         if this property represents a counter
 * @param counterIncrease if this property represents a value for a counter arithmetic operation
 *//*  w w  w . ja v a  2s .c  o m*/
private void addProperty(Column colAnnotation, String propertyName, Class<?> type, boolean indexed,
        boolean lazy, boolean counter, boolean counterIncrease)
        throws ClassNotFoundException, IntrospectionException {
    propertiesTypesMap.put(propertyName, type);
    mutationProperties.add(propertyName);
    if (indexed) {
        indexedProperties.add(propertyName);
        log.debug(String.format("added indexed property %s", propertyName));
    }
    if (lazy) {
        PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, target);
        lazyAccesors.put(descriptor.getReadMethod(), propertyName);
        lazyProperties.add(propertyName);
    }
    if (counter) {
        counterProperties.add(propertyName);
    }
    if (!counterIncrease) {
        selectionProperties.add(propertyName);
        addColumnToColumnFamilyDefinition(colAnnotation, propertyName, indexed);
    }
    log.debug(String.format("added property %s", propertyName));
}

From source file:org.fao.geonet.api.records.formatters.groovy.template.TRenderContext.java

private Object safeGetProperty(@Nonnull Object value, String prop)
        throws InvocationTargetException, IllegalAccessException {
    prop = prop.trim();//from  w  w  w  .  j  av  a2  s.  co m
    if (prop.trim().isEmpty()) {
        throw new EmptyPropertyException();
    }
    if (value instanceof GPathResult) {
        GPathResult result = (GPathResult) value;
        if (prop.replace("\\s+", "").equals("name()")) {
            return result.name();
        }
        return result.getProperty(prop);
    }
    if (value instanceof Map) {
        Map map = (Map) value;
        return map.get(prop);
    } else if (value instanceof List) {
        List list = (List) value;
        try {
            return list.get(Integer.parseInt(prop));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("When accessing a list the property must be a number.  Property:"
                    + prop + ".  List: " + list);
        }
    } else {
        final PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(value.getClass(),
                prop.trim());
        if (propertyDescriptor == null) {
            try {
                final Field declaredField = value.getClass().getDeclaredField(prop.trim());
                declaredField.setAccessible(true);
                return declaredField.get(value);
            } catch (NoSuchFieldException e) {
                // skip
            }
            throw new NoSuchPropertyException(prop + " on object: " + value + " (" + value.getClass() + ")");
        }
        Method method = propertyDescriptor.getReadMethod();
        method.setAccessible(true);
        value = method.invoke(value);
        return value;
    }
}

From source file:org.firebrandocm.dao.ClassMeta.java

/**
     * Private helper that caches information for a property for further persistence consideration
     */*from  w  ww.j  ava 2  s .  com*/
     * @param colAnnotation   the column annotation
     * @param propertyName    the property name
     * @param type            the property type
     * @param indexed         whether the property should be indexed in the data store
     * @param lazy            if access to this property should be loaded on demand
     * @param counter         if this property represents a counter
     * @param counterIncrease if this property represents a value for a counter arithmetic operation
     */
    private void addProperty(Column colAnnotation, String propertyName, Class<?> type, boolean indexed,
            boolean lazy, boolean counter, boolean counterIncrease)
            throws ClassNotFoundException, IntrospectionException {
        propertiesTypesMap.put(propertyName, type);
        mutationProperties.add(propertyName);
        if (indexed) {
            indexedProperties.add(propertyName);
            log.debug(String.format("added indexed property %s", propertyName));
        }
        if (lazy) {
            PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, target);
            lazyAccesors.put(descriptor.getReadMethod(), propertyName);
            lazyProperties.add(propertyName);
        }
        if (counter) {
            counterProperties.add(propertyName);
        }
        if (!counterIncrease) {
            selectionProperties.add(propertyName);
            addColumnToColumnFamilyDefinition(colAnnotation, propertyName, indexed);
        }
        log.debug(String.format("added property %s", propertyName));
    }

From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java

protected List<AutoChildTemplate> getChildTemplates(RuleTemplate ruleTemplate, TypeInfo typeInfo,
        XmlNodeInfo xmlNodeInfo, InitializerContext initializerContext) throws Exception {
    List<AutoChildTemplate> childTemplates = new ArrayList<AutoChildTemplate>();
    if (xmlNodeInfo != null) {
        for (XmlSubNode xmlSubNode : xmlNodeInfo.getSubNodes()) {
            TypeInfo propertyTypeInfo = TypeInfo.parse(xmlSubNode.propertyType());
            List<AutoChildTemplate> childRulesBySubNode = getChildTemplatesBySubNode(ruleTemplate, typeInfo,
                    xmlSubNode.propertyName(), xmlSubNode, propertyTypeInfo, initializerContext);
            if (childRulesBySubNode != null) {
                childTemplates.addAll(childRulesBySubNode);
            }/*from w w w  .ja v  a2  s.  c  o  m*/
        }
    }

    Class<?> type = typeInfo.getType();
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null) {
            if (readMethod.getDeclaringClass() != type) {
                try {
                    readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    continue;
                }
            }

            List<AutoChildTemplate> childTemplatesBySubNode = null;
            XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class);
            if (xmlSubNode != null) {
                TypeInfo propertyTypeInfo;
                Class<?> propertyType = propertyDescriptor.getPropertyType();
                if (Collection.class.isAssignableFrom(propertyType)) {
                    propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(),
                            true);
                    propertyType = propertyTypeInfo.getType();
                } else {
                    propertyTypeInfo = new TypeInfo(propertyType, false);
                }

                childTemplatesBySubNode = getChildTemplatesBySubNode(ruleTemplate, typeInfo,
                        propertyDescriptor.getName(), xmlSubNode, propertyTypeInfo, initializerContext);
            }

            if (childTemplatesBySubNode != null) {
                IdeSubObject ideSubObject = readMethod.getAnnotation(IdeSubObject.class);
                if (ideSubObject != null && !ideSubObject.visible()) {
                    for (AutoChildTemplate childTemplate : childTemplatesBySubNode) {
                        childTemplate.setVisible(false);
                    }
                }
                childTemplates.addAll(childTemplatesBySubNode);
            }
        }
    }
    return childTemplates;
}

From source file:com.interface21.beans.BeanWrapperImpl.java

/**
 * Set an individual field./*www. j  av a2  s.  c om*/
 * All other setters go through this.
 * @param pv property value to use for update
 * @throws PropertyVetoException if a listeners throws a JavaBeans API veto
 * @throws BeansException if there's a low-level, fatal error
 */
public void setPropertyValue(PropertyValue pv) throws PropertyVetoException, BeansException {

    if (isNestedProperty(pv.getName())) {
        try {
            BeanWrapper nestedBw = getBeanWrapperForNestedProperty(pv.getName());
            nestedBw.setPropertyValue(new PropertyValue(getFinalPath(pv.getName()), pv.getValue()));
            return;
        } catch (NullValueInNestedPathException ex) {
            // Let this through
            throw ex;
        } catch (FatalBeanException ex) {
            // Error in the nested path
            throw new NotWritablePropertyException(pv.getName(), getWrappedClass());
        }
    }

    if (!isWritableProperty(pv.getName())) {
        throw new NotWritablePropertyException(pv.getName(), getWrappedClass());
    }

    PropertyDescriptor pd = getPropertyDescriptor(pv.getName());
    Method writeMethod = pd.getWriteMethod();
    Method readMethod = pd.getReadMethod();
    Object oldValue = null; // May stay null if it's not a readable property
    PropertyChangeEvent propertyChangeEvent = null;

    try {
        if (readMethod != null && eventPropagationEnabled) {
            // Can only find existing value if it's a readable property
            try {
                oldValue = readMethod.invoke(object, new Object[] {});
            } catch (Exception ex) {
                // The getter threw an exception, so we couldn't retrieve the old value.
                // We're not really interested in any exceptions at this point,
                // so we merely log the problem and leave oldValue null
                logger.warn("Failed to invoke getter '" + readMethod.getName()
                        + "' to get old property value before property change: getter probably threw an exception",
                        ex);
            }
        }

        // Old value may still be null
        propertyChangeEvent = createPropertyChangeEventWithTypeConversionIfNecessary(object, pv.getName(),
                oldValue, pv.getValue(), pd.getPropertyType());

        // May throw PropertyVetoException: if this happens the PropertyChangeSupport
        // class fires a reversion event, and we jump out of this method, meaning
        // the change was never actually made
        if (eventPropagationEnabled) {
            vetoableChangeSupport.fireVetoableChange(propertyChangeEvent);
        }

        if (pd.getPropertyType().isPrimitive() && (pv.getValue() == null || "".equals(pv.getValue()))) {
            throw new IllegalArgumentException("Invalid value [" + pv.getValue() + "] for property ["
                    + pd.getName() + "] of primitive type [" + pd.getPropertyType() + "]");
        }

        // Make the change
        if (logger.isDebugEnabled())
            logger.debug("About to invoke write method [" + writeMethod + "] on object of class '"
                    + object.getClass().getName() + "'");
        writeMethod.invoke(object, new Object[] { propertyChangeEvent.getNewValue() });
        if (logger.isDebugEnabled())
            logger.debug("Invoked write method [" + writeMethod + "] ok");

        // If we get here we've changed the property OK and can broadcast it
        if (eventPropagationEnabled)
            propertyChangeSupport.firePropertyChange(propertyChangeEvent);
    } catch (InvocationTargetException ex) {
        if (ex.getTargetException() instanceof PropertyVetoException)
            throw (PropertyVetoException) ex.getTargetException();
        if (ex.getTargetException() instanceof ClassCastException)
            throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
        throw new MethodInvocationException(ex.getTargetException(), propertyChangeEvent);
    } catch (IllegalAccessException ex) {
        throw new FatalBeanException("illegal attempt to set property [" + pv + "] threw exception", ex);
    } catch (IllegalArgumentException ex) {
        throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex);
    }
}

From source file:org.gbif.portal.registration.UDDIUtils.java

/**
 * Creates a Provider detail from the business defined by the given key
 * /*from  w  w  w.  j a v  a2 s. c  o m*/
 * A username is provided so that the primary user is not added to the 
 * secondary contacts list.
 * 
 * @param uuid To get the business for
 * @param primaryContactName To NOT add to the secondary contacts      
 * @return The provider details for the given business or null
 * @throws TransportException On comms error
 * @throws UDDIException On corrupt data, or invalid key
 */
@SuppressWarnings("unchecked")
public ProviderDetail createProviderFromUDDI(String uuid, String primaryContactName)
        throws UDDIException, TransportException {
    BusinessDetail detail = getUddiProxy().get_businessDetail(uuid);
    Vector businessEntityVector = detail.getBusinessEntityVector();
    BusinessEntity business = (BusinessEntity) businessEntityVector.get(0);
    ProviderDetail provider = new ProviderDetail();
    provider.setBusinessKey(business.getBusinessKey());
    provider.setBusinessName(business.getDefaultNameString());
    provider.setBusinessDescription(business.getDefaultDescriptionString());
    CategoryBag metadata = business.getCategoryBag();
    Vector keyedMetadata = metadata.getKeyedReferenceVector();
    for (int i = 0; i < keyedMetadata.size(); i++) {
        KeyedReference kr = (KeyedReference) keyedMetadata.get(i);
        if (CATEGORY_BAG_KEY_COUNTRY.equals(kr.getKeyName())) {
            provider.setBusinessCountry(kr.getKeyValue());
        } else if (CATEGORY_BAG_KEY_LOGO_URL.equals(kr.getKeyName())) {
            provider.setBusinessLogoURL(kr.getKeyValue());
        }
    }
    //initialise the primary contact
    Contacts contacts = business.getContacts();
    if (contacts.size() > 0) {
        Contact uddiContact = contacts.get(0);
        ProviderDetail.Contact primaryContact = provider.getBusinessPrimaryContact();
        setContactDetailsFromUDDI(uddiContact, primaryContact);
    }

    addSecondaryContactsToModel(primaryContactName, business, provider);

    // add the resource data
    Vector names = new Vector();
    names.add(new Name("%"));
    ServiceList serviceList = getUddiProxy().find_service(uuid, names, null, null, null, 10000);
    if (serviceList != null) {
        ServiceInfos serviceInfos = serviceList.getServiceInfos();
        if (serviceInfos.size() > 0) {
            Vector<ServiceInfo> serviceInfosVector = serviceInfos.getServiceInfoVector();
            for (ServiceInfo serviceInfo : serviceInfosVector) {

                ServiceDetail serviceDetail = getUddiProxy().get_serviceDetail(serviceInfo.getServiceKey());
                Vector<BusinessService> businessServiceVector = serviceDetail.getBusinessServiceVector();
                // there should only be one but...
                for (BusinessService bs : businessServiceVector) {
                    logger.info("Adding a resource");
                    ResourceDetail resource = new ResourceDetail();
                    resource.setName(bs.getDefaultNameString());
                    resource.setServiceKey(bs.getServiceKey());
                    resource.setDescription(bs.getDefaultDescriptionString());

                    BindingTemplates bindingTemplates = bs.getBindingTemplates();
                    if (bindingTemplates != null && bindingTemplates.size() > 0) {
                        BindingTemplate bt = bindingTemplates.get(0);
                        AccessPoint ap = bt.getAccessPoint();
                        if (ap != null) {
                            resource.setAccessPoint(ap.getText());
                            resource.setResourceType(bt.getDefaultDescriptionString());
                        }
                    }

                    CategoryBag cb = bs.getCategoryBag();
                    if (cb != null) {
                        Vector<KeyedReference> keyedReferences = cb.getKeyedReferenceVector();
                        for (KeyedReference kr : keyedReferences) {
                            try {
                                PropertyDescriptor pd = org.springframework.beans.BeanUtils
                                        .getPropertyDescriptor(ResourceDetail.class, kr.getKeyName());
                                if (pd != null) {
                                    Object theProperty = (Object) pd.getReadMethod().invoke(resource,
                                            (Object[]) null);
                                    logger.debug(pd.getClass());
                                    if (theProperty instanceof List) {
                                        List propertyList = (List) theProperty;
                                        if (propertyList != null) {
                                            propertyList.add(kr.getKeyValue());
                                        }
                                    } else if (pd.getPropertyType().equals(Date.class)) {
                                        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
                                        try {
                                            Date theDate = sdf.parse(kr.getKeyValue());
                                            BeanUtils.setProperty(resource, kr.getKeyName(), theDate);
                                        } catch (Exception e) {
                                            logger.debug(e.getMessage(), e);
                                        }
                                    } else {
                                        BeanUtils.setProperty(resource, kr.getKeyName(), kr.getKeyValue());
                                    }
                                }
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                    provider.getBusinessResources().add(resource);
                }
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Provider detail retrieved: " + provider);
    }
    return provider;
}

From source file:com.wavemaker.runtime.data.util.QueryHandler.java

private Object cloneObject(Object oldObj, Object newObj, Class cls) {
    PropertyDescriptor[] beanProps;
    try {/*from w w  w .ja va 2  s.  co m*/
        beanProps = Introspector.getBeanInfo(cls).getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : beanProps) {
            if (propertyDescriptor.getName().equals("class")) {
                continue;
            }
            Method getter = propertyDescriptor.getReadMethod();
            Method setter = propertyDescriptor.getWriteMethod();
            Object val = getter.invoke(oldObj);
            setter.invoke(newObj, val);
        }
    } catch (Exception ex) {
        throw new WMRuntimeException(ex);
    }

    return newObj;
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors.// ww  w.  j a va 2 s .co m
 * 
 * <p>
 * The returned XML will be a single element with all JavaBean properties
 * turned into attributes. For example:
 * <p>
 * 
 * <pre>
 * &lt;powerDatum
 *   id="123"
 *   pvVolts="123.123"
 *   ... /&gt;
 * </pre>
 * 
 * <p>
 * {@link PropertyEditor} instances can be registered with the supplied
 * {@link BeanWrapper} for custom handling of properties, e.g. dates.
 * </p>
 * 
 * @param bean
 *        the object to turn into XML
 * @param elementName
 *        the name of the XML element
 * @return the element, as an XML DOM Element
 */
protected Element getElement(BeanWrapper bean, String elementName, Document dom) {
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    Element root = null;
    root = dom.createElement(elementName);
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor prop = props[i];
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }
        Object propValue = null;
        PropertyEditor editor = bean.findCustomEditor(prop.getPropertyType(), prop.getName());
        if (editor != null) {
            editor.setValue(bean.getPropertyValue(propName));
            propValue = editor.getAsText();
        } else {
            propValue = bean.getPropertyValue(propName);
        }
        if (propValue == null) {
            continue;
        }
        if (log.isTraceEnabled()) {
            log.trace("attribute name: " + propName + " attribute value: " + propValue);
        }
        root.setAttribute(propName, propValue.toString());
    }
    return root;
}

From source file:org.grails.datastore.mapping.reflect.ClassPropertyFetcher.java

private void init() {

    List<Class> allClasses = resolveAllClasses(clazz);
    for (Class c : allClasses) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            processField(field);//from w  w w . j av a2s .c  om
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            processMethod(method);
        }
    }

    try {
        propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
    } catch (IntrospectionException e) {
        // ignore
    }

    if (propertyDescriptors == null) {
        return;
    }

    for (PropertyDescriptor desc : propertyDescriptors) {
        propertyDescriptorsByName.put(desc.getName(), desc);
        final Class<?> propertyType = desc.getPropertyType();
        if (propertyType == null)
            continue;
        List<PropertyDescriptor> pds = typeToPropertyMap.get(propertyType);
        if (pds == null) {
            pds = new ArrayList<PropertyDescriptor>();
            typeToPropertyMap.put(propertyType, pds);
        }
        pds.add(desc);

        Method readMethod = desc.getReadMethod();
        if (readMethod != null) {
            boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers());
            if (staticReadMethod) {
                List<PropertyFetcher> propertyFetchers = staticFetchers.get(desc.getName());
                if (propertyFetchers == null) {
                    staticFetchers.put(desc.getName(), propertyFetchers = new ArrayList<PropertyFetcher>());
                }
                propertyFetchers.add(new GetterPropertyFetcher(readMethod, true));
            } else {
                instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, false));
            }
        }
    }
}