Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:com.sun.faces.el.impl.BeanInfoManager.java

/**
 * Initializes by mapping property names to BeanInfoProperties
 *///w w w.  jav  a 2s  .c  o  m
void initialize() throws ElException {
    try {
        mBeanInfo = Introspector.getBeanInfo(mBeanClass);

        mPropertyByName = new HashMap();
        mIndexedPropertyByName = new HashMap();
        PropertyDescriptor[] pds = mBeanInfo.getPropertyDescriptors();
        for (int i = 0; pds != null && i < pds.length; i++) {
            // Treat as both an indexed property and a normal property
            PropertyDescriptor pd = pds[i];
            if (pd instanceof IndexedPropertyDescriptor) {
                IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
                Method readMethod = getPublicMethod(ipd.getIndexedReadMethod());
                Method writeMethod = getPublicMethod(ipd.getIndexedWriteMethod());
                BeanInfoIndexedProperty property = new BeanInfoIndexedProperty(readMethod, writeMethod, ipd);

                mIndexedPropertyByName.put(ipd.getName(), property);
            }

            Method readMethod = getPublicMethod(pd.getReadMethod());
            Method writeMethod = getPublicMethod(pd.getWriteMethod());
            BeanInfoProperty property = new BeanInfoProperty(readMethod, writeMethod, pd);

            mPropertyByName.put(pd.getName(), property);
        }

        mEventSetByName = new HashMap();
        EventSetDescriptor[] esds = mBeanInfo.getEventSetDescriptors();
        for (int i = 0; esds != null && i < esds.length; i++) {
            EventSetDescriptor esd = esds[i];
            mEventSetByName.put(esd.getName(), esd);
        }
    } catch (IntrospectionException exc) {
        if (log.isWarnEnabled()) {
            log.warn(MessageUtil.getMessageWithArgs(Constants.EXCEPTION_GETTING_BEANINFO, mBeanClass.getName()),
                    exc);
        }
    }
}

From source file:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java

private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> beanType,
        ActionDescriptor actionDescriptor, ActionInputParameter actionInputParameter, Object currentCallValue)
        throws IntrospectionException, IOException {
    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(beanType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }//  ww  w. ja  va 2s.c o m
        final Class<?> propertyType = propertyDescriptor.getPropertyType();
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);
        if (DataType.isScalar(propertyType)) {

            final Property property = new Property(beanType, propertyDescriptor.getReadMethod(),
                    propertyDescriptor.getWriteMethod(), propertyDescriptor.getName());

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            ActionInputParameter propertySetterInputParameter = new ActionInputParameter(
                    new MethodParameter(propertyDescriptor.getWriteMethod(), 0), propertyValue);
            final Object[] possiblePropertyValues = actionInputParameter.getPossibleValues(property,
                    actionDescriptor);

            writeSupportedProperty(jgen, currentVocab, propertySetterInputParameter, propertyName, property,
                    possiblePropertyValues);
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", propertyName);
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(propertyType, Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = propertyType.getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3.org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            recurseSupportedProperties(jgen, currentVocab, propertyType, actionDescriptor, actionInputParameter,
                    propertyValue);
            jgen.writeEndArray();

            jgen.writeEndObject();
            jgen.writeEndObject();
        }
    }
}

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

/**
 * This test will be run for each object that extends SPObject and confirms
 * the SPSessionPersister can create new objects 
 * @throws Exception//from w  w w  .  j av a 2  s.  c  om
 */
