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:org.kuali.rice.krad.service.impl.PersistenceStructureServiceOjbImpl.java

@Override
public Map<String, String> getInverseForeignKeysForCollection(Class boClass, String collectionName) {
    // yelp if nulls were passed in
    if (boClass == null) {
        throw new IllegalArgumentException("The Class passed in for the boClass argument was null.");
    }//w ww.ja v  a2 s  .c  o m
    if (collectionName == null) {
        throw new IllegalArgumentException("The String passed in for the attributeName argument was null.");
    }

    PropertyDescriptor propertyDescriptor = null;

    // make an instance of the class passed
    Object classInstance;
    try {
        classInstance = boClass.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

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

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

    // make sure the class of the attribute descends from BusinessObject,
    // otherwise throw an exception
    if (!Collection.class.isAssignableFrom(attributeClass)) {
        throw new ObjectNotABusinessObjectRuntimeException(
                "Attribute requested (" + collectionName + ") is of class: " + "'" + attributeClass.getName()
                        + "' and is not a " + "descendent of Collection");
    }

    // make sure the collection designated is listed as a
    // collection-descriptor
    // on the boClass specified, otherwise throw an exception
    ClassDescriptor classDescriptor = getClassDescriptor(boClass);
    CollectionDescriptor collectionDescriptor = classDescriptor.getCollectionDescriptorByName(collectionName);

    // in collections, the number of keys is equal to the number of keys in
    // the parent class (the class with the collection).
    // Each of the primary keys on the parent object will be mapped to a
    // field in the element object.

    List parentForeignKeys = getPrimaryKeys(boClass);
    Vector childPrimaryKeysLegacy = collectionDescriptor.getForeignKeyFields();

    if (parentForeignKeys.size() != childPrimaryKeysLegacy.size()) {
        throw new RuntimeException(
                "The number of keys in the class descriptor and the inverse foreign key mapping for the collection descriptors do not match.");
    }

    Map<String, String> fkToPkMap = new HashMap<String, String>();

    Iterator pFKIter = parentForeignKeys.iterator();
    Iterator cPKIterator = childPrimaryKeysLegacy.iterator();

    while (pFKIter.hasNext()) {
        String parentForeignKey = (String) pFKIter.next();
        String childPrimaryKey = (String) cPKIterator.next();

        fkToPkMap.put(parentForeignKey, childPrimaryKey);
    }

    return fkToPkMap;
}

From source file:org.nextframework.controller.ExtendedBeanWrapper.java

public Class getPropertyType(String propertyName) throws BeansException {
    try {//from w w w  .ja v a2 s .  c o m
        PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName);
        if (pd != null) {
            return pd.getPropertyType();
        } else {
            // Maybe an indexed/mapped property...
            Object value = getPropertyValue(propertyName);
            if (value != null) {
                return value.getClass();
            }
            // Check to see if there is a custom editor,
            // which might give an indication on the desired target type.
            if (this.customEditors != null) {
                CustomEditorHolder editorHolder = (CustomEditorHolder) this.customEditors.get(propertyName);
                if (editorHolder == null) {
                    List strippedPaths = new LinkedList();
                    addStrippedPropertyPaths(strippedPaths, "", propertyName);
                    for (Iterator it = strippedPaths.iterator(); it.hasNext() && editorHolder == null;) {
                        String strippedName = (String) it.next();
                        editorHolder = (CustomEditorHolder) this.customEditors.get(strippedName);
                    }
                }
                if (editorHolder != null) {
                    return editorHolder.getRegisteredType();
                }
            }
        }
    } catch (InvalidPropertyException ex) {
        // Consider as not determinable.
    }
    return null;
}

From source file:org.kuali.kfs.module.bc.document.validation.impl.BudgetConstructionDocumentRules.java

/**
 * Validates a primitive in a BO/*www.  jav  a  2  s.c om*/
 *
 * @param entryName
 * @param object
 * @param propertyDescriptor
 * @param errorPrefix
 * @param validateRequired
 */
