Example usage for org.apache.commons.beanutils PropertyUtils getSimpleProperty

List of usage examples for org.apache.commons.beanutils PropertyUtils getSimpleProperty

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils getSimpleProperty.

Prototype

public static Object getSimpleProperty(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Return the value of the specified simple property of the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

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

/**
 * @throws IllegalArgumentException//w w  w .  j a va2 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:ca.sqlpower.object.PersistedSPObjectTest.java

/**
 * Tests the {@link SPSessionPersister} can update every settable property
 * on an object based on a persist call.
 *///from   w  w  w  .  ja v  a 2 s.c o  m
public void testSPPersisterPersistsProperties() throws Exception {
    SPSessionPersister persister = new TestingSessionPersister("Testing Persister", root, getConverter());
    persister.setWorkspaceContainer(root.getWorkspaceContainer());
    NewValueMaker valueMaker = createNewValueMaker(root, getPLIni());

    SPObject objectUnderTest = getSPObjectUnderTest();

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

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

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;

        //Changing the UUID of the object makes it referenced as a different object
        //and would make the check later in this test fail.
        if (property.getName().equals("UUID"))
            continue;

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

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

        //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 = getSPObjectUnderTest().getClass().getMethod("getParent").getReturnType();
            logger.debug("Persisting parent, type is " + propertyType);
        }
        Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName());

        System.out.println("Persisting property \"" + property.getName() + "\" from oldVal \"" + oldVal
                + "\" to newVal \"" + newVal + "\"");

        DataType type = PersisterUtils.getDataType(property.getPropertyType());
        Object basicNewValue = getConverter().convertToBasicType(newVal);
        persister.begin();
        persister.persistProperty(objectUnderTest.getUUID(), property.getName(), type,
                getConverter().convertToBasicType(oldVal), basicNewValue);
        persister.commit();

        Object newValAfterSet = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName());
        Object basicExpectedValue = getConverter().convertToBasicType(newValAfterSet);

        assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue,
                property.getPropertyType());
    }
}

From source file:ca.sqlpower.architect.swingui.TestPlayPen.java

/**
 * Checks that the properties of an instance from the copy constructor are equal to the original.
 * In the case of a mutable property, it also checks that they don't share the same instance.
 * //from   w w  w  .  j a v a2  s. c  om
 * @throws Exception
 */
