Example usage for java.beans PropertyDescriptor getPropertyType

List of usage examples for java.beans PropertyDescriptor getPropertyType

Introduction

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

Prototype

public synchronized Class<?> getPropertyType() 

Source Link

Document

Returns the Java type info for the property.

Usage

From source file:edu.harvard.med.screensaver.model.AbstractEntity.java

/**
 * Determine if a given property should be used in determining equivalence.
 * // w w w .  j  av  a 2s  .co m
 * @return boolean (see code, since this is private method)
 * @see #isEquivalent(AbstractEntity)
 */
// TODO: can we annotate a bean's properties with "@equivalence" and do some
// introspection to retrieve these annotated "equivalence" properties, rather
// than relying upon the below heuristics?
private boolean isEquivalenceProperty(PropertyDescriptor property) {
    Method method = property.getReadMethod();
    if (method == null) {
        // this can occur if there is a public setter method, but a non-public
        // getter method
        log.debug("no corresponding getter method for property " + property.getDisplayName());
        return false;
    }
    // only test methods that are declared by subclasses of AbstractEntity
    if (method.getDeclaringClass().equals(AbstractEntity.class)
            || !AbstractEntity.class.isAssignableFrom(method.getDeclaringClass())) {
        return false;
    }
    if (method.getAnnotation(Transient.class) != null) {
        return false;
    }
    if (method.getAnnotation(Column.class) != null
            && method.getAnnotation(Column.class).isNotEquivalenceProperty()) {
        return false;
    }
    // do not check embeddable types (as this would require descending into the embeddable to check equivalence)
    if (property.getPropertyType().getAnnotation(Embeddable.class) != null) {
        return false;
    }

    return !(Collection.class.isAssignableFrom(property.getPropertyType())
            || Map.class.isAssignableFrom(property.getPropertyType())
            || AbstractEntity.class.isAssignableFrom(property.getPropertyType()));
}

From source file:org.openspotlight.persist.support.SimplePersistImpl.java

private <T> void fillNodeChildrenProperties(final ConversionToNodeContext context, final T bean,
        final List<PropertyDescriptor> childrenPropertiesDescriptor, final StorageNode newNodeEntry)
        throws Exception {

    final Map<String, BeanToNodeChildData> nodesToConvert = newHashMap();
    for (final PropertyDescriptor property : childrenPropertiesDescriptor) {
        final String propertyName = property.getName();
        BeanToNodeChildData data = nodesToConvert.get(propertyName);
        final Class<?> propertyType = property.getPropertyType();

        final Object value = property.getReadMethod().invoke(bean);
        if (SimpleNodeType.class.isAssignableFrom(propertyType)) {
            if (data == null) {
                data = new BeanToNodeChildData(propertyName, Collection.class.isAssignableFrom(propertyType),
                        propertyType);/*w ww  . ja  v  a  2s  .  com*/
                nodesToConvert.put(propertyName, data);
            }
            data.childrenToSave.add((SimpleNodeType) value);
        } else if (Collection.class.isAssignableFrom(propertyType)) {
            final Reflection.UnwrappedCollectionTypeFromMethodReturn<Object> methodInformation = unwrapCollectionFromMethodReturn(
                    property.getReadMethod());
            if (data == null) {
                data = new BeanToNodeChildData(propertyName, Collection.class.isAssignableFrom(propertyType),
                        methodInformation.getItemType());
                nodesToConvert.put(propertyName, data);
            }
            if (List.class.isAssignableFrom(methodInformation.getCollectionType())) {
                for (final SimpleNodeType t : (List<SimpleNodeType>) value) {
                    data.childrenToSave.add(t);
                }
            } else if (Set.class.isAssignableFrom(methodInformation.getCollectionType())) {
                for (final SimpleNodeType t : (Set<SimpleNodeType>) value) {
                    data.childrenToSave.add(t);
                }
            } else {
                throw new IllegalStateException("invalid collection type");
            }

        } else {
            throw new IllegalStateException("invalid type:" + property.getPropertyType());
        }
    }
    for (final BeanToNodeChildData data : nodesToConvert.values()) {
        if (!data.multiple && data.childrenToSave.size() > 1) {
            throw new IllegalStateException("single property with more than one child");
        }
        for (final SimpleNodeType beanBeenSaved : data.childrenToSave) {
            internalConvertBeanToNode(context, data.propertyName, beanBeenSaved, newNodeEntry);
        }
        context.allNodes.addAll(iterableToList(newNodeEntry.getChildren(currentPartition, currentSession,
                internalGetNodeName(data.nodeType))));
    }

}

