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.gbif.portal.registration.UDDIUtils.java

/**
 * Creates a Provider detail from the business defined by the given key
 * /* w  w  w .  ja  va  2  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.twinsoft.convertigo.beans.core.DatabaseObject.java

public static DatabaseObject read(Node node) throws EngineException {
    String objectClassName = "n/a";
    String childNodeName = "n/a";
    String propertyName = "n/a";
    String propertyValue = "n/a";
    DatabaseObject databaseObject = null;
    Element element = (Element) node;

    objectClassName = element.getAttribute("classname");

    // Migration to 4.x+ projects
    if (objectClassName.equals("com.twinsoft.convertigo.beans.core.ScreenClass")) {
        objectClassName = "com.twinsoft.convertigo.beans.screenclasses.JavelinScreenClass";
    }/*w  ww .j a v  a 2s .  c o  m*/

    String version = element.getAttribute("version");
    if ("".equals(version)) {
        version = node.getOwnerDocument().getDocumentElement().getAttribute("beans");
        if (!"".equals(version)) {
            element.setAttribute("version", version);
        }
    }
    // Verifying product version
    if (VersionUtils.compareProductVersion(Version.productVersion, version) < 0) {
        String message = "Unable to create an object of product version superior to the current beans product version ("
                + com.twinsoft.convertigo.beans.Version.version + ").\n" + "Object class: " + objectClassName
                + "\n" + "Object version: " + version;
        EngineException ee = new EngineException(message);
        throw ee;
    }

    try {
        Engine.logBeans.trace("Creating object of class \"" + objectClassName + "\"");
        databaseObject = (DatabaseObject) Class.forName(objectClassName).newInstance();
    } catch (Exception e) {
        String s = node.getNodeName();// XMLUtils.prettyPrintDOM(node);
        String message = "Unable to create a new instance of the object from the serialized XML data.\n"
                + "Object class: '" + objectClassName + "'\n" + "Object version: " + version + "\n"
                + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        // Performs custom configuration before object de-serialization
        databaseObject.preconfigure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data before its creation.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        long priority = new Long(element.getAttribute("priority")).longValue();
        databaseObject.priority = priority;

        Class<? extends DatabaseObject> databaseObjectClass = databaseObject.getClass();
        BeanInfo bi = CachedIntrospector.getBeanInfo(databaseObjectClass);
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();

        NodeList childNodes = element.getChildNodes();
        int len = childNodes.getLength();

        PropertyDescriptor pd;
        Object propertyObjectValue;
        Class<?> propertyType;
        NamedNodeMap childAttributes;
        boolean maskValue = false;

        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            Element childElement = (Element) childNode;

            childNodeName = childNode.getNodeName();

            Engine.logBeans.trace("Analyzing node '" + childNodeName + "'");

            if (childNodeName.equalsIgnoreCase("property")) {
                childAttributes = childNode.getAttributes();
                propertyName = childAttributes.getNamedItem("name").getNodeValue();
                Engine.logBeans.trace("  name = '" + propertyName + "'");
                pd = findPropertyDescriptor(pds, propertyName);
                if (pd == null) {
                    Engine.logBeans.warn(
                            "Unable to find the definition of property \"" + propertyName + "\"; skipping.");
                    continue;
                }
                propertyType = pd.getPropertyType();
                propertyObjectValue = XMLUtils
                        .readObjectFromXml((Element) XMLUtils.findChildNode(childNode, Node.ELEMENT_NODE));

                // Hides value in log trace if needed
                if ("false".equals(childElement.getAttribute("traceable"))) {
                    maskValue = true;
                }
                Engine.logBeans.trace("  value='"
                        + (maskValue ? Visibility.maskValue(propertyObjectValue) : propertyObjectValue) + "'");

                // Decrypts value if needed
                try {
                    if ("true".equals(childElement.getAttribute("ciphered"))) {
                        propertyObjectValue = decryptPropertyValue(propertyObjectValue);
                    }
                } catch (Exception e) {
                }

                propertyObjectValue = databaseObject.compileProperty(propertyType, propertyName,
                        propertyObjectValue);

                if (Enum.class.isAssignableFrom(propertyType)) {
                    propertyObjectValue = EnumUtils.valueOf(propertyType, propertyObjectValue);
                }

                propertyValue = propertyObjectValue.toString();

                Method setter = pd.getWriteMethod();
                Engine.logBeans.trace("  setter='" + setter.getName() + "'");
                Engine.logBeans.trace("  param type='" + propertyObjectValue.getClass().getName() + "'");
                Engine.logBeans.trace("  expected type='" + propertyType.getName() + "'");
                try {
                    setter.invoke(databaseObject, new Object[] { propertyObjectValue });
                } catch (InvocationTargetException e) {
                    Throwable targetException = e.getTargetException();
                    Engine.logBeans.warn("Unable to set the property '" + propertyName + "' for the object '"
                            + databaseObject.getName() + "' (" + objectClassName + "): ["
                            + targetException.getClass().getName() + "] " + targetException.getMessage());
                }

                if (Boolean.TRUE.equals(pd.getValue("nillable"))) {
                    Node nodeNull = childAttributes.getNamedItem("isNull");
                    String valNull = (nodeNull == null) ? "false" : nodeNull.getNodeValue();
                    Engine.logBeans.trace("  treats as null='" + valNull + "'");
                    try {
                        Method method = databaseObject.getClass().getMethod("setNullProperty",
                                new Class[] { String.class, Boolean.class });
                        method.invoke(databaseObject, new Object[] { propertyName, Boolean.valueOf(valNull) });
                    } catch (Exception ex) {
                        Engine.logBeans.warn("Unable to set the 'isNull' attribute for property '"
                                + propertyName + "' of '" + databaseObject.getName() + "' object");
                    }
                }
            }
        }
    } catch (Exception e) {
        String message = "Unable to set the object properties from the serialized XML data.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML analyzed node: " + childNodeName + "\n"
                + "Property name: " + propertyName + "\n" + "Property value: " + propertyValue;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        // Performs custom configuration
        databaseObject.configure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data after its creation.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    return databaseObject;
}