public void testCopyConstructor() throws Exception {
    List<PropertyDescriptor> settableProperties = Arrays
            .asList(PropertyUtils.getPropertyDescriptors(pp.getClass()));
    Set<String> copyIgnoreProperties = new HashSet<String>();

    copyIgnoreProperties.add("UI");
    copyIgnoreProperties.add("UIClassID");
    copyIgnoreProperties.add("accessibleContext");
    copyIgnoreProperties.add("actionMap");
    copyIgnoreProperties.add("alignmentX");
    copyIgnoreProperties.add("alignmentY");
    copyIgnoreProperties.add("ancestorListeners");
    copyIgnoreProperties.add("autoscrolls");
    copyIgnoreProperties.add("border");
    copyIgnoreProperties.add("class");
    copyIgnoreProperties.add("component");
    copyIgnoreProperties.add("componentPopupMenu");
    copyIgnoreProperties.add("containerListeners");
    copyIgnoreProperties.add("contentPane");
    copyIgnoreProperties.add("cursorManager");
    copyIgnoreProperties.add("debugGraphicsOptions");
    copyIgnoreProperties.add("doubleBuffered");
    copyIgnoreProperties.add("enabled");
    copyIgnoreProperties.add("focusCycleRoot");
    copyIgnoreProperties.add("focusTraversalKeys");
    copyIgnoreProperties.add("focusTraversalPolicy");
    copyIgnoreProperties.add("focusTraversalPolicyProvider");
    copyIgnoreProperties.add("focusTraversalPolicySet");
    copyIgnoreProperties.add("focusable");
    copyIgnoreProperties.add("fontRenderContext");
    copyIgnoreProperties.add("graphics");
    copyIgnoreProperties.add("height");
    copyIgnoreProperties.add("ignoreTreeSelection");
    copyIgnoreProperties.add("inheritsPopupMenu");
    copyIgnoreProperties.add("inputMap");
    copyIgnoreProperties.add("inputVerifier");
    copyIgnoreProperties.add("insets");
    copyIgnoreProperties.add("layout");
    copyIgnoreProperties.add("managingFocus");
    copyIgnoreProperties.add("maximumSize");
    copyIgnoreProperties.add("minimumSize");
    copyIgnoreProperties.add("mouseMode");
    copyIgnoreProperties.add("name");
    copyIgnoreProperties.add("nextFocusableComponent");
    copyIgnoreProperties.add("opaque");
    copyIgnoreProperties.add("optimizedDrawingEnabled");
    copyIgnoreProperties.add("paintingEnabled");
    copyIgnoreProperties.add("paintingTile");
    copyIgnoreProperties.add("panel");
    copyIgnoreProperties.add("playPenContentPane");
    copyIgnoreProperties.add("preferredScrollableViewportSize");
    copyIgnoreProperties.add("preferredSize");
    copyIgnoreProperties.add("registeredKeyStrokes");
    copyIgnoreProperties.add("requestFocusEnabled");
    copyIgnoreProperties.add("rootPane");
    copyIgnoreProperties.add("scrollableTracksViewportHeight");
    copyIgnoreProperties.add("scrollableTracksViewportWidth");
    copyIgnoreProperties.add("selectedItems");
    copyIgnoreProperties.add("selectedRelationShips");
    copyIgnoreProperties.add("selectedTables");
    copyIgnoreProperties.add("session");
    copyIgnoreProperties.add("topLevelAncestor");
    copyIgnoreProperties.add("toolTipText");
    copyIgnoreProperties.add("transferHandler");
    copyIgnoreProperties.add("usedArea");
    copyIgnoreProperties.add("validateRoot");
    copyIgnoreProperties.add("verifyInputWhenFocusTarget");
    copyIgnoreProperties.add("vetoableChangeListeners");
    copyIgnoreProperties.add("viewPosition");
    copyIgnoreProperties.add("viewportSize");
    copyIgnoreProperties.add("visible");
    copyIgnoreProperties.add("visibleRect");
    copyIgnoreProperties.add("width");
    copyIgnoreProperties.add("x");
    copyIgnoreProperties.add("y");

    copyIgnoreProperties.add("draggingTablePanes");
    copyIgnoreProperties.add("rubberBand");

    // These should not be copied because any new PlayPen needs
    // different values or else it will not work on the new
    // PlayPen.
    copyIgnoreProperties.add("mouseZoomInAction");
    copyIgnoreProperties.add("mouseZoomOutAction");
    copyIgnoreProperties.add("scrollPane");

    // we're not sure if zoom should be duplicated...
    // it might mess up printing?!?!?
    copyIgnoreProperties.add("zoom");

    // individual lists (e.g. tables) checked instead
    copyIgnoreProperties.add("components");

    // The copy of the play pen is for things like print preview, so we don't want to
    // duplicate menus and other interactive features. (?)
    copyIgnoreProperties.add("popupFactory");

    //This property is specific to each play pen and it's settings will be re-calculated
    //regularly so it does not need to be copied.
    copyIgnoreProperties.add("criticismBucket");

    // First pass: set all settable properties, because testing the duplication of
    //             an object with all its properties at their defaults is not a
    //             very convincing test of duplication!
    for (PropertyDescriptor property : settableProperties) {
        if (copyIgnoreProperties.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(pp, property.getName());
            // check for a setter
            if (property.getWriteMethod() != null) {
                Object newVal = getNewDifferentValue(property, oldVal);
                BeanUtils.copyProperty(pp, property.getName(), newVal);
            }
        } catch (NoSuchMethodException e) {
            logger.warn(
                    "Skipping non-settable property " + property.getName() + " on " + pp.getClass().getName());
        }
    }
    // Second pass get a copy make sure all of 
    // the original mutable objects returned from getters are different
    // between the two objects, but have the same values. 
    PlayPen duplicate = new PlayPen(pp.getSession(), pp);
    for (PropertyDescriptor property : settableProperties) {
        logger.info(property.getName() + property.getDisplayName() + property.getShortDescription());
        if (copyIgnoreProperties.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(pp, property.getName());
            Object copyVal = PropertyUtils.getSimpleProperty(duplicate, property.getName());
            if (oldVal == null) {
                throw new NullPointerException("We forgot to set " + property.getName());
            } else {
                assertEquals("The two values for property " + property.getDisplayName() + " in "
                        + pp.getClass().getName() + " should be equal", oldVal, copyVal);

                if (isPropertyInstanceMutable(property)) {
                    assertNotSame("Copy shares mutable property with original, property name: "
                            + property.getDisplayName(), copyVal, oldVal);
                }
            }
        } catch (NoSuchMethodException e) {
            logger.warn(
                    "Skipping non-settable property " + property.getName() + " on " + pp.getClass().getName());
        }
    }
}

From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