protected void validatePrimitiveFromDescriptor(String entryName, Object object,
        PropertyDescriptor propertyDescriptor, String errorPrefix, boolean validateRequired) {

    // validate the primitive attributes if defined in the dictionary
    if (null != propertyDescriptor
            && dataDictionaryService.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)) {
                    SpringContext.getBean(DictionaryValidationService.class).validate(object, entryName,
                            propertyDescriptor.getName(), false);
                }
            } else if (validateRequired) {
                SpringContext.getBean(DictionaryValidationService.class).validate(object, entryName,
                        propertyDescriptor.getName(), true);
            }
        }
    }
}

From source file:com.complexible.pinto.RDFMapper.java

private Object valueToObject(final Value theValue, final Model theGraph,
        final PropertyDescriptor theDescriptor) {
    if (theValue instanceof Literal) {
        final Literal aLit = (Literal) theValue;
        final IRI aDatatype = aLit.getDatatype() != null ? aLit.getDatatype() : null;

        if (aDatatype == null || XMLSchema.STRING.equals(aDatatype) || RDFS.LITERAL.equals(aDatatype)) {
            String aStr = aLit.getLabel();

            if (theDescriptor != null && Character.TYPE.isAssignableFrom(theDescriptor.getPropertyType())) {
                if (aStr.length() == 1) {
                    return aStr.charAt(0);
                } else {
                    throw new RDFMappingException("Bean type is char, but value is a a string.");
                }/*from   w  ww.ja v a 2  s  .c om*/
            } else {
                return aStr;
            }
        } else if (XMLSchema.BOOLEAN.equals(aDatatype)) {
            return Boolean.valueOf(aLit.getLabel());
        } else if (INTEGER_TYPES.contains(aDatatype)) {
            return Integer.parseInt(aLit.getLabel());
        } else if (LONG_TYPES.contains(aDatatype)) {
            return Long.parseLong(aLit.getLabel());
        } else if (XMLSchema.DOUBLE.equals(aDatatype)) {
            return Double.valueOf(aLit.getLabel());
        } else if (FLOAT_TYPES.contains(aDatatype)) {
            return Float.valueOf(aLit.getLabel());
        } else if (SHORT_TYPES.contains(aDatatype)) {
            return Short.valueOf(aLit.getLabel());
        } else if (BYTE_TYPES.contains(aDatatype)) {
            return Byte.valueOf(aLit.getLabel());
        } else if (XMLSchema.ANYURI.equals(aDatatype)) {
            try {
                return new java.net.URI(aLit.getLabel());
            } catch (URISyntaxException e) {
                LOGGER.warn("URI syntax exception converting literal value which is not a valid URI {} ",
                        aLit.getLabel());
                return null;
            }
        } else if (XMLSchema.DATE.equals(aDatatype) || XMLSchema.DATETIME.equals(aDatatype)) {
            return Dates2.asDate(aLit.getLabel());
        } else if (XMLSchema.TIME.equals(aDatatype)) {
            return new Date(Long.parseLong(aLit.getLabel()));
        } else {
            throw new RuntimeException("Unsupported or unknown literal datatype: " + aLit);
        }
    } else if (theDescriptor != null && Enum.class.isAssignableFrom(theDescriptor.getPropertyType())) {
        IRI aURI = (IRI) theValue;
        Object[] aEnums = theDescriptor.getPropertyType().getEnumConstants();
        for (Object aObj : aEnums) {
            if (((Enum) aObj).name().equals(aURI.getLocalName())) {
                return aObj;
            }
        }

        for (Field aField : theDescriptor.getPropertyType().getFields()) {
            Iri aAnnotation = aField.getAnnotation(Iri.class);
            if (aAnnotation != null && aURI.equals(iri(aAnnotation.value()))) {
                for (Object aObj : aEnums) {
                    if (((Enum) aObj).name().equals(aField.getName())) {
                        return aObj;
                    }
                }

                // if the uri in the Iri annotation equals the value we're converting, but there was no field
                // match, something bad has happened
                throw new RDFMappingException("Expected enum value not found");
            }
        }

        LOGGER.info("{} maps to the enum {}, but does not correspond to any of the values of the enum.", aURI,
                theDescriptor.getPropertyType());

        return null;
    } else {
        Resource aResource = (Resource) theValue;

        final Class aClass = pinpointClass(theGraph, aResource, theDescriptor);

        RDFCodec aCodec = mCodecs.get(aClass);
        if (aCodec != null) {
            return aCodec.readValue(theGraph, aResource);
        } else {
            return readValue(theGraph, aClass, aResource);
        }
    }
}