From source file:org.enerj.apache.commons.beanutils.locale.LocaleBeanUtilsBean.java

/**
 * Calculate the property type./*from  www.ja  v a 2 s. co m*/
 *
 * @param target The bean
 * @param name The property name
 * @param propName The Simple name of target property
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
protected Class definePropertyType(Object target, String name, String propName)
        throws IllegalAccessException, InvocationTargetException {

    Class type = null; // Java type of target property

    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return null; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return null; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return null; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (descriptor instanceof IndexedPropertyDescriptor) {
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else {
            type = descriptor.getPropertyType();
        }
    }
    return type;
}

From source file:ca.sqlpower.sqlobject.BaseSQLObjectTestCase.java

/**
 * @throws IllegalArgumentException//from w  w  w  . j a v  a 2  s. c o m
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws SQLObjectException 
 */
public void testAllSettersAreUndoable() throws IllegalArgumentException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SQLObjectException {

    SQLObject so = getSQLObjectUnderTest();
    propertiesToIgnoreForUndo.add("referenceCount");
    propertiesToIgnoreForUndo.add("populated");
    propertiesToIgnoreForUndo.add("exportedKeysPopulated");
    propertiesToIgnoreForUndo.add("importedKeysPopulated");
    propertiesToIgnoreForUndo.add("columnsPopulated");
    propertiesToIgnoreForUndo.add("indicesPopulated");
    propertiesToIgnoreForUndo.add("SQLObjectListeners");
    propertiesToIgnoreForUndo.add("children");
    propertiesToIgnoreForUndo.add("parent");
    propertiesToIgnoreForUndo.add("parentDatabase");
    propertiesToIgnoreForUndo.add("class");
    propertiesToIgnoreForUndo.add("childCount");
    propertiesToIgnoreForUndo.add("undoEventListeners");
    propertiesToIgnoreForUndo.add("connection");
    propertiesToIgnoreForUndo.add("typeMap");
    propertiesToIgnoreForUndo.add("secondaryChangeMode");
    propertiesToIgnoreForUndo.add("zoomInAction");
    propertiesToIgnoreForUndo.add("zoomOutAction");
    propertiesToIgnoreForUndo.add("magicEnabled");
    propertiesToIgnoreForUndo.add("deleteRule");
    propertiesToIgnoreForUndo.add("updateRule");
    propertiesToIgnoreForUndo.add("tableContainer");
    propertiesToIgnoreForUndo.add("session");
    propertiesToIgnoreForUndo.add("workspaceContainer");
    propertiesToIgnoreForUndo.add("runnableDispatcher");
    propertiesToIgnoreForUndo.add("foregroundThread");

    if (so instanceof SQLDatabase) {
        // should be handled in the Datasource
        propertiesToIgnoreForUndo.add("name");
    }

    SPObjectUndoManager undoManager = new SPObjectUndoManager(so);
    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(so.getClass()));
    if (so instanceof SQLDatabase) {
        // should be handled in the Datasource
        settableProperties.remove("name");
    }
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForUndo.contains(property.getName()))
            continue;

        try {
            oldVal = PropertyUtils.getSimpleProperty(so, property.getName());
            if (property.getWriteMethod() == null) {
                continue;
            }
        } catch (NoSuchMethodException e) {
            System.out.println(
                    "Skipping non-settable property " + property.getName() + " on " + so.getClass().getName());
            continue;
        }
        Object newVal; // don't init here so compiler can warn if the following code doesn't always give it a value
        if (property.getPropertyType() == Integer.TYPE || property.getPropertyType() == Integer.class) {
            if (oldVal != null) {
                newVal = ((Integer) oldVal) + 1;
            } else {
                newVal = 1;
            }
        } else if (property.getPropertyType() == String.class) {
            // make sure it's unique
            newVal = "new " + oldVal;

        } else if (property.getPropertyType() == Boolean.TYPE || property.getPropertyType() == Boolean.class) {
            if (oldVal == null) {
                newVal = Boolean.TRUE;
            } else {
                newVal = new Boolean(!((Boolean) oldVal).booleanValue());
            }
        } else if (property.getPropertyType() == SQLCatalog.class) {
            newVal = new SQLCatalog(new SQLDatabase(), "This is a new catalog");
        } else if (property.getPropertyType() == SPDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1,tab2");
        } else if (property.getPropertyType() == JDBCDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1,tab2");
        } else if (property.getPropertyType() == SQLTable.class) {
            newVal = new SQLTable();
        } else if (property.getPropertyType() == SQLColumn.class) {
            newVal = new SQLColumn();
        } else if (property.getPropertyType() == SQLIndex.class) {
            newVal = new SQLIndex();
        } else if (property.getPropertyType() == SQLRelationship.SQLImportedKey.class) {
            SQLRelationship rel = new SQLRelationship();
            newVal = rel.getForeignKey();
        } else if (property.getPropertyType() == SQLRelationship.Deferrability.class) {
            if (oldVal == SQLRelationship.Deferrability.INITIALLY_DEFERRED) {
                newVal = SQLRelationship.Deferrability.NOT_DEFERRABLE;
            } else {
                newVal = SQLRelationship.Deferrability.INITIALLY_DEFERRED;
            }
        } else if (property.getPropertyType() == SQLIndex.AscendDescend.class) {
            if (oldVal == SQLIndex.AscendDescend.ASCENDING) {
                newVal = SQLIndex.AscendDescend.DESCENDING;
            } else {
                newVal = SQLIndex.AscendDescend.ASCENDING;
            }
        } else if (property.getPropertyType() == Throwable.class) {
            newVal = new Throwable();
        } else if (property.getPropertyType() == BasicSQLType.class) {
            if (oldVal != BasicSQLType.OTHER) {
                newVal = BasicSQLType.OTHER;
            } else {
                newVal = BasicSQLType.TEXT;
            }
        } else if (property.getPropertyType() == UserDefinedSQLType.class) {
            newVal = new UserDefinedSQLType();
        } else if (property.getPropertyType() == SQLTypeConstraint.class) {
            if (oldVal != SQLTypeConstraint.NONE) {
                newVal = SQLTypeConstraint.NONE;
            } else {
                newVal = SQLTypeConstraint.CHECK;
            }
        } else if (property.getPropertyType() == SQLCheckConstraint.class) {
            newVal = new SQLCheckConstraint("check constraint name", "check constraint condition");
        } else if (property.getPropertyType() == SQLEnumeration.class) {
            newVal = new SQLEnumeration("some enumeration");
        } else if (property.getPropertyType() == String[].class) {
            newVal = new String[3];
        } else if (property.getPropertyType() == PropertyType.class) {
            if (oldVal != PropertyType.NOT_APPLICABLE) {
                newVal = PropertyType.NOT_APPLICABLE;
            } else {
                newVal = PropertyType.VARIABLE;
            }
        } else {
            throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type "
                    + property.getPropertyType().getName() + ") from " + so.getClass());
        }

        int oldChangeCount = undoManager.getUndoableEditCount();

        try {
            BeanUtils.copyProperty(so, property.getName(), newVal);

            // some setters fire multiple events (they change more than one property)  but only register one as an undo
            assertEquals(
                    "Event for set " + property.getName() + " on " + so.getClass().getName()
                            + " added multiple (" + undoManager.printUndoVector() + ") undos!",
                    oldChangeCount + 1, undoManager.getUndoableEditCount());

        } catch (InvocationTargetException e) {
            System.out.println("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + so.getClass().getName());
        }
    }
}

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

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 w  w. 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");
    }

    EntityDescriptor descriptor = MetadataManager.getEntityDescriptor(boClass);
    org.kuali.rice.core.framework.persistence.jpa.metadata.CollectionDescriptor cd = descriptor
            .getCollectionDescriptorByName(collectionName);
    List<String> childPrimaryKeys = cd.getForeignKeyFields();

    List parentForeignKeys = getPrimaryKeys(boClass);

    if (parentForeignKeys.size() != childPrimaryKeys.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 = childPrimaryKeys.iterator();

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

        fkToPkMap.put(parentForeignKey, childPrimaryKey);
    }
    return fkToPkMap;
}

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