public void testPersisterCreatesNewObjects() throws Exception {
    SPObjectRoot newRoot = new SPObjectRoot();
    WorkspaceContainer stub = new StubWorkspaceContainer() {
        private final SPObject workspace = new StubWorkspace(this, this, root);

        @Override
        public SPObject getWorkspace() {
            return workspace;
        }
    };
    newRoot.setParent(stub.getWorkspace());
    NewValueMaker valueMaker = createNewValueMaker(root, getPLIni());

    NewValueMaker newValueMaker = createNewValueMaker(newRoot, getPLIni());

    SessionPersisterSuperConverter newConverter = new SessionPersisterSuperConverter(getPLIni(), newRoot);

    SPSessionPersister persister = new TestingSessionPersister("Test persister", newRoot, newConverter);
    persister.setWorkspaceContainer(stub);

    for (SPObject child : root.getChildren()) {
        copyToRoot(child, newValueMaker);
    }

    SPObject objectUnderTest = getSPObjectUnderTest();

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

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

    //set all properties of the object
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (!propertiesToPersist.contains(property.getName()))
            continue;
        if (property.getName().equals("parent"))
            continue; //Changing the parent causes headaches.

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

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

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

        Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());
        Object newValInNewRoot = newValueMaker.makeNewValue(property.getPropertyType(), oldVal,
                property.getName());
        if (newValInNewRoot instanceof SPObject) {
            ((SPObject) newValInNewRoot).setUUID(((SPObject) newVal).getUUID());
        }

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

        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + objectUnderTest.getClass().getName());
        }
    }

    //create a new root and parent for the object
    SPObject newParent;
    if (objectUnderTest.getParent() instanceof SPObjectRoot) {
        newParent = newRoot;
    } else {
        newParent = (SPObject) newValueMaker.makeNewValue(objectUnderTest.getParent().getClass(), null, "");
    }
    newParent.setUUID(objectUnderTest.getParent().getUUID());

    int childCount = newParent.getChildren().size();

    //persist the object to the new target root
    Class<? extends SPObject> classChildType = PersisterUtils.getParentAllowedChildType(
            objectUnderTest.getClass().getName(), objectUnderTest.getParent().getClass().getName());
    new SPPersisterListener(persister, getConverter()).persistObject(objectUnderTest,
            objectUnderTest.getParent().getChildren(classChildType).indexOf(objectUnderTest));

    //check object exists
    assertEquals(childCount + 1, newParent.getChildren().size());
    SPObject newChild = null;
    for (SPObject child : newParent.getChildren()) {
        if (child.getUUID().equals(objectUnderTest.getUUID())) {
            newChild = child;
            break;
        }
    }
    if (newChild == null)
        fail("The child was not correctly persisted.");

    //check all interesting properties
    for (PropertyDescriptor property : settableProperties) {
        if (!propertiesToPersist.contains(property.getName()))
            continue;
        if (property.getName().equals("parent"))
            continue; //Changing the parent causes headaches.

        Method readMethod = property.getReadMethod();

        Object valueBeforePersist = readMethod.invoke(objectUnderTest);
        Object valueAfterPersist = readMethod.invoke(newChild);
        Object basicValueBeforePersist = getConverter().convertToBasicType(valueBeforePersist);
        Object basicValueAfterPersist = newConverter.convertToBasicType(valueAfterPersist);

        assertPersistedValuesAreEqual(valueBeforePersist, valueAfterPersist, basicValueBeforePersist,
                basicValueAfterPersist, readMethod.getReturnType());
    }
}

From source file:loxia.support.json.JSONObject.java