From source file:de.xwic.appkit.core.access.AccessHandler.java

/**
 * Update the entity specified by this EntityTransferObject.
 * @param eto/*w  ww.j ava 2  s  . c o  m*/
 * @return
 */
@SuppressWarnings("unchecked")
public EntityTransferObject updateETO(EntityTransferObject eto) {

    if (log.isDebugEnabled()) {
        log.debug("updateETO: " + eto.getEntityClass().getName() + " ID#" + eto.getEntityId() + " v"
                + eto.getEntityVersion() + " by user " + getCurrentUsername());
    }

    ISecurityManager secMan = DAOSystem.getSecurityManager();

    DAO dao = DAOSystem.findDAOforEntity(eto.getEntityClass().getName());
    IPicklisteDAO plDAO = (IPicklisteDAO) DAOSystem.getDAO(IPicklisteDAO.class);

    IEntity entity;
    if (eto.getEntityId() == 0) {
        // create entity
        entity = dao.createEntity(eto.getEntityClass().getName());
    } else {
        if (IPicklistEntry.class.isAssignableFrom(eto.getEntityClass())) {
            entity = ((IPicklisteDAO) dao).getPickListEntryByID(eto.getEntityId());
        } else if (IPicklistText.class.isAssignableFrom(eto.getEntityClass())) {
            entity = ((IPicklisteDAO) dao).getPickListTextByID(eto.getEntityId());
        } else {
            entity = dao.getEntity(eto.getEntityId());
        }
        // must "disconnect" the entity from the session, to prevent database 
        // synchronisation
        HibernateUtil.currentSession().evict(entity);
    }

    // check version
    if (entity.getVersion() != eto.getEntityVersion()) {
        throw new DataAccessException("The entity has been modified by someone else.");
    }

    String scope = entity.type().getName();

    boolean monitoring = !entity.isChanged()
            && !secMan.hasRight(scope, ApplicationData.SECURITY_ACTION_APPROVE);
    // always set changed flag if the entity is 'new', user has no approve rights and entity is monitored.
    boolean setChanged = monitoring && entity.getId() == 0
            && omSettings.getMonitoringProperties(scope).isTypeMonitored();

    ObjectMonitoringTypeProperties omTp = null;
    if (monitoring) {
        omTp = omSettings.getMonitoringProperties(scope);
    }
    try {

        Map<String, PropertyDescriptor> propertyMap = classProperties.get(entity.getClass());
        Set<String> propertyKeys = eto.getPropertyValues().keySet();
        for (String propName : propertyKeys) {

            PropertyValue pValue = eto.getPropertyValue(propName);
            if (!pValue.isModified()) {
                continue;
            }

            log.debug("Modified attribute: " + propName);
            if (monitoring && omTp.isMonitored(propName)) {
                setChanged = true;
                monitoring = false; // no need to monitor any other properties
                log.debug("ObjectMonitoring detected change.");
            }

            PropertyDescriptor pd = propertyMap.get(propName);
            if (pd == null) {
                log.error("Attribute modified but no such property: " + propName, new IllegalStateException());
                continue;
            }

            //            PropertyDescriptor pd = new PropertyDescriptor(propName, entity.getClass());
            Method mWrite = pd.getWriteMethod();
            if (mWrite == null) {
                log.warn("No write method for property " + propName);
                continue;
            }

            if (secMan.getAccess(scope, propName) != ISecurityManager.READ_WRITE) {
                log.warn("Tried to modify attribute without rights:  " + propName);
                continue;
            }

            Object value;

            if (pValue.isLoaded()) {
                value = pValue.getValue();
                if (pd.getPropertyType().equals(Date.class) && value instanceof Calendar) {
                    value = ((Calendar) value).getTime();

                    // handle collections --
                    // collections may contain PropertyValue 'stubs' instead of
                    // entities to reduce message-size.
                } else if (value != null && value.getClass().isArray()) {
                    value = parseCollection(plDAO, pValue, value);
                }
            } else if (pValue.getType().equals(IPicklistEntry.class)) {
                value = plDAO.getPickListEntryByID(pValue.getEntityId());
            } else {
                if (!pValue.isEntityType()) {
                    // must be a Set that has not been loaded
                    log.warn("Modified but not-loaded set detected in property " + propName);
                    continue;
                }
                if (pValue.getType().getName().equals(entity.type().getName())
                        && pValue.getEntityId() == entity.getId()) {
                    value = entity;
                } else {
                    value = toEntity(pValue.getType().getName(), pValue.getEntityId());
                    // disconnect entity from session to prevent
                    // double update by hibernate
                    HibernateUtil.currentSession().evict(value);
                }
            }

            if (value != null && value.getClass().isArray()) {
                // AXIS turns Set's into arrays - need to be converted
                if (pd.getPropertyType().equals(Set.class)) {
                    Object[] array = (Object[]) value;
                    Set<Object> set = new HashSet<Object>();
                    for (Object element : array) {
                        set.add(element);
                    }
                    mWrite.invoke(entity, new Object[] { set });
                } else {
                    throw new RuntimeException("NOT IMPLEMENTED: Handle Arrays.");
                }
            } else {
                mWrite.invoke(entity, new Object[] { value });
            }
        }
    } catch (Exception ie) {
        throw new DataAccessException("Error writing entity properties: " + ie, ie);
    }
    // FLI: Set the change property just before update, to prevent "overriding" during
    // the field update.
    if (setChanged) {
        entity.setChanged(true);
    }
    dao.update(entity);

    fireEvent(EVENT_UPDATE, new AccessEvent(this, entity));

    EntityTransferObject result = new EntityTransferObject(entity);

    return result;
}