From source file:de.xwic.appkit.core.transport.xml.XmlBeanSerializer.java

/**
 * @param context/*from   w w w  .java 2 s .  c  om*/
 * @param elmProp
 * @param pd
 * @return
 * @throws TransportException
 */
@SuppressWarnings("unchecked")
public Object readValue(Map<EntityKey, Integer> context, Element elProp, PropertyDescriptor pd,
        boolean forceLoadCollection) throws TransportException {

    // check if value is null
    if (elProp.element(XmlExport.ELM_NULL) != null || ATTRVALUE_TRUE.equals(elProp.attributeValue("null"))) {
        return null;
    }

    Class<?> type = getType(elProp.attributeValue("type"));

    if (type == null) {
        if (pd != null) {
            type = pd.getPropertyType();
        } else {
            // is it a bean?
            Element elBean = elProp.element(ELM_BEAN);
            if (elBean != null) {
                return deserializeBean(elBean, context, forceLoadCollection);
            }
            throw new TransportException(
                    "Can't deserialize element '" + elProp.getName() + "' - no type informations available.");
        }
    }

    // check custom object serializers first.
    for (ICustomObjectSerializer cos : customSerializer) {
        if (cos.handlesType(type)) {
            // found a custom serializer, directly return the value, even if null
            return cos.deserialize(elProp);
        }
    }

    Object value = null;

    if (Enum.class.isAssignableFrom(type)) {
        return deserializeEnum(type, elProp);
    }

    if (Set.class.isAssignableFrom(type)) {
        // a set.
        Element elSet = elProp.element(ELM_SET);
        if (elSet != null) {
            Set<Object> set = new HashSet<Object>();
            for (Iterator<?> itSet = elSet.elementIterator(ELM_ELEMENT); itSet.hasNext();) {
                Element elSetElement = (Element) itSet.next();
                set.add(readValue(context, elSetElement, null, forceLoadCollection));
            }
            value = set;
        }
    } else if (List.class.isAssignableFrom(type)) {
        Element elSet = elProp.element(ELM_LIST);
        if (elSet != null) {
            List<Object> list = new ArrayList<Object>();
            for (Iterator<?> itSet = elSet.elementIterator(ELM_ELEMENT); itSet.hasNext();) {
                Element elSetElement = (Element) itSet.next();
                list.add(readValue(context, elSetElement, null, forceLoadCollection));
            }
            value = list;
        }
    } else if (Map.class.isAssignableFrom(type)) {
        value = deserializeMap(context, elProp, forceLoadCollection);
    } else if (IPicklistEntry.class.isAssignableFrom(type)) {

        IPicklisteDAO plDAO = DAOSystem.getDAO(IPicklisteDAO.class);
        IPicklistEntry entry = null;

        String picklistId = elProp.attributeValue("picklistid");
        String key = elProp.attributeValue("key");
        String text = elProp.getText();

        if ((picklistId == null || picklistId.trim().isEmpty()) || (key == null || key.trim().isEmpty())) {
            // maybe it was sent with the ID?

            String strId = elProp.attributeValue("id");

            if (strId != null && !strId.isEmpty()) {
                int id = Integer.parseInt(strId);
                entry = plDAO.getPickListEntryByID(id);
            }

        } else {

            String langid = elProp.attributeValue("langid");
            if (langid == null || langid.length() == 0) {
                langid = "en";
            }

            // try to find by key
            if (key != null && key.length() != 0 && picklistId != null && picklistId.length() != 0) {
                entry = plDAO.getPickListEntryByKey(picklistId, key); // try to find by key
            }

            // not found, try by title
            if (entry == null && picklistId != null && picklistId.length() != 0 && text != null
                    && text.length() != 0) {
                List<IPicklistEntry> lst = plDAO.getAllEntriesToList(picklistId);
                for (IPicklistEntry pe : lst) {
                    if (text.equals(pe.getBezeichnung(langid))) {
                        entry = pe;
                        break;
                    }
                }
            }
        }

        if (entry == null && picklistId != null && text != null) {
            // create??
            IPickliste plist = plDAO.getPicklisteByKey(picklistId);
            if (plist != null) {
                entry = plDAO.createPicklistEntry();
                entry.setKey(key);
                entry.setPickliste(plist);
                plDAO.update(entry);

                for (Language lang : ConfigurationManager.getSetup().getLanguages()) {
                    plDAO.createBezeichnung(entry, lang.getId(), text);
                }
            }
        }
        value = entry;

    } else if (IEntity.class.isAssignableFrom(type)) {
        // entity type
        int refId = Integer.parseInt(elProp.attributeValue("id"));
        if (context != null) {
            Integer newId = context.get(new EntityKey(type.getName(), refId));
            if (newId != null) {
                // its an imported object
                refId = newId.intValue();
            }
        }
        DAO<?> refDAO = DAOSystem.findDAOforEntity((Class<? extends IEntity>) type);
        IEntity refEntity;

        if (refId == Entities.NEW_ENTITY_ID && elProp.attributeValue(EtoSerializer.ETO_PROPERTY) != null) {
            refEntity = EtoSerializer.newEntity(elProp.attributeValue(EtoSerializer.ETO_PROPERTY),
                    forceLoadCollection);
        } else if (elProp.element(XmlEntityTransport.ELM_ENTITY) != null) {

            EtoEntityNodeParser parser = new EtoEntityNodeParser();
            EntityTransferObject refEto = (EntityTransferObject) parser.parseElement(
                    elProp.element(XmlEntityTransport.ELM_ENTITY), context, type, refDAO.getEntityDescriptor(),
                    this, transport.getSessionCache(), forceLoadCollection);
            refEntity = EntityProxyFactory.createEntityProxy(refEto);
        } else {
            refEntity = refDAO.getEntity(refId);
        }

        if (refEntity == null) {
            throw new TransportException(String.format("No entity of type %s with id %s.", type, refId));
        }
        value = refEntity;

    } else {

        Element elBean = elProp.element(ELM_BEAN);
        if (elBean != null) {
            value = deserializeBean(elBean, context, forceLoadCollection);
        } else {
            // basic type
            String text = elProp.getText();
            if (String.class.equals(type)) {
                if (text != null) {
                    value = text.replaceAll(NEW_LINE_PLACEHOLDER, "\n");
                }
            } else if (int.class.equals(type) || Integer.class.equals(type)) {
                value = new Integer(text);
            } else if (long.class.equals(type) || Long.class.equals(type)) {
                value = new Long(text);
            } else if (boolean.class.equals(type) || Boolean.class.equals(type)) {
                value = new Boolean(text.equals("true"));
            } else if (Date.class.equals(type) || java.sql.Timestamp.class.equals(type)) {
                // entities coming from the DB have the Date field as java.sql.Timestamp
                // the serialized value is the ms timestamp, so we can instantiate a Date from
                // it
                value = new Date(Long.parseLong(text));
            } else if (double.class.equals(type) || Double.class.equals(type)) {
                value = new Double(text);
            }
        }
    }

    return value;
}