@SuppressWarnings("unchecked")
public void setObject(Object bean, String propFilterStr) {
    JSONPropFilter filter = new JSONPropFilter(propFilterStr, objStrTransferMap.keySet());
    this.myHashMap = new HashMap<String, Object>();
    PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(bean.getClass());
    for (PropertyDescriptor prop : props) {
        if ("class".equals(prop.getName()))
            continue;
        if (prop.getReadMethod() != null) {
            String key = prop.getName();
            try {
                Object value = prop.getReadMethod().invoke(bean, (Object[]) null);

                if (filter.isValid(key, value)) {
                    if (value == null) {
                        Class<? extends Object> c = prop.getReadMethod().getReturnType();
                        if (Map.class.isAssignableFrom(c) || Collection.class.isAssignableFrom(c)
                                || c.isArray())
                            continue;
                        this.myHashMap.put(key, NULL);
                    } else if (value instanceof Map) {
                        Map<String, Object> m = (Map<String, Object>) value;
                        this.myHashMap.put(key, new JSONObject(m, filter.getFilterStr(key), objStrTransferMap));
                    } else if (value instanceof Collection) {
                        Collection<? extends Object> c = (Collection<? extends Object>) value;
                        this.myHashMap.put(key, new JSONArray(c, filter.getFilterStr(key), objStrTransferMap));
                    } else if (value.getClass().isArray()) {
                        this.myHashMap.put(key,
                                new JSONArray(value, filter.getFilterStr(key), objStrTransferMap));
                    } else if (filter.isSupportedClass(value)) {
                        this.put(key, value);
                    } else {
                        this.myHashMap.put(key,
                                new JSONObject(value, filter.getFilterStr(key), objStrTransferMap));
                    }//from   w  ww.  java 2s . com
                }
            } catch (Exception e) {
                e.printStackTrace();
                //do nothing
            }
        }
    }

    /*Class<? extends Object> klass = bean.getClass();
     Method[] methods = klass.getMethods();
     for (int i = 0; i < methods.length; i += 1) {
    try {
        Method method = methods[i];
        String name = method.getName();
        String key = "";
        if (name.startsWith("get")) {
            key = name.substring(3);
        } else if (name.startsWith("is")) {
            key = name.substring(2);
        }
        if (key.length() > 0 &&
                Character.isUpperCase(key.charAt(0)) &&
                method.getParameterTypes().length == 0) {
            if (key.length() == 1) {
                key = key.toLowerCase();
            } else if (!Character.isUpperCase(key.charAt(1))) {
                key = key.substring(0, 1).toLowerCase() +
                    key.substring(1);
            }
            Object value = method.invoke(bean, (Object[])null);
                    
            if(filter.isValid(key,value)){ 
               if(value == null){ 
                  Class<? extends Object> c = method.getReturnType();
                  if(Map.class.isAssignableFrom(c) ||
                        Collection.class.isAssignableFrom(c) ||
                        c.isArray()) continue;
                  this.myHashMap.put(key, NULL);                          
               }else if(value instanceof Map){
                Map<String,Object> m = (Map<String,Object>) value;
                this.myHashMap.put(key, new JSONObject(m,filter.getFilterStr(key),objStrTransferMap));
             }else if(value instanceof Collection){
                Collection<? extends Object> c = (Collection<? extends Object>)value;
                this.myHashMap.put(key, new JSONArray(c,filter.getFilterStr(key),objStrTransferMap));
             }else if(value.getClass().isArray()){
                this.myHashMap.put(key, new JSONArray(value,filter.getFilterStr(key),objStrTransferMap));
             }else if(filter.isSupportedClass(value)){
                this.put(key, value);
             }else{
                this.myHashMap.put(key, new JSONObject(value,filter.getFilterStr(key),objStrTransferMap));
             }
          }
        }
    } catch (Exception e) {
       e.printStackTrace();
                
    }
     }*/
}

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

/**
 * This will reflectively iterate over all of the properties in the Wabit
 * object and set each value that has a setter and getter. When the property
 * is set it should cause the property to be persisted through the
 * {@link WorkspacePersisterListener}.//from www  .  j  av a 2 s . c  o  m
 */
public void testPropertiesArePersisted() throws Exception {

    CountingWabitPersister countingPersister = new CountingWabitPersister();
    WorkspacePersisterListener listener = new WorkspacePersisterListener(
            new StubWabitSession(new StubWabitSessionContext()), countingPersister, true);

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

    WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter(
            new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true);
    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass()));

    //Ignore properties that are not in events because we won't have an event
    //to respond to.
    Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents();

    Set<String> propertiesToIgnoreForPersisting = getPropertiesToIgnoreForPersisting();

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;

        if (propertiesToIgnoreForEvents.contains(property.getName()))
            continue;
        if (propertiesToIgnoreForPersisting.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 {
            logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(wo, property.getName(), newVal);

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

            //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;

            for (PersistedSPOProperty nextPropertyChange : countingPersister.getAllPropertyChanges()) {
                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());

            //XXX will replace this later
            List<Object> additionalVals = new ArrayList<Object>();
            if (wo instanceof OlapQuery && property.getName().equals("currentCube")) {
                additionalVals.add(((OlapQuery) wo).getOlapDataSource());
            }

            Object oldConvertedType = converterFactory.convertToBasicType(oldVal, additionalVals.toArray());
            assertEquals(
                    "Old value of property " + property.getName() + " was wrong, value expected was  "
                            + oldConvertedType + " but is " + countingPersister.getLastOldValue(),
                    oldConvertedType, propertyChange.getOldValue());

            //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) converterFactory
                                        .convertToComplexType(propertyChange.getNewValue(), Image.class))
                                .toByteArray()));
            } else {
                assertEquals(converterFactory.convertToBasicType(newVal, additionalVals.toArray()),
                        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());
        }
    }

}

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