From source file:org.apache.usergrid.persistence.Schema.java

public void setEntityProperty(Entity entity, String property, Object value) {
    PropertyDescriptor descriptor = getDescriptorForEntityProperty(entity.getClass(), property);
    if (descriptor != null) {
        Class<?> cls = descriptor.getPropertyType();
        if (cls != null) {
            if ((value == null) || (cls.isAssignableFrom(value.getClass()))) {
                try {
                    descriptor.getWriteMethod().invoke(entity, value);
                    return;
                } catch (Exception e) {
                    logger.error("Unable to set entity property " + property, e);
                }//from w ww .ja va  2 s .com
            }
            try {
                descriptor.getWriteMethod().invoke(entity, mapper.convertValue(value, cls));
                return;
            } catch (Exception e) {
                logger.error("Unable to set entity property " + property, e);
            }
        }
    }
    entity.setDynamicProperty(property, value);
}

From source file:com.bstek.dorado.config.xml.XmlParserHelper.java

protected void doInitObjectParser(Context context, ObjectParser objectParser, XmlNodeInfo xmlNodeInfo,
        Class<?> beanType) throws Exception {
    objectParser.setAnnotationOwnerType(beanType);
    if (!Modifier.isAbstract(beanType.getModifiers())) {
        objectParser.setImpl(beanType.getName());
    }/*w  w w.  j av a2  s .  c o m*/

    if (xmlNodeInfo != null) {
        if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) {
            objectParser.setDefinitionType(xmlNodeInfo.getDefinitionType());
        }

        Map<String, XmlParser> propertyParsers = objectParser.getPropertyParsers();
        Map<String, XmlParser> subParsers = objectParser.getSubParsers();

        if (!(objectParser instanceof CompositePropertyParser)) {
            boolean inheritable = objectParser.isInheritable() || xmlNodeInfo.isInheritable();
            objectParser.setInheritable(inheritable);
            if (inheritable) {
                if (propertyParsers.get("parent") == null) {
                    objectParser.registerPropertyParser("parent",
                            beanFactory.getBean(IGNORE_PARSER, XmlParser.class));
                }
            }

            boolean scopable = objectParser.isScopable() || xmlNodeInfo.isScopable();
            objectParser.setScopable(scopable);
            if (scopable) {
                if (propertyParsers.get("scope") == null) {
                    objectParser.registerPropertyParser("scope",
                            beanFactory.getBean(IGNORE_PARSER, XmlParser.class));
                }
            }

            for (String fixedProperty : xmlNodeInfo.getFixedProperties().keySet()) {
                if (propertyParsers.get(fixedProperty) == null) {
                    objectParser.registerPropertyParser(fixedProperty,
                            beanFactory.getBean(IGNORE_PARSER, XmlParser.class));
                }
            }
        }

        for (XmlSubNode xmlSubNode : xmlNodeInfo.getSubNodes()) {
            if (StringUtils.isNotEmpty(xmlSubNode.propertyType())) {
                List<XmlParserInfo> xmlParserInfos = getSubNodeXmlParserInfos(context, beanType,
                        xmlSubNode.propertyName(), null, xmlSubNode);
                if (xmlParserInfos != null) {
                    for (XmlParserInfo xmlParserInfo : xmlParserInfos) {
                        objectParser.registerSubParser(xmlParserInfo.getPath(), xmlParserInfo.getParser());
                    }
                }
            } else if (StringUtils.isNotEmpty(xmlSubNode.nodeName())
                    && StringUtils.isNotEmpty(xmlSubNode.parser())) {
                BeanWrapper beanWrapper = BeanFactoryUtils.getBean(xmlSubNode.parser(), Scope.instant);
                objectParser.registerSubParser(xmlSubNode.nodeName(), (XmlParser) beanWrapper.getBean());
            }
        }

        for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) {
            XmlProperty xmlProperty = entry.getValue();
            XmlParserInfo xmlParserInfo = getPropertyXmlParserInfo(context, beanType,
                    xmlProperty.propertyName(), null, xmlProperty);
            if (xmlParserInfo != null) {
                objectParser.registerPropertyParser(xmlParserInfo.getPath(), xmlParserInfo.getParser());
            }
        }

        if (ClientEventSupported.class.isAssignableFrom(beanType) && subParsers.get("ClientEvent") == null) {
            objectParser.registerSubParser("ClientEvent",
                    beanFactory.getBean(CLIENT_EVENT_PARSER, XmlParser.class));
        }
    }

    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String propertyName = propertyDescriptor.getName();
        if ("class".equals(propertyName)) {
            continue;
        }

        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod == null) {
            continue;
        }
        if (readMethod.getDeclaringClass() != beanType) {
            try {
                readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes());
            } catch (NoSuchMethodException e) {
                // do nothing
            }
        }

        TypeInfo typeInfo;
        Class<?> propertyType = propertyDescriptor.getPropertyType();
        if (Collection.class.isAssignableFrom(propertyType)) {
            typeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true);
            propertyType = typeInfo.getType();
        } else {
            typeInfo = new TypeInfo(propertyType, false);
        }

        XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class);
        if (xmlSubNode != null) {
            if (StringUtils.isNotEmpty(xmlSubNode.propertyName())) {
                throw new IllegalArgumentException("@XmlSubNode.propertyName should be empty. ["
                        + beanType.getName() + '#' + propertyName + "]");
            }

            List<XmlParserInfo> xmlParserInfos = getSubNodeXmlParserInfos(context, beanType, propertyName,
                    typeInfo, xmlSubNode);
            if (xmlParserInfos != null) {
                for (XmlParserInfo xmlParserInfo : xmlParserInfos) {
                    objectParser.registerSubParser(xmlParserInfo.getPath(), xmlParserInfo.getParser());
                }
            }
        } else {
            XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class);
            if (xmlProperty != null && StringUtils.isNotEmpty(xmlProperty.propertyName())) {
                throw new IllegalArgumentException("@XmlProperty.propertyName should be empty. ["
                        + beanType.getName() + '#' + propertyName + "]");
            }

            XmlParserInfo xmlParserInfo = getPropertyXmlParserInfo(context, beanType, propertyName, typeInfo,
                    xmlProperty);
            if (xmlParserInfo != null) {
                XmlParser parser = xmlParserInfo.getParser();
                if (parser instanceof TextPropertyParser) {
                    TextPropertyParser textPropertyParser = (TextPropertyParser) parser;
                    if (textPropertyParser.getTextParser() == null) {
                        TextParser textParser = textParserHelper.getTextParser(propertyType);
                        textPropertyParser.setTextParser(textParser);
                    }
                }
                objectParser.registerPropertyParser(xmlParserInfo.getPath(), parser);
            }
        }
    }

    if (objectParser instanceof ObjectParserInitializationAware) {
        ((ObjectParserInitializationAware) objectParser).postObjectParserInitialized(objectParser);
    }

    Map<String, XmlParserHelperListener> listenerMap = ((ListableBeanFactory) beanFactory)
            .getBeansOfType(XmlParserHelperListener.class);
    for (XmlParserHelperListener listener : listenerMap.values()) {
        listener.onInitParser(this, objectParser, beanType);
    }
}