@Override
public BusinessObject getReferenceIfExists(BusinessObject bo, String referenceName) {
    // if either argument is null, then we have nothing to do, complain and abort
    if (ObjectUtils.isNull(bo)) {
        throw new IllegalArgumentException("Passed in BusinessObject was null.  No processing can be done.");
    }/*  ww  w  .  j ava2 s .  c om*/
    if (StringUtils.isEmpty(referenceName)) {
        throw new IllegalArgumentException(
                "Passed in referenceName was empty or null.  No processing can be done.");
    }

    // make sure the attribute exists at all, throw exception if not
    PropertyDescriptor propertyDescriptor;
    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() + "'. GFK");
    }

    // get the class of the attribute name
    Class referenceClass = null;
    if (bo instanceof PersistableBusinessObject) {
        referenceClass = persistenceStructureService
                .getBusinessObjectAttributeClass(((PersistableBusinessObject) bo).getClass(), referenceName);
    }
    if (referenceClass == null) {
        referenceClass = ObjectUtils.getPropertyType(bo, referenceName, persistenceStructureService);
    }
    if (referenceClass == null) {
        referenceClass = propertyDescriptor.getPropertyType();
    }

    /*
     * check for Person or EBO references in which case we can just get the reference through propertyutils
     */
    if (ExternalizableBusinessObject.class.isAssignableFrom(referenceClass)) {
        try {
            BusinessObject referenceBoExternalizable = (BusinessObject) PropertyUtils.getProperty(bo,
                    referenceName);
            if (referenceBoExternalizable != null) {
                return referenceBoExternalizable;
            }
        } catch (Exception ex) {
            //throw new RuntimeException("Unable to get property " + referenceName + " from a BO of class: " + bo.getClass().getName(),ex);
            //Proceed further - get the BO relationship using responsible module service and proceed further
        }
    }

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

    // get the list of foreign-keys for this reference. if the reference
    // does not exist, or is not a reference-descriptor, an exception will
    // be thrown here.
    //DataObjectRelationship boRel = dataObjectMetaDataService.getBusinessObjectRelationship( bo, referenceName );
    DataObjectRelationship boRel = getDataObjectMetaDataService().getDataObjectRelationship(bo, bo.getClass(),
            referenceName, "", true, false, false);
    final Map<String, String> fkMap = boRel != null ? boRel.getParentToChildReferences()
            : Collections.<String, String>emptyMap();

    boolean allFkeysHaveValues = true;
    // walk through the foreign keys, testing each one to see if it has a value
    Map<String, Object> pkMap = new HashMap<String, Object>();
    for (Map.Entry<String, String> entry : fkMap.entrySet()) {
        String fkFieldName = entry.getKey();
        String pkFieldName = entry.getValue();

        // attempt to retrieve the value for the given field
        Object fkFieldValue;
        try {
            fkFieldValue = PropertyUtils.getProperty(bo, fkFieldName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // determine if there is a value for the field
        if (ObjectUtils.isNull(fkFieldValue)) {
            allFkeysHaveValues = false;
            break; // no reason to continue processing the fkeys
        } else if (String.class.isAssignableFrom(fkFieldValue.getClass())) {
            if (StringUtils.isEmpty((String) fkFieldValue)) {
                allFkeysHaveValues = false;
                break;
            } else {
                pkMap.put(pkFieldName, fkFieldValue);
            }
        }

        // if there is a value, grab it
        else {
            pkMap.put(pkFieldName, fkFieldValue);
        }
    }

    BusinessObject referenceBo = null;
    // only do the retrieval if all Foreign Keys have values
    if (allFkeysHaveValues) {
        if (ExternalizableBusinessObject.class.isAssignableFrom(referenceClass)) {
            ModuleService responsibleModuleService = KRADServiceLocatorWeb.getKualiModuleService()
                    .getResponsibleModuleService(referenceClass);
            if (responsibleModuleService != null) {
                return responsibleModuleService
                        .<ExternalizableBusinessObject>getExternalizableBusinessObject(referenceClass, pkMap);
            }
        } else
            referenceBo = this.<BusinessObject>findByPrimaryKey(referenceClass, pkMap);
    }

    // return what we have, it'll be null if it was never retrieved
    return referenceBo;
}

From source file:ca.sqlpower.sqlobject.BaseSQLObjectTestCase.java

/**
 * XXX This test should use the {@link GenericNewValueMaker} as it has it's own mini
 * version inside it. This test should also be using the annotations to decide which 
 * setters can fire events./*from  w  w  w.  j av  a 2  s .  com*/
 * 
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws SQLObjectException
 */
public void testAllSettersGenerateEvents() throws IllegalArgumentException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SQLObjectException {
    SQLObject so = getSQLObjectUnderTest();
    so.populate();

    propertiesToIgnoreForEventGeneration.addAll(getPropertiesToIgnoreForEvents());

    //Ignored because we expect the object to be populated.
    propertiesToIgnoreForEventGeneration.add("exportedKeysPopulated");
    propertiesToIgnoreForEventGeneration.add("importedKeysPopulated");
    propertiesToIgnoreForEventGeneration.add("columnsPopulated");
    propertiesToIgnoreForEventGeneration.add("indicesPopulated");

    CountingSQLObjectListener listener = new CountingSQLObjectListener();
    SQLPowerUtils.listenToHierarchy(so, listener);

    if (so instanceof SQLDatabase) {
        // should be handled in the Datasource
        propertiesToIgnoreForEventGeneration.add("name");
    }

    List<PropertyDescriptor> settableProperties;

    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(so.getClass()));

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForEventGeneration.contains(property.getName()))
            continue;

        try {
            oldVal = PropertyUtils.getSimpleProperty(so, property.getName());
            // check for a setter
            if (property.getWriteMethod() == null) {
                continue;
            }

        } catch (NoSuchMethodException e) {
            System.out.println(
                    "Skipping non-settable property " + property.getName() + " on " + so.getClass().getName());
            continue;
        }
        Object newVal; // don't init here so compiler can warn if the following code doesn't always give it a value
        if (property.getPropertyType() == Integer.TYPE || property.getPropertyType() == Integer.class) {
            if (oldVal != null) {
                newVal = ((Integer) oldVal) + 1;
            } else {
                newVal = 1;
            }
        } else if (property.getPropertyType() == String.class) {
            // make sure it's unique
            newVal = "new " + oldVal;

        } else if (property.getPropertyType() == Boolean.TYPE || property.getPropertyType() == Boolean.class) {
            if (oldVal == null) {
                newVal = Boolean.TRUE;
            } else {
                newVal = new Boolean(!((Boolean) oldVal).booleanValue());
            }
        } else if (property.getPropertyType() == SQLCatalog.class) {
            newVal = new SQLCatalog(new SQLDatabase(), "This is a new catalog");
        } else if (property.getPropertyType() == SPDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1");
        } else if (property.getPropertyType() == JDBCDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1");
        } else if (property.getPropertyType() == SQLTable.class) {
            newVal = new SQLTable();
        } else if (property.getPropertyType() == SQLColumn.class) {
            newVal = new SQLColumn();
        } else if (property.getPropertyType() == SQLIndex.class) {
            newVal = new SQLIndex();
        } else if (property.getPropertyType() == SQLRelationship.SQLImportedKey.class) {
            SQLRelationship rel = new SQLRelationship();
            newVal = rel.getForeignKey();
        } else if (property.getPropertyType() == SQLRelationship.Deferrability.class) {
            if (oldVal == SQLRelationship.Deferrability.INITIALLY_DEFERRED) {
                newVal = SQLRelationship.Deferrability.NOT_DEFERRABLE;
            } else {
                newVal = SQLRelationship.Deferrability.INITIALLY_DEFERRED;
            }
        } else if (property.getPropertyType() == SQLRelationship.UpdateDeleteRule.class) {
            if (oldVal == SQLRelationship.UpdateDeleteRule.CASCADE) {
                newVal = SQLRelationship.UpdateDeleteRule.RESTRICT;
            } else {
                newVal = SQLRelationship.UpdateDeleteRule.CASCADE;
            }
        } else if (property.getPropertyType() == SQLIndex.AscendDescend.class) {
            if (oldVal == SQLIndex.AscendDescend.ASCENDING) {
                newVal = SQLIndex.AscendDescend.DESCENDING;
            } else {
                newVal = SQLIndex.AscendDescend.ASCENDING;
            }
        } else if (property.getPropertyType() == Throwable.class) {
            newVal = new Throwable();
        } else if (property.getPropertyType() == BasicSQLType.class) {
            if (oldVal != BasicSQLType.OTHER) {
                newVal = BasicSQLType.OTHER;
            } else {
                newVal = BasicSQLType.TEXT;
            }
        } else if (property.getPropertyType() == UserDefinedSQLType.class) {
            newVal = new UserDefinedSQLType();
        } else if (property.getPropertyType() == SQLTypeConstraint.class) {
            if (oldVal != SQLTypeConstraint.NONE) {
                newVal = SQLTypeConstraint.NONE;
            } else {
                newVal = SQLTypeConstraint.CHECK;
            }
        } else if (property.getPropertyType() == String[].class) {
            newVal = new String[3];
        } else if (property.getPropertyType() == PropertyType.class) {
            if (oldVal != PropertyType.NOT_APPLICABLE) {
                newVal = PropertyType.NOT_APPLICABLE;
            } else {
                newVal = PropertyType.VARIABLE;
            }
        } else if (property.getPropertyType() == List.class) {
            newVal = Arrays.asList("one", "two");
        } else {
            throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type "
                    + property.getPropertyType().getName() + ") from " + so.getClass() + " on property "
                    + property.getDisplayName());
        }

        int oldChangeCount = listener.getChangedCount();

        try {
            System.out.println("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(so, property.getName(), newVal);

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

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);
            }/*  w w  w. j a va2  s .  c om*/
        }
    }

    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:org.kuali.rice.kns.maintenance.KualiMaintainableImpl.java