/**
 * Tests that calling/*from   w  ww .  java 2s  .co  m*/
 * {@link SPPersister#persistObject(String, String, String, int)} for a
 * session persister will create a new object and set all of the properties
 * on the object.
 */
public void testPersisterAddsNewObject() throws Exception {

    SPObject wo = getObjectUnderTest();
    wo.setMagicEnabled(false);

    WabitSessionPersister persister = new WabitSessionPersister("test persister", session,
            session.getWorkspace(), true);
    WorkspacePersisterListener listener = new WorkspacePersisterListener(session, persister, true);

    WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter(
            new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true);

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

    //Set all possible values to new values for testing.
    Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents();
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForEvents.contains(property.getName()))
            continue;
        if (property.getName().equals("parent"))
            continue; //Changing the parent causes headaches.

        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());

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

        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + wo.getClass().getName());
        }
    }

    SPObject parent = wo.getParent();
    int oldChildCount = parent.getChildren().size();

    listener.transactionStarted(null);
    listener.childRemoved(
            new SPChildEvent(parent, wo.getClass(), wo, parent.getChildren().indexOf(wo), EventType.REMOVED));
    listener.transactionEnded(null);

    //persist the object
    wo.setParent(parent);
    listener.transactionStarted(null);
    listener.childAdded(
            new SPChildEvent(parent, wo.getClass(), wo, parent.getChildren().size(), EventType.ADDED));
    listener.transactionEnded(null);

    //the object must now be added to the super parent
    assertEquals(oldChildCount, parent.getChildren().size());
    SPObject persistedObject = parent.getChildren().get(parent.childPositionOffset(wo.getClass()));
    persistedObject.setMagicEnabled(false);

    //check all the properties are what we expect on the new object
    Set<String> ignorableProperties = getPropertiesToNotPersistOnObjectPersist();

    List<String> settablePropertyNames = new ArrayList<String>();
    for (PropertyDescriptor pd : settableProperties) {
        settablePropertyNames.add(pd.getName());
    }

    settablePropertyNames.removeAll(ignorableProperties);

    for (String persistedPropertyName : settablePropertyNames) {
        Class<?> classType = null;
        for (PropertyDescriptor propertyDescriptor : settableProperties) {
            if (propertyDescriptor.getName().equals(persistedPropertyName)) {
                classType = propertyDescriptor.getPropertyType();
                break;
            }
        }

        logger.debug("Persisted object is of type " + persistedObject.getClass());
        Object oldVal = PropertyUtils.getSimpleProperty(wo, persistedPropertyName);
        Object newVal = PropertyUtils.getSimpleProperty(persistedObject, persistedPropertyName);

        //XXX will replace this later
        List<Object> additionalVals = new ArrayList<Object>();
        if (wo instanceof OlapQuery && persistedPropertyName.equals("currentCube")) {
            additionalVals.add(((OlapQuery) wo).getOlapDataSource());
        }

        Object basicOldVal = converterFactory.convertToBasicType(oldVal, additionalVals.toArray());
        Object basicNewVal = converterFactory.convertToBasicType(newVal, additionalVals.toArray());

        logger.debug("Property " + persistedPropertyName + ". oldVal is \"" + basicOldVal
                + "\" but newVal is \"" + basicNewVal + "\"");

        assertPersistedValuesAreEqual(oldVal, newVal, basicOldVal, basicNewVal, classType);
    }

}

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

/**
 * This test will set all of the properties in a WabitObject in one transaction then
 * after committing the next persister after it will throw an exception causing the
 * persister to undo all of the changes it just made.
 *///from   w  w w  .ja va2  s. c  o  m