From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java

/**
 * Generate schema construct for given type
 *
 * @param javaType : Class to whcih need to generate Schema
 * @return : Generated QName/*from w  w  w .  jav  a 2  s  .  c  o m*/
 */
protected QName generateSchema(Class<?> javaType) throws Exception {
    String name = getClassName(javaType);
    QName schemaTypeName = typeTable.getComplexSchemaType(name);
    if (schemaTypeName == null) {
        String simpleName = getSimpleClassName(javaType);

        String packageName = getQualifiedName(javaType.getPackage());
        String targetNameSpace = resolveSchemaNamespace(packageName);

        XmlSchema xmlSchema = getXmlSchema(targetNameSpace);
        String targetNamespacePrefix = targetNamespacePrefixMap.get(targetNameSpace);
        if (targetNamespacePrefix == null) {
            targetNamespacePrefix = generatePrefix();
            targetNamespacePrefixMap.put(targetNameSpace, targetNamespacePrefix);
        }

        XmlSchemaComplexType complexType = new XmlSchemaComplexType(xmlSchema);
        XmlSchemaSequence sequence = new XmlSchemaSequence();
        XmlSchemaComplexContentExtension complexExtension = new XmlSchemaComplexContentExtension();

        XmlSchemaElement eltOuter = new XmlSchemaElement();
        schemaTypeName = new QName(targetNameSpace, simpleName, targetNamespacePrefix);
        eltOuter.setName(simpleName);
        eltOuter.setQName(schemaTypeName);

        Class<?> sup = javaType.getSuperclass();
        if ((sup != null) && (!"java.lang.Object".equals(sup.getName()))
                && (!"java.lang.Exception".equals(sup.getName()))
                && !getQualifiedName(sup.getPackage()).startsWith("org.apache.axis2")
                && !getQualifiedName(sup.getPackage()).startsWith("java.util")) {
            String superClassName = sup.getName();
            String superclassname = getSimpleClassName(sup);
            String tgtNamespace;
            String tgtNamespacepfx;
            QName qName = typeTable.getSimpleSchemaTypeName(superClassName);
            if (qName != null) {
                tgtNamespace = qName.getNamespaceURI();
                tgtNamespacepfx = qName.getPrefix();
            } else {
                tgtNamespace = resolveSchemaNamespace(getQualifiedName(sup.getPackage()));
                tgtNamespacepfx = targetNamespacePrefixMap.get(tgtNamespace);
                QName superClassQname = generateSchema(sup);
                if (superClassQname != null) {
                    tgtNamespacepfx = superClassQname.getPrefix();
                    tgtNamespace = superClassQname.getNamespaceURI();
                }
            }
            if (tgtNamespacepfx == null) {
                tgtNamespacepfx = generatePrefix();
                targetNamespacePrefixMap.put(tgtNamespace, tgtNamespacepfx);
            }
            //if the parent class package name is differ from the child
            if (!((NamespaceMap) xmlSchema.getNamespaceContext()).values().contains(tgtNamespace)) {
                XmlSchemaImport importElement = new XmlSchemaImport();
                importElement.setNamespace(tgtNamespace);
                xmlSchema.getItems().add(importElement);
                ((NamespaceMap) xmlSchema.getNamespaceContext()).put(generatePrefix(), tgtNamespace);
            }

            QName basetype = new QName(tgtNamespace, superclassname, tgtNamespacepfx);
            complexExtension.setBaseTypeName(basetype);
            complexExtension.setParticle(sequence);
            XmlSchemaComplexContent contentModel = new XmlSchemaComplexContent();
            contentModel.setContent(complexExtension);
            complexType.setContentModel(contentModel);

        } else {
            complexType.setParticle(sequence);
        }

        complexType.setName(simpleName);

        if (Modifier.isAbstract(javaType.getModifiers())) {
            complexType.setAbstract(true);
        }

        //            xmlSchema.getItems().add(eltOuter);
        xmlSchema.getElements().add(schemaTypeName, eltOuter);
        eltOuter.setSchemaTypeName(complexType.getQName());

        xmlSchema.getItems().add(complexType);
        xmlSchema.getSchemaTypes().add(schemaTypeName, complexType);

        // adding this type to the table
        typeTable.addComplexSchema(name, eltOuter.getQName());
        // adding this type's package to the table, to support inheritance.
        typeTable.addComplexSchema(getQualifiedName(javaType.getPackage()), eltOuter.getQName());

        typeTable.addClassNameForQName(eltOuter.getQName(), name);

        BeanExcludeInfo beanExcludeInfo = null;
        if (service.getExcludeInfo() != null) {
            beanExcludeInfo = service.getExcludeInfo().getBeanExcludeInfoForClass(getClassName(javaType));
        }

        // we need to get properties only for this bean. hence ignore the super
        // class properties
        BeanInfo beanInfo = Introspector.getBeanInfo(javaType, javaType.getSuperclass());

        for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
            String propertyName = property.getName();
            if (!property.getName().equals("class") && (property.getPropertyType() != null)) {
                if ((beanExcludeInfo == null) || !beanExcludeInfo.isExcludedProperty(propertyName)) {
                    Type genericFieldType = null;
                    try {
                        Field field = javaType.getDeclaredField(propertyName);
                        genericFieldType = field.getGenericType();
                    } catch (Exception e) {
                        //log.info(e.getMessage());
                    }

                    if (genericFieldType instanceof ParameterizedType) {
                        ParameterizedType aType = (ParameterizedType) genericFieldType;
                        Type[] fieldArgTypes = aType.getActualTypeArguments();
                        try {
                            generateSchemaforGenericFields(xmlSchema, sequence, fieldArgTypes[0], propertyName);
                        } catch (Exception e) {
                            generateSchemaforFieldsandProperties(xmlSchema, sequence,
                                    property.getPropertyType(), propertyName,
                                    property.getPropertyType().isArray());
                        }
                    } else {
                        generateSchemaforFieldsandProperties(xmlSchema, sequence, property.getPropertyType(),
                                propertyName, property.getPropertyType().isArray());
                    }
                }
            }
        }
    }
    return schemaTypeName;
}