protected void setNewCollectionLineDefaultValues(String collectionName, PersistableBusinessObject addLine) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(addLine);
    for (int i = 0; i < descriptors.length; ++i) {
        PropertyDescriptor propertyDescriptor = descriptors[i];

        String fieldName = propertyDescriptor.getName();
        Class propertyType = propertyDescriptor.getPropertyType();
        String value = getMaintenanceDocumentDictionaryService()
                .getCollectionFieldDefaultValue(getDocumentTypeName(), collectionName, fieldName);

        if (value != null) {
            try {
                ObjectUtils.setObjectProperty(addLine, fieldName, propertyType, value);
            } catch (Exception ex) {
                LOG.error("Unable to set default property of collection object: " + "\nobject: " + addLine
                        + "\nfieldName=" + fieldName + "\npropertyType=" + propertyType + "\nvalue=" + value,
                        ex);/*from  ww w .jav  a 2 s. c o m*/
            }
        }

    }
}

From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java

private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException {
    JSONArray arr = new JSONArray();
    TypeDiscoverer td = new TypeDiscoverer();
    try {/*from   w  w w  .ja  v  a  2 s.com*/
        for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
            Method readMethod = pd.getReadMethod();
            if (readMethod != null) {
                if (readMethod.getDeclaringClass() == java.lang.Enum.class) {
                    // skip getDeclaringClass
                    continue;
                } else if ("class".equals(pd.getName())) {
                    // skip getClass
                    continue;
                }
            } else {
                // yields com.datatorrent.api.Context on JDK6 and com.datatorrent.api.Context.OperatorContext with JDK7
                if ("up".equals(pd.getName())
                        && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) {
                    continue;
                }
            }
            //LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType());

            Class<?> propertyType = pd.getPropertyType();
            if (propertyType != null) {
                JSONObject propertyObj = new JSONObject();
                propertyObj.put("name", pd.getName());
                propertyObj.put("canGet", readMethod != null);
                propertyObj.put("canSet", pd.getWriteMethod() != null);
                if (readMethod != null) {
                    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
                        OperatorClassInfo oci = classInfo.get(c.getName());
                        if (oci != null) {
                            MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName());
                            if (getMethodInfo != null) {
                                addTagsToProperties(getMethodInfo, propertyObj);
                                break;
                            }
                        }
                    }
                    // type can be a type symbol or parameterized type
                    td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj);
                } else {
                    if (pd.getWriteMethod() != null) {
                        td.setTypeArguments(clazz, pd.getWriteMethod().getGenericParameterTypes()[0],
                                propertyObj);
                    }
                }
                //if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() && !propertyType.getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) {
                //  propertyObj.put("properties", getClassProperties(propertyType, level + 1));
                //}
                arr.put(propertyObj);
            }
        }
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
    return arr;
}