public void testPersisterCommitCanRollbackProperties() throws Exception {

    SPObject wo = getObjectUnderTest();

    WabitSessionPersister persister = new WabitSessionPersister("test persister", session, getWorkspace(),
            true);

    CountingWabitListener countingListener = new CountingWabitListener();

    ErrorWabitPersister errorPersister = new ErrorWabitPersister();

    WorkspacePersisterListener listener = new WorkspacePersisterListener(session, errorPersister, true);

    SQLPowerUtils.listenToHierarchy(getWorkspace(), listener);
    wo.addSPListener(countingListener);

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

    Set<String> propertiesToIgnore = new HashSet<String>(getPropertiesToIgnoreForEvents());

    propertiesToIgnore.addAll(getPropertiesToIgnoreForPersisting());

    //Track old and new property values to test they are set properly
    Map<String, Object> propertyNameToOldVal = new HashMap<String, Object>();

    //Set all of the properties of the object under test in one transaction.
    persister.begin();

    int propertyChangeCount = 0;
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;

        if (propertiesToIgnore.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;
        }

        propertyNameToOldVal.put(property.getName(), oldVal);

        //special case for parent types. If a specific wabit object has a tighter parent then
        //WabitObject the getParentClass should return the parent type.
        Class<?> propertyType = property.getPropertyType();
        if (property.getName().equals("parent")) {
            propertyType = getParentClass();
        }
        Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName());

        logger.debug("Persisting property \"" + property.getName() + "\" from oldVal \"" + oldVal
                + "\" to newVal \"" + newVal + "\"");

        //XXX will replace this later
        List<Object> additionalVals = new ArrayList<Object>();
        if (wo instanceof OlapQuery && property.getName().equals("currentCube")) {
            additionalVals.add(((OlapQuery) wo).getOlapDataSource());
        }

        DataType type = PersisterUtils.getDataType(property.getPropertyType());
        Object basicNewValue = converterFactory.convertToBasicType(newVal, additionalVals.toArray());
        persister.persistProperty(wo.getUUID(), property.getName(), type,
                converterFactory.convertToBasicType(oldVal, additionalVals.toArray()), basicNewValue);
        propertyChangeCount++;
    }

    //Commit the transaction causing the rollback to occur
    errorPersister.setThrowError(true);

    try {
        persister.commit();
        fail("The commit method should have an error sent to it and it should rethrow the exception.");
    } catch (SPPersistenceException t) {
        //continue
    }

    for (PropertyDescriptor property : settableProperties) {
        Object currentVal;

        if (propertiesToIgnore.contains(property.getName()))
            continue;

        try {
            currentVal = 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 oldVal = propertyNameToOldVal.get(property.getName());
        //XXX will replace this later
        List<Object> additionalVals = new ArrayList<Object>();
        if (wo instanceof OlapQuery && property.getName().equals("currentCube")) {
            additionalVals.add(((OlapQuery) wo).getOlapDataSource());
        }
        logger.debug("Checking property " + property.getName() + " was set to " + oldVal + ", actual value is "
                + currentVal);
        assertEquals(converterFactory.convertToBasicType(oldVal, additionalVals.toArray()),
                converterFactory.convertToBasicType(currentVal, additionalVals.toArray()));
    }

    logger.debug("Received " + countingListener.getPropertyChangeCount() + " change events.");
    assertTrue(propertyChangeCount * 2 <= countingListener.getPropertyChangeCount());
}

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. j  a  va2s .c  o  m*/
        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;
}

From source file:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java