From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java

/**
 * Uses reflection to find all the settable properties of the object under test,
 * and fails if any of them can be set without an event happening.
 *///  www  .j  av  a2 s.c om
public void testSettingPropertiesFiresEvents() throws Exception {

    CountingWabitListener listener = new CountingWabitListener();
    SPObject wo = getObjectUnderTest();
    wo.addSPListener(listener);

    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass()));

    Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents();
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForEvents.contains(property.getName()))
            continue;

        try {
            oldVal = PropertyUtils.getSimpleProperty(wo, property.getName());

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

        } catch (NoSuchMethodException e) {
            logger.debug(
                    "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName());
            continue;
        }

        int oldChangeCount = listener.getPropertyChangeCount();
        Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());

        try {
            logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(wo, property.getName(), newVal);

            // some setters fire multiple events (they change more than one property)
            assertTrue(
                    "Event for set " + property.getName() + " on " + wo.getClass().getName() + " didn't fire!",
                    listener.getPropertyChangeCount() > oldChangeCount);
            if (listener.getPropertyChangeCount() == oldChangeCount + 1) {
                assertEquals("Property name mismatch for " + property.getName() + " in " + wo.getClass(),
                        property.getName(), listener.getLastPropertyEvent().getPropertyName());
                assertEquals("New value for " + property.getName() + " was wrong", newVal,
                        listener.getLastPropertyEvent().getNewValue());
            }
        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + wo.getClass().getName());
        }
    }

}