From source file:org.apache.shiro.config.ReflectionBuilder.java

protected boolean isTypedProperty(Object object, String propertyName, Class clazz) {
    if (clazz == null) {
        throw new NullPointerException("type (class) argument cannot be null.");
    }//from  w  w  w  .  ja  va 2  s  . co m
    try {
        PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(object, propertyName);
        if (descriptor == null) {
            String msg = "Property '" + propertyName + "' does not exist for object of " + "type "
                    + object.getClass().getName() + ".";
            throw new ConfigurationException(msg);
        }
        Class propertyClazz = descriptor.getPropertyType();
        return clazz.isAssignableFrom(propertyClazz);
    } catch (ConfigurationException ce) {
        //let it propagate:
        throw ce;
    } catch (Exception e) {
        String msg = "Unable to determine if property [" + propertyName + "] represents a " + clazz.getName();
        throw new ConfigurationException(msg, e);
    }
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

private boolean isCandidateForBinding(PropertyValue pv) {
    boolean isCandidate = true;
    final Object value = pv.getValue();
    if (value instanceof GrailsParameterMap || value instanceof JSONObject) {
        isCandidate = false;/* ww  w  . j a  va  2  s .c om*/
    } else if (value instanceof Map) {
        isCandidate = false;
        final String propertyName = pv.getName();
        final PropertyDescriptor property = BeanUtils.getPropertyDescriptor(getTarget().getClass(),
                propertyName);
        if (property != null) {
            final Class<?> propertyType = property.getPropertyType();
            if (propertyType.isAssignableFrom(value.getClass())) {
                isCandidate = true;
            }
        }
    }
    return isCandidate;
}

From source file:org.kuali.rice.krad.service.impl.PersistenceStructureServiceJpaImpl.java

/**
 * @see org.kuali.rice.krad.service.PersistenceService#getForeignKeyFieldsPopulationState(org.kuali.rice.krad.bo.BusinessObject,
 *      java.lang.String)/*from  www  . j  av a 2 s  .c  o  m*/
 */
public ForeignKeyFieldsPopulationState getForeignKeyFieldsPopulationState(PersistableBusinessObject bo,
        String referenceName) {

    boolean allFieldsPopulated = true;
    boolean anyFieldsPopulated = false;
    List<String> unpopulatedFields = new ArrayList<String>();

    // yelp if nulls were passed in
    if (bo == null) {
        throw new IllegalArgumentException("The Class passed in for the BusinessObject argument was null.");
    }
    if (StringUtils.isBlank(referenceName)) {
        throw new IllegalArgumentException(
                "The String passed in for the referenceName argument was null or empty.");
    }

    PropertyDescriptor propertyDescriptor = null;

    // make sure the attribute exists at all, throw exception if not
    try {
        propertyDescriptor = PropertyUtils.getPropertyDescriptor(bo, referenceName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (propertyDescriptor == null) {
        throw new ReferenceAttributeDoesntExistException("Requested attribute: '" + referenceName
                + "' does not exist " + "on class: '" + bo.getClass().getName() + "'.");
    }

    // get the class of the attribute name
    Class referenceClass = propertyDescriptor.getPropertyType();

    // make sure the class of the attribute descends from BusinessObject,
    // otherwise throw an exception
    if (!PersistableBusinessObject.class.isAssignableFrom(referenceClass)) {
        throw new ObjectNotABusinessObjectRuntimeException("Attribute requested (" + referenceName
                + ") is of class: " + "'" + referenceClass.getName() + "' and is not a "
                + "descendent of BusinessObject.  Only descendents of BusinessObject " + "can be used.");
    }

    EntityDescriptor descriptor = MetadataManager.getEntityDescriptor(bo.getClass());
    ObjectDescriptor objectDescriptor = descriptor.getObjectDescriptorByName(referenceName);

    if (objectDescriptor == null) {
        throw new ReferenceAttributeNotAnOjbReferenceException(
                "Attribute requested (" + referenceName + ") is not listed "
                        + "in OJB as a reference-descriptor for class: '" + bo.getClass().getName() + "'");
    }

    List<String> fkFields = objectDescriptor.getForeignKeyFields();
    Iterator fkIterator = fkFields.iterator();

    // walk through the list of the foreign keys, get their types
    while (fkIterator.hasNext()) {

        // get the field name of the fk & pk field
        String fkFieldName = (String) fkIterator.next();

        // get the value for the fk field
        Object fkFieldValue = null;
        try {
            fkFieldValue = PropertyUtils.getSimpleProperty(bo, fkFieldName);
        }

        // abort if the value is not retrievable
        catch (Exception e) {
            throw new RuntimeException(e);
        }

        // test the value
        if (fkFieldValue == null) {
            allFieldsPopulated = false;
            unpopulatedFields.add(fkFieldName);
        } else if (fkFieldValue instanceof String) {
            if (StringUtils.isBlank((String) fkFieldValue)) {
                allFieldsPopulated = false;
                unpopulatedFields.add(fkFieldName);
            } else {
                anyFieldsPopulated = true;
            }
        } else {
            anyFieldsPopulated = true;
        }
    }

    // sanity check. if the flag for all fields populated is set, then
    // there should be nothing in the unpopulatedFields list
    if (allFieldsPopulated) {
        if (!unpopulatedFields.isEmpty()) {
            throw new RuntimeException("The flag is set that indicates all fields are populated, but there "
                    + "are fields present in the unpopulatedFields list.  This should never happen, and indicates "
                    + "that the logic in this method is broken.");
        }
    }

    return new ForeignKeyFieldsPopulationState(allFieldsPopulated, anyFieldsPopulated, unpopulatedFields);
}

From source file:org.kuali.rice.kns.kim.type.DataDictionaryTypeServiceBase.java

protected List<RemotableAttributeError> validatePrimitiveFromDescriptor(String kimTypeId, String entryName,
        Object object, PropertyDescriptor propertyDescriptor) {
    List<RemotableAttributeError> errors = new ArrayList<RemotableAttributeError>();
    // validate the primitive attributes if defined in the dictionary
    if (null != propertyDescriptor
            && getDataDictionaryService().isAttributeDefined(entryName, propertyDescriptor.getName())) {
        Object value = ObjectUtils.getPropertyValue(object, propertyDescriptor.getName());
        Class<?> propertyType = propertyDescriptor.getPropertyType();

        if (TypeUtils.isStringClass(propertyType) || TypeUtils.isIntegralClass(propertyType)
                || TypeUtils.isDecimalClass(propertyType) || TypeUtils.isTemporalClass(propertyType)) {

            // check value format against dictionary
            if (value != null && StringUtils.isNotBlank(value.toString())) {
                if (!TypeUtils.isTemporalClass(propertyType)) {
                    errors.addAll(validateAttributeFormat(kimTypeId, entryName, propertyDescriptor.getName(),
                            value.toString(), propertyDescriptor.getName()));
                }/*from   www . j  a  v  a  2  s .co m*/
            } else {
                // if it's blank, then we check whether the attribute should be required
                errors.addAll(validateAttributeRequired(kimTypeId, entryName, propertyDescriptor.getName(),
                        value, propertyDescriptor.getName()));
            }
        }
    }
    return errors;
}

From source file:org.gameye.psp.image.utils.TBeanUtilsBean.java

public void copyProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  copyProperty(");
        sb.append(bean);//from   w  ww .jav  a  2  s . c  om
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String values[] = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    int delim = name.lastIndexOf(PropertyUtils.NESTED_DELIM);
    if (delim >= 0) {
        try {
            target = getPropertyUtils().getProperty(bean, name.substring(0, delim));
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        name = name.substring(delim + 1);
        if (log.isTraceEnabled()) {
            log.trace("    Target bean = " + target);
            log.trace("    Target name = " + name);
        }
    }

    // Declare local variables we will require
    String propName = null; // Simple name of target property
    Class type = null; // Java type of target property
    int index = -1; // Indexed subscript value (if any)
    String key = null; // Mapped key value (if any)

    // Calculate the target property name, index, and key values
    propName = name;
    int i = propName.indexOf(PropertyUtils.INDEXED_DELIM);
    if (i >= 0) {
        int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2);
        try {
            index = Integer.parseInt(propName.substring(i + 1, k));
        } catch (NumberFormatException e) {
            ;
        }
        propName = propName.substring(0, i);
    }
    int j = propName.indexOf(PropertyUtils.MAPPED_DELIM);
    if (j >= 0) {
        int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2);
        try {
            key = propName.substring(j + 1, k);
        } catch (IndexOutOfBoundsException e) {
            ;
        }
        propName = propName.substring(0, j);
    }

    // Calculate the target property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        type = descriptor.getPropertyType();
        if (type == null) {
            // Most likely an indexed setter on a POJB only
            if (log.isTraceEnabled()) {
                log.trace("    target type for property '" + propName + "' is null, so skipping ths setter");
            }
            return;
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("    target propName=" + propName + ", type=" + type + ", index=" + index + ", key=" + key);
    }

    // Convert the specified value to the required type and store it
    if (index >= 0) { // Destination must be indexed
        Converter converter = getConvertUtils().lookup(type.getComponentType());
        if (converter != null) {
            log.trace("        USING CONVERTER " + converter);
            value = converter.convert(type, value);
        }
        try {
            getPropertyUtils().setIndexedProperty(target, propName, index, value);
        } catch (NoSuchMethodException e) {
            throw new InvocationTargetException(e, "Cannot set " + propName);
        }
    } else if (key != null) { // Destination must be mapped
        // Maps do not know what the preferred data type is,
        // so perform no conversions at all
        // FIXME - should we create or support a TypedMap?
        try {
            getPropertyUtils().setMappedProperty(target, propName, key, value);
        } catch (NoSuchMethodException e) {
            throw new InvocationTargetException(e, "Cannot set " + propName);
        }
    } else { // Destination must be simple
        Converter converter = getConvertUtils().lookup(type);
        if (converter != null) {
            log.trace("        USING CONVERTER " + converter);
            value = converter.convert(type, value);
        }
        try {
            getPropertyUtils().setSimpleProperty(target, propName, value);
        } catch (NoSuchMethodException e) {
            throw new InvocationTargetException(e, "Cannot set " + propName);
        }
    }

}

From source file:com.opensymphony.xwork2.util.DefaultLocalizedTextProvider.java

/**
 * <p>/*from  ww  w .  j  a v a 2s .  c  o m*/
 * Finds a localized text message for the given key, aTextName. Both the key and the message
 * itself is evaluated as required.  The following algorithm is used to find the requested
 * message:
 * </p>
 *
 * <ol>
 * <li>Look for message in aClass' class hierarchy.
 * <ol>
 * <li>Look for the message in a resource bundle for aClass</li>
 * <li>If not found, look for the message in a resource bundle for any implemented interface</li>
 * <li>If not found, traverse up the Class' hierarchy and repeat from the first sub-step</li>
 * </ol></li>
 * <li>If not found and aClass is a {@link ModelDriven} Action, then look for message in
 * the model's class hierarchy (repeat sub-steps listed above).</li>
 * <li>If not found, look for message in child property.  This is determined by evaluating
 * the message key as an OGNL expression.  For example, if the key is
 * <i>user.address.state</i>, then it will attempt to see if "user" can be resolved into an
 * object.  If so, repeat the entire process fromthe beginning with the object's class as
 * aClass and "address.state" as the message key.</li>
 * <li>If not found, look for the message in aClass' package hierarchy.</li>
 * <li>If still not found, look for the message in the default resource bundles.</li>
 * <li>Return defaultMessage</li>
 * </ol>
 *
 * <p>
 * When looking for the message, if the key indexes a collection (e.g. user.phone[0]) and a
 * message for that specific key cannot be found, the general form will also be looked up
 * (i.e. user.phone[*]).
 * </p>
 *
 * <p>
 * If a message is found, it will also be interpolated.  Anything within <code>${...}</code>
 * will be treated as an OGNL expression and evaluated as such.
 * </p>
 *
 * <p>
 * If a message is <b>not</b> found a WARN log will be logged.
 * </p>
 *
 * @param aClass         the class whose name to use as the start point for the search
 * @param aTextName      the key to find the text message for
 * @param locale         the locale the message should be for
 * @param defaultMessage the message to be returned if no text message can be found in any
 *                       resource bundle
 * @param args           arguments
 * @param valueStack     the value stack to use to evaluate expressions instead of the
 *                       one in the ActionContext ThreadLocal
 * @return the localized text, or null if none can be found and no defaultMessage is provided
 */
@Override
public String findText(Class aClass, String aTextName, Locale locale, String defaultMessage, Object[] args,
        ValueStack valueStack) {
    String indexedTextName = null;
    if (aTextName == null) {
        LOG.warn("Trying to find text with null key!");
        aTextName = "";
    }
    // calculate indexedTextName (collection[*]) if applicable
    if (aTextName.contains("[")) {
        int i = -1;

        indexedTextName = aTextName;

        while ((i = indexedTextName.indexOf("[", i + 1)) != -1) {
            int j = indexedTextName.indexOf("]", i);
            String a = indexedTextName.substring(0, i);
            String b = indexedTextName.substring(j);
            indexedTextName = a + "[*" + b;
        }
    }

    // search up class hierarchy
    String msg = findMessage(aClass, aTextName, indexedTextName, locale, args, null, valueStack);

    if (msg != null) {
        return msg;
    }

    if (ModelDriven.class.isAssignableFrom(aClass)) {
        ActionContext context = ActionContext.getContext();
        // search up model's class hierarchy
        ActionInvocation actionInvocation = context.getActionInvocation();

        // ActionInvocation may be null if we're being run from a Sitemesh filter, so we won't get model texts if this is null
        if (actionInvocation != null) {
            Object action = actionInvocation.getAction();
            if (action instanceof ModelDriven) {
                Object model = ((ModelDriven) action).getModel();
                if (model != null) {
                    msg = findMessage(model.getClass(), aTextName, indexedTextName, locale, args, null,
                            valueStack);
                    if (msg != null) {
                        return msg;
                    }
                }
            }
        }
    }

    // nothing still? alright, search the package hierarchy now
    for (Class clazz = aClass; (clazz != null) && !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {

        String basePackageName = clazz.getName();
        while (basePackageName.lastIndexOf('.') != -1) {
            basePackageName = basePackageName.substring(0, basePackageName.lastIndexOf('.'));
            String packageName = basePackageName + ".package";
            msg = getMessage(packageName, locale, aTextName, valueStack, args);

            if (msg != null) {
                return msg;
            }

            if (indexedTextName != null) {
                msg = getMessage(packageName, locale, indexedTextName, valueStack, args);

                if (msg != null) {
                    return msg;
                }
            }
        }
    }

    // see if it's a child property
    int idx = aTextName.indexOf(".");

    if (idx != -1) {
        String newKey = null;
        String prop = null;

        if (aTextName.startsWith(XWorkConverter.CONVERSION_ERROR_PROPERTY_PREFIX)) {
            idx = aTextName.indexOf(".", XWorkConverter.CONVERSION_ERROR_PROPERTY_PREFIX.length());

            if (idx != -1) {
                prop = aTextName.substring(XWorkConverter.CONVERSION_ERROR_PROPERTY_PREFIX.length(), idx);
                newKey = XWorkConverter.CONVERSION_ERROR_PROPERTY_PREFIX + aTextName.substring(idx + 1);
            }
        } else {
            prop = aTextName.substring(0, idx);
            newKey = aTextName.substring(idx + 1);
        }

        if (prop != null) {
            Object obj = valueStack.findValue(prop);
            try {
                Object actionObj = ReflectionProviderFactory.getInstance().getRealTarget(prop,
                        valueStack.getContext(), valueStack.getRoot());
                if (actionObj != null) {
                    PropertyDescriptor propertyDescriptor = ReflectionProviderFactory.getInstance()
                            .getPropertyDescriptor(actionObj.getClass(), prop);

                    if (propertyDescriptor != null) {
                        Class clazz = propertyDescriptor.getPropertyType();

                        if (clazz != null) {
                            if (obj != null) {
                                valueStack.push(obj);
                            }
                            msg = findText(clazz, newKey, locale, null, args);
                            if (obj != null) {
                                valueStack.pop();
                            }
                            if (msg != null) {
                                return msg;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                LOG.debug("unable to find property {}", prop, e);
            }
        }
    }

    // get default
    GetDefaultMessageReturnArg result;
    if (indexedTextName == null) {
        result = getDefaultMessage(aTextName, locale, valueStack, args, defaultMessage);
    } else {
        result = getDefaultMessage(aTextName, locale, valueStack, args, null);
        if (result != null && result.message != null) {
            return result.message;
        }
        result = getDefaultMessage(indexedTextName, locale, valueStack, args, defaultMessage);
    }

    // could we find the text, if not log a warn
    if (unableToFindTextForKey(result) && LOG.isDebugEnabled()) {
        String warn = "Unable to find text for key '" + aTextName + "' ";
        if (indexedTextName != null) {
            warn += " or indexed key '" + indexedTextName + "' ";
        }
        warn += "in class '" + aClass.getName() + "' and locale '" + locale + "'";
        LOG.debug(warn);
    }

    return result != null ? result.message : null;
}

From source file:org.eclipse.jubula.client.archive.XmlExporter.java

/**
 * @param xml//  w  w  w.j a v a 2  s  . com
 *            The XML element representation of the project.
 * @param po
 *            The PO representation of the project.
 */
private void fillTestResultSummary(Project xml, IProjectPO po) throws PMException {

    PropertyDescriptor[] properties = XmlImporter.BEAN_UTILS.getPropertyUtils()
            .getPropertyDescriptors(ITestResultSummary.class);
    List<ITestResultSummaryPO> poSummaryList = TestResultSummaryPM.getAllTestResultSummaries(po, null);
    TestresultSummaries xmlSummaryList = xml.addNewTestresultSummaries();
    for (ITestResultSummaryPO poSummary : poSummaryList) {
        checkForCancel();
        if (!poSummary.isTestsuiteRelevant()) {
            continue;
        }
        TestresultSummary xmlSummary = xmlSummaryList.addNewTestresultSummary();
        for (PropertyDescriptor p : properties) {
            String pName = p.getName();
            try {
                String pValue = XmlImporter.BEAN_UTILS.getProperty(poSummary, pName);
                Class<? extends Object> pType = p.getPropertyType();
                SummaryAttribute xmlSummaryAttribute = xmlSummary.addNewAttribute();
                xmlSummaryAttribute.setKey(pName);
                if (pValue != null) {
                    xmlSummaryAttribute.setValue(pValue);
                } else {
                    xmlSummaryAttribute.setNilValue();
                }
                xmlSummaryAttribute.setType(pType.getName());
            } catch (NoSuchMethodException e) {
                log.warn(e.getLocalizedMessage(), e);
            } catch (IllegalAccessException e) {
                log.warn(e.getLocalizedMessage(), e);
            } catch (InvocationTargetException e) {
                log.warn(e.getLocalizedMessage(), e);
            }
        }
        Map<String, IMonitoringValue> tmpMap = poSummary.getMonitoringValues();
        Iterator it = tmpMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry) it.next();
            MonitoringValue tmp = (MonitoringValue) pairs.getValue();
            MonitoringValues monTmp = xmlSummary.addNewMonitoringValue();
            monTmp.setKey((String) pairs.getKey());
            monTmp.setCategory(tmp.getCategory());
            monTmp.setIsSignificant(tmp.isSignificant());
            monTmp.setType(tmp.getType());
            monTmp.setValue(tmp.getValue());

        }

    }
}