public List<PersistentProperty> getPersistentProperties(PersistentEntity entity, MappingContext context,
        ClassMapping classMapping) {//  w w  w . j a v  a 2 s . c  o m
    final List<PersistentProperty> persistentProperties = new ArrayList<PersistentProperty>();
    ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(entity.getJavaClass());

    // owners are the classes that own this class
    Collection embedded = cpf.getStaticPropertyValue(EMBEDDED, Collection.class);
    if (embedded == null)
        embedded = Collections.emptyList();

    Collection transients = cpf.getStaticPropertyValue(TRANSIENT, Collection.class);
    if (transients == null)
        transients = Collections.emptyList();

    // hasMany associations for defining one-to-many and many-to-many
    Map hasManyMap = getAssociationMap(cpf);
    // mappedBy for defining by which property an association is mapped
    Map mappedByMap = cpf.getStaticPropertyValue(MAPPED_BY, Map.class);
    if (mappedByMap == null)
        mappedByMap = Collections.emptyMap();
    // hasOne for declaring a one-to-one association with the foreign key in the child
    Map hasOneMap = cpf.getStaticPropertyValue(HAS_ONE, Map.class);
    if (hasOneMap == null)
        hasOneMap = Collections.emptyMap();

    for (PropertyDescriptor descriptor : cpf.getPropertyDescriptors()) {
        if (descriptor.getPropertyType() == null || descriptor.getPropertyType() == Object.class) {
            // indexed property
            continue;
        }
        if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) {
            // non-persistent getter or setter
            continue;
        }
        if (descriptor.getName().equals(VERSION) && !entity.isVersioned()) {
            continue;
        }

        Field field = cpf.getDeclaredField(descriptor.getName());
        if (field != null && java.lang.reflect.Modifier.isTransient(field.getModifiers())) {
            continue;
        }
        final String propertyName = descriptor.getName();
        if (isExcludedProperty(propertyName, classMapping, transients))
            continue;
        Class<?> propertyType = descriptor.getPropertyType();
        Class currentPropType = propertyType;
        // establish if the property is a one-to-many
        // if it is a Set and there are relationships defined
        // and it is defined as persistent
        if (embedded.contains(propertyName)) {
            if (isCollectionType(currentPropType)) {
                Class relatedClassType = (Class) hasManyMap.get(propertyName);
                if (relatedClassType == null) {
                    Class javaClass = entity.getJavaClass();

                    Class genericClass = MappingUtils.getGenericTypeForProperty(javaClass, propertyName);

                    if (genericClass != null) {
                        relatedClassType = genericClass;
                    }
                }
                if (relatedClassType != null) {
                    if (propertyFactory.isSimpleType(relatedClassType)) {
                        Basic basicCollection = propertyFactory.createBasicCollection(entity, context,
                                descriptor);
                        persistentProperties.add(basicCollection);
                    } else {
                        EmbeddedCollection association = propertyFactory.createEmbeddedCollection(entity,
                                context, descriptor);

                        persistentProperties.add(association);
                        if (isPersistentEntity(relatedClassType)) {
                            association.setAssociatedEntity(
                                    getOrCreateAssociatedEntity(entity, context, relatedClassType));
                        } else {
                            PersistentEntity embeddedEntity = context.createEmbeddedEntity(relatedClassType);
                            embeddedEntity.initialize();
                            association.setAssociatedEntity(embeddedEntity);
                        }

                    }
                }
            } else {
                ToOne association = propertyFactory.createEmbedded(entity, context, descriptor);
                PersistentEntity associatedEntity = getOrCreateEmbeddedEntity(entity, context,
                        association.getType());
                association.setAssociatedEntity(associatedEntity);
                persistentProperties.add(association);
            }
        } else if (isCollectionType(currentPropType)) {
            final Association association = establishRelationshipForCollection(descriptor, entity, context,
                    hasManyMap, mappedByMap);
            if (association != null) {
                configureOwningSide(association);
                persistentProperties.add(association);
            }
        }
        // otherwise if the type is a domain class establish relationship
        else if (isPersistentEntity(currentPropType)) {
            final ToOne association = establishDomainClassRelationship(entity, descriptor, context, hasOneMap);
            if (association != null) {
                configureOwningSide(association);
                persistentProperties.add(association);
            }
        } else if (Enum.class.isAssignableFrom(currentPropType) || propertyFactory.isSimpleType(propertyType)) {
            persistentProperties.add(propertyFactory.createSimple(entity, context, descriptor));
        } else if (MappingFactory.isCustomType(propertyType)) {
            persistentProperties.add(propertyFactory.createCustom(entity, context, descriptor));
        }
    }
    return persistentProperties;
}