From source file:ca.sqlpower.object.PersistedSPObjectTest.java

/**
 * Tests the SPPersisterListener will persist a property change to its
 * target persister./*  w  w w  .  j  a  v a2 s .c  o  m*/
 */
public void testSPListenerPersistsProperty() throws Exception {
    CountingSPPersister countingPersister = new CountingSPPersister();
    SPPersisterListener listener = new SPPersisterListener(countingPersister, getConverter());
    NewValueMaker valueMaker = createNewValueMaker(root, getPLIni());

    SPObject wo = getSPObjectUnderTest();
    wo.addSPListener(listener);

    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass()));

    Set<String> propertiesToPersist = findPersistableBeanProperties(false, false);

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;

        if (!propertiesToPersist.contains(property.getName()))
            continue;

        countingPersister.clearAllPropertyChanges();
        try {
            oldVal = PropertyUtils.getSimpleProperty(wo, property.getName());

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

        } catch (NoSuchMethodException e) {
            logger.debug(
                    "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName());
            continue;
        }

        Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());
        int oldChangeCount = countingPersister.getPersistPropertyCount();

        try {
            //The first property change at current is always the property change we are
            //looking for, this may need to be changed in the future to find the correct
            //property.
            PersistedSPOProperty propertyChange = null;

            try {
                logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                        + newVal.getClass().getName() + ")");
                wo.setMagicEnabled(false);
                BeanUtils.copyProperty(wo, property.getName(), newVal);

                assertTrue("Did not persist property " + property.getName(),
                        oldChangeCount < countingPersister.getPersistPropertyCount());

                for (PersistedSPOProperty nextPropertyChange : countingPersister.getPersistPropertyList()) {
                    if (nextPropertyChange.getPropertyName().equals(property.getName())) {
                        propertyChange = nextPropertyChange;
                        break;
                    }
                }
                assertNotNull("A property change event cannot be found for the property " + property.getName(),
                        propertyChange);

                assertEquals(wo.getUUID(), propertyChange.getUUID());
                assertEquals(property.getName(), propertyChange.getPropertyName());

                assertEquals(
                        "Old value of property " + property.getName() + " was wrong, value expected was  "
                                + oldVal + " but is " + countingPersister.getLastOldValue(),
                        getConverter().convertToBasicType(oldVal), propertyChange.getOldValue());

            } finally {
                wo.setMagicEnabled(true);
            }

            //Input streams from images are being compared by hash code not values
            if (Image.class.isAssignableFrom(property.getPropertyType())) {
                logger.debug(propertyChange.getNewValue().getClass());
                assertTrue(Arrays.equals(PersisterUtils.convertImageToStreamAsPNG((Image) newVal).toByteArray(),
                        PersisterUtils
                                .convertImageToStreamAsPNG((Image) getConverter()
                                        .convertToComplexType(propertyChange.getNewValue(), Image.class))
                                .toByteArray()));
            } else {
                assertEquals(getConverter().convertToBasicType(newVal), propertyChange.getNewValue());
            }
            Class<? extends Object> classType;
            if (oldVal != null) {
                classType = oldVal.getClass();
            } else {
                classType = newVal.getClass();
            }
            assertEquals(PersisterUtils.getDataType(classType), propertyChange.getDataType());
        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + wo.getClass().getName());
        }
    }
}