private OperationResponse insert(final AbstractEntity record, final Connection conn) throws Exception {
    Class<?> type = record.getClass();
    OperationResponse response = new OperationResponse();

    SimpleDbQuery parser = new SimpleDbQuery();

    String sql = parser.getInsertQuery(type);
    PreparedStatement pstmnt = conn.prepareStatement(sql);
    try {/*from   ww w. ja  v  a2 s  .  c om*/
        StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(type);
        response.setEntity(enref.Entity);
        response.setKey(getEntityKey(record));

        int index = 1;
        for (StructAttributeReflect attr : enref.Attributes) {
            if (attr == null) {
                continue;
            }

            Object value = PropertyUtils.getSimpleProperty(record, attr.Field.getName());
            if (value == null) {
                if (attr.IsKeyColumn && attr.AutoIncrement) {
                    Entity entity = record.getClass().getAnnotation(Entity.class);
                    value = getSequenceValue(entity, attr, conn);
                }
            }
            if (attr.Reference != null) {
                boolean overwrite = false;
                if (attr.Reference.CascadeUpdate) {
                    overwrite = true;
                }
                save((AbstractEntity) value, conn, overwrite);
                StructAttributeReflect rattr = ReflectionUtils.get().getAttribute(value.getClass(),
                        attr.Reference.Field);
                value = PropertyUtils.getProperty(value, rattr.Field.getName());
            } else if (attr.Column.compareTo(AbstractPersistedEntity._TX_TIMESTAMP_COLUMN_) == 0) {
                value = new Date();
            }
            setPreparedValue(pstmnt, index, attr, value, record);
            index++;
        }
        int count = pstmnt.executeUpdate();
        if (count > 0) {
            response.setOperation(EnumPersistenceOperation.Inserted);
        } else {
            response.setOperation(EnumPersistenceOperation.Ignored);
        }
        log.debug("[" + record.getClass().getCanonicalName() + "] created [count=" + count + "]");
        return response;
    } finally {
        if (pstmnt != null && !pstmnt.isClosed()) {
            pstmnt.close();
        }
    }
}

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

/**
 * This test uses the object under test to ensure that the
 * {@link WabitSessionPersister} updates each property appropriately on
 * persistence./*from  w w w. j  a  v  a2 s. com*/
 */
public void testPersisterUpdatesProperties() throws Exception {

    SPObject wo = getObjectUnderTest();

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

    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;

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

        //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.begin();
        persister.persistProperty(wo.getUUID(), property.getName(), type,
                converterFactory.convertToBasicType(oldVal, additionalVals.toArray()), basicNewValue);
        persister.commit();

        Object newValAfterSet = PropertyUtils.getSimpleProperty(wo, property.getName());
        Object basicExpectedValue = converterFactory.convertToBasicType(newValAfterSet,
                additionalVals.toArray());

        assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue,
                property.getPropertyType());
    }
}

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/* w  ww .  j av a 2 s.  c  o  m*/
 */
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:com.sop4j.dbutils.QueryRunner.java

/**
 * Binds values to an executor./*from  w  w  w  .  j  a va  2s  .c o  m*/
 * @param exec
 * @param columns
 * @param entity
 * @param excludes
 * @throws SQLException
 */
private <T> void bindColumnValues(final AbstractExecutor<?> exec, final Map<String, String> columns,
        final T entity, final Collection<String> excludes) throws SQLException {
    for (String column : columns.keySet()) {
        // skip anything in the exclude set
        if (excludes.contains(column)) {
            continue;
        }

        try {
            // bind all of the values
            final Object value = PropertyUtils.getSimpleProperty(entity, columns.get(column));

            if (value == null) {
                exec.bindNull(column);
            } else {
                exec.bind(column, value);
            }
        } catch (final IllegalAccessException e) {
            throw new SQLException(e);
        } catch (final InvocationTargetException e) {
            throw new SQLException(e);
        } catch (final NoSuchMethodException e) {
            throw new SQLException(e);
        }
    }
}

From source file:com.inamik.template.TemplateVariable.java

/**
 * getNamedProperty - For wrapped objects that are Java Beans, get the
 * named property of the bean.//w ww .  java 2  s .c  o m
 * <p>
 * This method uses the Apache Commons BeanUtils package.
 *
 * @return A TemplateVariable containing the named property of the wrapped
 *         bean, or <code>TemplateVariable.NULL</code> if the wrapped
 *         object is not a Java Bean.
 *
 * @throws TemplateException If the Apache BeanUtils package throws an
 *         exception, that exception is wrapped in a TemplateException
 *         and re-thrown.
 */
public TemplateVariable getNamedProperty(final String property) throws TemplateException {
    if (property == null) {
        return NULL;
    }

    if (isNull) {
        return NULL;
    }

    if (isArray) {
        return NULL;
    }

    try {
        Object o = PropertyUtils.getSimpleProperty(object, property);

        return newInstance(o);
    } catch (Exception e) {
        throw new TemplateException(e);
    }
}

From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

private void setPreparedValue(final PreparedStatement pstmnt, final int index,
        final StructAttributeReflect attr, Object value, final AbstractEntity entity) throws Exception {
    Class<?> type = attr.Field.getType();
    if (EnumPrimitives.isPrimitiveType(type)) {
        EnumPrimitives prim = EnumPrimitives.type(type);
        switch (prim) {
        case ECharacter:
            pstmnt.setString(index, String.valueOf(value));
            break;
        case EShort:
            pstmnt.setShort(index, (Short) value);
            break;
        case EInteger:
            pstmnt.setInt(index, (Integer) value);
            break;
        case ELong:
            pstmnt.setLong(index, (Long) value);
            break;
        case EFloat:
            pstmnt.setFloat(index, (Float) value);
            break;
        case EDouble:
            pstmnt.setDouble(index, (Double) value);
            break;
        default:/*from   ww  w.  j  av a  2  s. c o  m*/
            throw new Exception("Unsupported Data type [" + prim.name() + "]");
        }
    } else {
        if (type.equals(String.class)) {
            pstmnt.setString(index, (String) value);
        } else if (type.equals(Date.class)) {
            long dtval = new Date().getTime();
            if (value != null) {
                dtval = ((Date) value).getTime();
            }
            pstmnt.setLong(index, dtval);
        } else if (value instanceof Enum) {
            pstmnt.setString(index, getEnumValue(value));
        } else if (attr.Convertor != null) {
            pstmnt.setString(index, (String) attr.Convertor.save(entity, attr.Field.getName()));
        } else if (attr.Reference != null) {
            Class<?> cls = Class.forName(attr.Reference.Class);
            StructAttributeReflect rattr = ReflectionUtils.get().getAttribute(cls, attr.Reference.Field);
            Object refval = PropertyUtils.getSimpleProperty(entity, attr.Field.getName());
            value = PropertyUtils.getSimpleProperty(refval, rattr.Field.getName());
            setPreparedValue(pstmnt, index, rattr, value, entity);
        } else
            throw new Exception("Unsupported field type [" + type.getCanonicalName() + "]");
    }
}

From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

private OperationResponse update(final AbstractEntity record, final Connection conn) throws Exception {
    Class<?> type = record.getClass();
    OperationResponse response = new OperationResponse();

    SimpleDbQuery parser = new SimpleDbQuery();

    String sql = parser.getUpdateQuery(type);

    PreparedStatement pstmnt = conn.prepareStatement(sql);

    try {//from   w  ww  .  j  av a  2  s  .c  o m
        List<StructAttributeReflect> keyattrs = new ArrayList<StructAttributeReflect>();

        StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(type);

        response.setEntity(enref.Entity);
        response.setKey(getEntityKey(record));

        int index = 1;
        for (StructAttributeReflect attr : enref.Attributes) {
            if (attr == null) {
                continue;
            }

            if (attr.IsKeyColumn) {
                keyattrs.add(attr);
                continue;
            }

            Object value = PropertyUtils.getSimpleProperty(record, attr.Field.getName());
            if (attr.Reference != null && attr.Reference.CascadeUpdate) {
                save((AbstractEntity) value, conn, true);
                StructAttributeReflect rattr = ReflectionUtils.get().getAttribute(value.getClass(),
                        attr.Reference.Field);
                value = PropertyUtils.getProperty(value, rattr.Field.getName());
            } else if (attr.Column.compareTo(AbstractPersistedEntity._TX_TIMESTAMP_COLUMN_) == 0) {
                value = new Date();
                keyattrs.add(attr);
            }
            setPreparedValue(pstmnt, index, attr, value, record);
            index++;
        }
        for (int ii = 0; ii < keyattrs.size(); ii++) {
            Object value = PropertyUtils.getSimpleProperty(record, keyattrs.get(ii).Field.getName());
            setPreparedValue(pstmnt, (index + ii), keyattrs.get(ii), value, record);
        }

        int count = pstmnt.executeUpdate();
        if (count > 0) {
            response.setOperation(EnumPersistenceOperation.Updated);
        } else {
            response.setOperation(EnumPersistenceOperation.Ignored);
        }
        log.debug("[" + record.getClass().getCanonicalName() + "] updated [count=" + count + "]");
        return response;
    } finally {
        if (pstmnt != null && !pstmnt.isClosed()) {
            pstmnt.close();
        }
    }
}