Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

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

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

Gets the method that should be used to read the property value.

Usage

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private void processRemovedManyToMany(ObjectsToPersist toPersist,
        Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId,
        EntityManager em) throws ClassNotFoundException, IntrospectionException, PersistenceException,
        IllegalAccessException, InvocationTargetException, NoSuchFieldException {
    Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> manyToManyRemoved = toPersist
            .getManyToManyRemovedByClassName();
    if (manyToManyRemoved != null && !manyToManyRemoved.isEmpty()) {
        for (Entry<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> e : manyToManyRemoved
                .entrySet()) {/*from  w  ww  .j  a  v a  2 s  . co  m*/
            String className = e.getKey();
            Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> map = e
                    .getValue();
            if (map != null && !map.isEmpty()) {
                Class<?> clazz = Class.forName(className);
                for (Entry<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> entry : map
                        .entrySet()) {
                    com.hiperf.common.ui.shared.util.Id id = entry.getKey();
                    Map<String, List<com.hiperf.common.ui.shared.util.Id>> m = entry.getValue();
                    if (m != null && !m.isEmpty()) {
                        Object objId = id.getFieldValues().get(0);
                        if (newIdByOldId.containsKey(objId))
                            objId = newIdByOldId.get(objId).getId();
                        Object o = em.find(clazz, objId);
                        if (o != null) {
                            PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(className);
                            for (Entry<String, List<com.hiperf.common.ui.shared.util.Id>> ee : m.entrySet()) {
                                String attr = ee.getKey();
                                List<com.hiperf.common.ui.shared.util.Id> ll = ee.getValue();
                                if (ll != null && !ll.isEmpty()) {
                                    Collection coll = null;
                                    Class classInColl = null;
                                    PropertyDescriptor myPd = null;
                                    for (PropertyDescriptor pd : pds) {
                                        if (pd.getName().equals(attr)) {
                                            myPd = pd;
                                            coll = (Collection) pd.getReadMethod().invoke(o,
                                                    StorageService.emptyArg);
                                            break;
                                        }
                                    }
                                    if (coll != null) {
                                        ParameterizedType genericType = (ParameterizedType) clazz
                                                .getDeclaredField(myPd.getName()).getGenericType();
                                        if (genericType != null) {
                                            for (Type t : genericType.getActualTypeArguments()) {

                                                if (t instanceof Class
                                                        && INakedObject.class.isAssignableFrom((Class) t)) {
                                                    classInColl = (Class) t;
                                                    break;
                                                }
                                            }
                                        }
                                        for (com.hiperf.common.ui.shared.util.Id i : ll) {
                                            Object idObj = i.getFieldValues().get(0);
                                            if (newIdByOldId.containsKey(idObj))
                                                idObj = newIdByOldId.get(idObj);
                                            Object linkedObj = em.find(classInColl, idObj);
                                            coll.remove(linkedObj);
                                        }
                                    }
                                }
                            }
                            res.put(id, (INakedObject) em.merge(o));
                        }
                    }

                }
            }
        }
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private void processAddedManyToMany(ObjectsToPersist toPersist,
        Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId,
        EntityManager em) throws ClassNotFoundException, IntrospectionException, PersistenceException,
        IllegalAccessException, InvocationTargetException, NoSuchFieldException {
    Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> manyToManyAdded = toPersist
            .getManyToManyAddedByClassName();
    if (manyToManyAdded != null && !manyToManyAdded.isEmpty()) {
        for (Entry<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> e : manyToManyAdded
                .entrySet()) {/*ww  w . java2s .c  o m*/
            String className = e.getKey();
            Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> map = e
                    .getValue();
            if (map != null && !map.isEmpty()) {
                Class<?> clazz = Class.forName(className);
                for (Entry<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> entry : map
                        .entrySet()) {
                    com.hiperf.common.ui.shared.util.Id id = entry.getKey();
                    Map<String, List<com.hiperf.common.ui.shared.util.Id>> m = entry.getValue();
                    if (m != null && !m.isEmpty()) {
                        Object objId = id.getFieldValues().get(0);
                        if (newIdByOldId.containsKey(objId))
                            objId = newIdByOldId.get(objId).getId();
                        Object o = em.find(clazz, objId);
                        if (o != null) {
                            PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(className);
                            for (Entry<String, List<com.hiperf.common.ui.shared.util.Id>> ee : m.entrySet()) {
                                String attr = ee.getKey();
                                List<com.hiperf.common.ui.shared.util.Id> ll = ee.getValue();
                                if (ll != null && !ll.isEmpty()) {
                                    Collection coll = null;
                                    Class classInColl = null;
                                    PropertyDescriptor myPd = null;
                                    String mappedBy = null;
                                    for (PropertyDescriptor pd : pds) {
                                        if (pd.getName().equals(attr)) {
                                            myPd = pd;
                                            coll = (Collection) pd.getReadMethod().invoke(o,
                                                    StorageService.emptyArg);
                                            if (coll == null) {
                                                if (List.class.isAssignableFrom(pd.getPropertyType()))
                                                    coll = new ArrayList();
                                                else
                                                    coll = new HashSet();
                                                pd.getWriteMethod().invoke(o, coll);
                                            }
                                            ManyToMany ann = pd.getReadMethod().getAnnotation(ManyToMany.class);
                                            if (ann == null) {
                                                ann = clazz.getDeclaredField(pd.getName())
                                                        .getAnnotation(ManyToMany.class);
                                            }
                                            if (ann != null) {
                                                mappedBy = ann.mappedBy();
                                            }
                                            break;
                                        }
                                    }
                                    if (coll != null) {
                                        ParameterizedType genericType = (ParameterizedType) clazz
                                                .getDeclaredField(myPd.getName()).getGenericType();
                                        if (genericType != null) {
                                            for (Type t : genericType.getActualTypeArguments()) {

                                                if (t instanceof Class
                                                        && INakedObject.class.isAssignableFrom((Class) t)) {
                                                    classInColl = (Class) t;
                                                    break;
                                                }
                                            }
                                        }
                                        for (com.hiperf.common.ui.shared.util.Id i : ll) {
                                            Object idObj = i.getFieldValues().get(0);
                                            if (newIdByOldId.containsKey(idObj))
                                                idObj = newIdByOldId.get(idObj).getId();
                                            Object linkedObj = em.find(classInColl, idObj);
                                            if (mappedBy == null || mappedBy.length() == 0)
                                                coll.add(linkedObj);
                                            else {
                                                PropertyDescriptor[] pds2 = propertyDescriptorsByClassName
                                                        .get(classInColl.getName());
                                                if (pds2 == null) {
                                                    pds2 = propertyDescriptorsByClassName
                                                            .get(classInColl.getName());
                                                }
                                                for (PropertyDescriptor pd : collectionsByClassName
                                                        .get(classInColl.getName())) {
                                                    if (pd.getName().equals(mappedBy)) {
                                                        Collection coll2 = (Collection) pd.getReadMethod()
                                                                .invoke(linkedObj, StorageService.emptyArg);
                                                        if (coll2 == null) {
                                                            if (List.class
                                                                    .isAssignableFrom(pd.getPropertyType()))
                                                                coll2 = new ArrayList();
                                                            else
                                                                coll2 = new HashSet();
                                                            pd.getWriteMethod().invoke(linkedObj, coll2);
                                                        }
                                                        coll2.add(o);
                                                    }
                                                }
                                                em.merge(linkedObj);
                                            }
                                            if (linkedObj instanceof INakedObject)
                                                res.put(i, (INakedObject) linkedObj);
                                        }
                                    }
                                }
                            }
                            res.put(id, (INakedObject) em.merge(o));
                        }
                    }

                }
            }
        }
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private boolean doPersist(ObjectsToPersist toPersist, String userName,
        Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId,
        EntityManager em, boolean validateBefore, Locale locale, boolean processExceptions)
        throws ClassNotFoundException, IntrospectionException, PersistenceException, IllegalAccessException,
        InvocationTargetException, InstantiationException {
    try {//ww  w .  ja v  a 2s. c o  m
        Validator validator = validatorFactory.getValidator();
        List<INakedObject> toInsert = toPersist.getInsertedObjects();
        if (toInsert != null) {
            int max = 100 * toInsert.size();
            int idx = -1;
            int k = -1;
            int s = toInsert.size();
            int prevSize = s;
            while (!toInsert.isEmpty()) {

                if (s == toInsert.size()) {
                    k++;
                } else
                    k = 0;
                if (k == 1) {
                    logger.log(Level.FINE,
                            "Impossible to persist data : one linked object not found in toInsert list");
                    return false;
                }

                if (prevSize == toInsert.size()) {
                    idx++;
                } else {
                    idx = 0;
                    prevSize = toInsert.size();
                }
                if (idx > max) {
                    logger.log(Level.FINE,
                            "Impossible to persist data : one linked object not found in toInsert list...");
                    return false;
                }
                Iterator<INakedObject> it = toInsert.iterator();
                while (it.hasNext()) {
                    INakedObject o = (INakedObject) it.next();
                    String className = o.getClass().getName();
                    if (o instanceof IAuditable) {
                        IAuditable aud = (IAuditable) o;
                        aud.setCreateUser(userName);
                        aud.setCreateDate(new Date());
                    }

                    Set<PropertyDescriptor> ids = idsByClassName.get(className);

                    processLinkedCollectionsBeforePersist(o, collectionsByClassName.get(className));

                    if (!processLinkedObjectsBeforePersist(newIdByOldId, o, lazysByClassName.get(className),
                            toPersist))
                        continue;
                    if (!processLinkedObjectsBeforePersist(newIdByOldId, o,
                            eagerObjectsByClassName.get(className), toPersist))
                        continue;

                    if (generatedIdClasses.contains(className)) {
                        PropertyDescriptor idPd = ids.iterator().next();
                        Object oldId = idPd.getReadMethod().invoke(o, StorageService.emptyArg);
                        Object[] args = new Object[1];
                        if (!idPd.getPropertyType().isPrimitive())
                            args[0] = null;
                        else
                            args[0] = 0L;
                        idPd.getWriteMethod().invoke(o, args);

                        if (validateBefore) {
                            Set<ConstraintViolation<INakedObject>> errors = validator.validate(o);
                            if (errors != null && !errors.isEmpty()) {
                                it.remove();
                                continue;
                            }
                            try {
                                em.persist(o);
                            } catch (Exception e) {
                                it.remove();
                                continue;
                            }
                        } else
                            em.persist(o);
                        Object newId = idPd.getReadMethod().invoke(o, StorageService.emptyArg);
                        newIdByOldId.put(oldId, new IdHolder(newId, className));
                        List<Object> idVals = new ArrayList<Object>(1);
                        idVals.add(oldId);
                        List<String> idFields = new ArrayList<String>(1);
                        idFields.add(idPd.getName());
                        res.put(new com.hiperf.common.ui.shared.util.Id(idFields, idVals), o);

                        it.remove();
                    } else {
                        com.hiperf.common.ui.shared.util.Id id = getId(o, ids);
                        int i = 0;
                        boolean toProcess = true;
                        for (Object idVal : id.getFieldValues()) {
                            if ((idVal instanceof Long && ((Long) idVal).longValue() < 0)
                                    || (idVal instanceof String
                                            && ((String) idVal).startsWith(PersistenceManager.SEQ_PREFIX))) {
                                IdHolder newIds = newIdByOldId.get(idVal);
                                if (newIds != null) {
                                    String att = id.getFieldNames().get(i);
                                    for (PropertyDescriptor idPd : ids) {
                                        if (idPd.getName().equals(att)) {
                                            Object[] args = new Object[1];
                                            args[0] = newIds.getId();
                                            idPd.getWriteMethod().invoke(o, args);
                                            break;
                                        }
                                    }
                                } else {
                                    toProcess = false;
                                    break;
                                }
                            }
                            i++;
                        }
                        if (toProcess) {
                            if (validateBefore) {
                                Set<ConstraintViolation<INakedObject>> errors = validator.validate(o);
                                if (errors != null && !errors.isEmpty()) {
                                    it.remove();
                                    continue;
                                }
                                try {
                                    refreshManyToOneLinkedWithId(o, id, em);
                                    em.persist(o);
                                } catch (Exception e) {
                                    it.remove();
                                    continue;
                                }
                            } else {
                                refreshManyToOneLinkedWithId(o, id, em);
                                em.persist(o);
                            }
                            id = getId(o, ids);
                            res.put(id, o);
                            it.remove();
                        }
                    }
                }
            }
        }
        Map<String, Set<com.hiperf.common.ui.shared.util.Id>> toDelete = toPersist
                .getRemovedObjectsIdsByClassName();
        if (toDelete != null) {
            for (String className : toDelete.keySet()) {
                Set<com.hiperf.common.ui.shared.util.Id> ids = toDelete.get(className);
                Class<?> clazz = Class.forName(className);
                Map<Field, Field> toRemove = null;
                if (ids != null && !ids.isEmpty()) {
                    com.hiperf.common.ui.shared.util.Id id = ids.iterator().next();
                    if (id.getFieldValues().size() > 1) {
                        toRemove = new HashMap<Field, Field>();
                        Field[] fields = clazz.getDeclaredFields();
                        for (Field f : fields) {
                            if (f.isAnnotationPresent(ManyToOne.class)) {
                                Field[] ff = f.getType().getDeclaredFields();
                                for (Field lf : ff) {
                                    OneToMany ann = lf.getAnnotation(OneToMany.class);
                                    if (ann != null && ann.targetEntity() != null
                                            && ann.targetEntity().equals(clazz)) {
                                        toRemove.put(f, lf);
                                    }
                                }
                            }
                        }
                        // TODO : manage annotations on the getters...
                    }
                }
                for (com.hiperf.common.ui.shared.util.Id id : ids) {
                    INakedObject no = getObject(clazz, id, em);
                    if (no != null) {
                        if (toRemove != null && !toRemove.isEmpty()) {
                            for (Entry<Field, Field> e : toRemove.entrySet()) {
                                Field f = e.getKey();
                                Field ff = e.getValue();
                                boolean b1 = false;
                                boolean b2 = false;
                                if (!f.isAccessible()) {
                                    f.setAccessible(true);
                                    b1 = true;
                                }
                                if (!ff.isAccessible()) {
                                    ff.setAccessible(true);
                                    b2 = true;
                                }
                                ((Collection) ff.get(f.get(no))).remove(no);
                                if (b1)
                                    f.setAccessible(false);
                                if (b2)
                                    ff.setAccessible(false);
                            }
                        } else {
                            // TODO : manage annotations on the getters...
                        }
                        em.remove(no);
                    }
                }
            }
        }
        Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>>> toUpdate = toPersist
                .getUpdatedObjects();
        if (toUpdate != null) {
            for (String className : toUpdate.keySet()) {
                Map<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>> map = toUpdate
                        .get(className);
                Class<?> clazz = Class.forName(className);
                Iterator<Entry<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>>> iterator = map
                        .entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>> entry = iterator
                            .next();
                    com.hiperf.common.ui.shared.util.Id id = entry.getKey();
                    INakedObject original = getObject(clazz, id, em);
                    Map<String, Serializable> updateMap = entry.getValue();
                    for (String att : updateMap.keySet()) {
                        Object object = updateMap.get(att);
                        if (object != null && object instanceof NakedObjectHandler) {
                            NakedObjectHandler oo = (NakedObjectHandler) object;
                            com.hiperf.common.ui.shared.util.Id objId = oo.getId();
                            if (generatedIdClasses.contains(oo.getClassName())
                                    && newIdByOldId.containsKey(objId.getFieldValues().get(0))) {
                                IdHolder newIds = newIdByOldId.get(objId.getFieldValues().get(0));
                                List<Object> idVals = new ArrayList<Object>(1);
                                idVals.add(newIds.getId());
                                List<String> idFields = new ArrayList<String>(1);
                                idFields.add(idsByClassName.get(oo.getClassName()).iterator().next().getName());
                                com.hiperf.common.ui.shared.util.Id newObjId = new com.hiperf.common.ui.shared.util.Id(
                                        idFields, idVals);
                                object = getObject(Class.forName(oo.getClassName()), newObjId, em);
                            } else {
                                object = getObject(Class.forName(oo.getClassName()), oo.getId(), em);
                            }
                        }
                        updateAttributeValue(className, original, att, object);
                    }
                    if (original instanceof IAuditable) {
                        IAuditable aud = (IAuditable) original;
                        aud.setModifyUser(userName);
                        aud.setModifyDate(new Date());
                    }
                    INakedObject o = null;
                    if (validateBefore) {
                        Set<ConstraintViolation<INakedObject>> errors = validator.validate(original);
                        if (errors != null && !errors.isEmpty()) {
                            iterator.remove();
                            continue;
                        }
                        try {
                            o = em.merge(original);
                            em.flush();
                        } catch (Exception e) {
                            iterator.remove();
                            continue;
                        }
                    } else
                        o = em.merge(original);

                    res.put(id, o);
                }
            }
        }
        processAddedManyToMany(toPersist, res, newIdByOldId, em);
        processRemovedManyToMany(toPersist, res, newIdByOldId, em);
        em.flush();
        return true;
    } catch (Exception e) {
        logger.log(Level.WARNING, "Exception", e);
        if (processExceptions) {
            processDbExceptions(locale, e);
            return false;
        } else
            throw new PersistenceException(e);
    }

}

From source file:it.webappcommon.lib.jsf.AbstractPageBase.java

/**
 * Metodo che permette di ordinare, in ordine crescente o decrescente in
 * base ad ascending, un arraylist di oggetti di qualsiasi tipo in base al
 * parametro column. In particolare, con la reflection, viene gestito
 * l'ordinamento per column se essa e' int, long, double, float, boolean,
 * String, Date, Integer. Se non e' di uno di questi tipi, l'ordinamento non
 * fa niente in quanto il compareTo del comparator definito all'interno del
 * metodo ritorna sempre 0. La column, va indicata, come sempre del resto,
 * senza il get o l'is davanti.//from  w w w. jav  a 2s . c  o  m
 * 
 * @param list
 *            ArrayList da ordinare
 * @param column
 *            Nome della colonna/propriet dell'oggetto in base alla quale
 *            effettuare l'ordinamento
 * @param ascending
 *            Booleano che specifica se l'ordinamento deve essere ascendente
 *            o meno
 */
public void sort(List list, final String column, final boolean ascending) {
    // TODO: Gestione di property a pi livelli: ad esempio
    // ElementBL.element.nome
    Comparator comparator = null;

    if ((column != null) && (!column.equals("")) && (list != null) && (list.size() > 0)) {

        final Class item_class = list.get(0).getClass();

        comparator = new Comparator() {

            public int compare(Object o1, Object o2) {

                PropertyDescriptor column_descriptor = null;
                Method read_method = null;
                Object obj1 = null;
                Object obj2 = null;
                Object resInvoke1 = null;
                Object resInvoke2 = null;
                Date date1 = null;
                Date date2 = null;
                String str1 = null;
                String str2 = null;
                Integer Int1 = null;
                Integer Int2 = null;
                Double Double1 = null;
                Double Double2 = null;
                Float Float1 = null;
                Float Float2 = null;
                int returnValue = 0;

                try {

                    if ((column == null) || (o1 == null) || (o2 == null)) {

                        /*
                         * In caso di non specificazione della colonna o di
                         * uno dei due oggetti ritorna 0, facendo in modo
                         * che l'ordinamento non ha alcun effetto
                         */
                        returnValue = 0;

                    } else {

                        /*
                         * Tenta di ottenere un property descriptor a
                         * partire dalla colonna
                         */
                        try {

                            column_descriptor = new PropertyDescriptor(column, item_class);
                            read_method = column_descriptor.getReadMethod();

                        } catch (Exception e) {

                            read_method = null;

                        }

                        if (read_method != null) {

                            obj1 = item_class.cast(o1);
                            obj2 = item_class.cast(o2);

                            /*
                             * Viene gestito l'ordinamento per String,
                             * Boolean, int
                             */
                            if (read_method.getReturnType() == int.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo primitivo int">
                                /*
                                 * Variabili di tipo primitivo e'
                                 * impossibile che siano NULL
                                 */
                                str1 = read_method.invoke(obj1).toString();
                                str2 = read_method.invoke(obj2).toString();

                                int int1 = Integer.parseInt(str1);
                                int int2 = Integer.parseInt(str2);

                                if (ascending) {

                                    if (int1 < int2) {
                                        returnValue = -1;
                                    } else if (int1 > int2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                } else {

                                    if (int1 > int2) {
                                        returnValue = -1;
                                    } else if (int1 < int2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == long.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo primitivo long">
                                /*
                                 * Variabili di tipo primitivo e'
                                 * impossibile che siano NULL
                                 */
                                str1 = read_method.invoke(obj1).toString();
                                str2 = read_method.invoke(obj2).toString();

                                long lng1 = Long.parseLong(str1);
                                long lng2 = Long.parseLong(str2);

                                if (ascending) {

                                    if (lng1 < lng2) {
                                        returnValue = -1;
                                    } else if (lng1 > lng2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                } else {

                                    if (lng1 > lng2) {
                                        returnValue = -1;
                                    } else if (lng1 < lng2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == double.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo primitivo double">
                                /*
                                 * Variabili di tipo primitivo e'
                                 * impossibile che siano NULL
                                 */
                                str1 = read_method.invoke(obj1).toString();
                                str2 = read_method.invoke(obj2).toString();

                                double dbl1 = Double.parseDouble(str1);
                                double dbl2 = Double.parseDouble(str2);

                                if (ascending) {

                                    if (dbl1 < dbl2) {
                                        returnValue = -1;
                                    } else if (dbl1 > dbl2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                } else {

                                    if (dbl1 > dbl2) {
                                        returnValue = -1;
                                    } else if (dbl1 < dbl2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == float.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo primitivo float">
                                /*
                                 * Variabili di tipo primitivo e'
                                 * impossibile che siano NULL
                                 */
                                str1 = read_method.invoke(obj1).toString();
                                str2 = read_method.invoke(obj2).toString();

                                float flt1 = Float.parseFloat(str1);
                                float flt2 = Float.parseFloat(str2);

                                if (ascending) {

                                    if (flt1 < flt2) {
                                        returnValue = -1;
                                    } else if (flt1 > flt2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                } else {

                                    if (flt1 > flt2) {
                                        returnValue = -1;
                                    } else if (flt1 < flt2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == Float.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo object Float">
                                /*
                                 * Variabili di tipo object e' impossibile
                                 * che siano NULL
                                 */
                                /*
                                 * Pu essere che la propriet degli
                                 * oggetti sia NULL. In quel caso il
                                 * toString() genera errore se non gestito.
                                 * Se resInvoke1 oppure resInvoke2 sono
                                 * NULL, anche le rispettive conversioni in
                                 * interi lo devono essere
                                 */
                                resInvoke1 = read_method.invoke(obj1);
                                resInvoke2 = read_method.invoke(obj2);
                                if (resInvoke1 != null) {
                                    Float1 = (Float) resInvoke1;
                                }
                                if (resInvoke2 != null) {
                                    Float2 = (Float) resInvoke2;
                                }

                                if (ascending) {

                                    if ((Float1 != null) && (Float2 != null)) {
                                        returnValue = Float1.compareTo(Float2);
                                    } else if ((Float1 == null) && (Float2 != null)) {
                                        returnValue = -1;
                                    } else if ((Float1 != null) && (Float2 == null)) {
                                        returnValue = 1;
                                    } else if ((Float1 == null) && (Float2 == null)) {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((Float1 != null) && (Float2 != null)) {
                                        returnValue = Float2.compareTo(Float1);
                                    } else if ((Float1 != null) && (Float2 == null)) {
                                        returnValue = -1;
                                    } else if ((Float1 == null) && (Float2 != null)) {
                                        returnValue = 1;
                                    } else if ((Float1 == null) && (Float2 == null)) {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == boolean.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo primitivo boolean">
                                /*
                                 * Variabili di tipo primitivo e'
                                 * impossibile che siano NULL
                                 */
                                str1 = read_method.invoke(obj1).toString();
                                str2 = read_method.invoke(obj2).toString();

                                boolean bool1 = Boolean.parseBoolean(str1);
                                boolean bool2 = Boolean.parseBoolean(str2);

                                if (ascending) {

                                    if ((!bool1) && (bool2)) {
                                        returnValue = -1;
                                    } else if ((bool1) && (!bool2)) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((bool1) && (!bool2)) {
                                        returnValue = -1;
                                    } else if ((!bool1) && (bool2)) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == String.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo object String">
                                /*
                                 * Pu essere che la propriet degli
                                 * oggetti sia NULL. In quel caso il
                                 * toString() genera errore se non gestito.
                                 * Se resInvoke1
                                 * 
                                 * oppure resInvoke2 sono NULL, anche le
                                 * rispettive conversioni in stringa lo
                                 * devono essere
                                 */
                                resInvoke1 = read_method.invoke(obj1);
                                resInvoke2 = read_method.invoke(obj2);
                                if (resInvoke1 != null) {
                                    str1 = resInvoke1.toString().toUpperCase();
                                }
                                if (resInvoke2 != null) {
                                    str2 = resInvoke2.toString().toUpperCase();
                                }

                                if (ascending) {

                                    if ((str1 != null) && (str2 != null)) {
                                        returnValue = str1.compareTo(str2);
                                    } else if ((str1 == null) && (str2 != null)) {
                                        returnValue = -1;
                                    } else if ((str1 != null) && (str2 == null)) {
                                        returnValue = 1;
                                    } else if ((str1 == null) && (str2 == null)) {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((str1 != null) && (str2 != null)) {
                                        returnValue = str2.compareTo(str1);
                                    } else if ((str1 != null) && (str2 == null)) {
                                        returnValue = -1;
                                    } else if ((str1 == null) && (str2 != null)) {
                                        returnValue = 1;
                                    } else if ((str1 == null) && (str2 == null)) {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == Date.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo object Date">
                                /*
                                 * Pu essere che la propriet degli
                                 * oggetti sia NULL. In quel caso il
                                 * toString() genera errore se non gestito.
                                 * Se resInvoke1 oppure resInvoke2 sono
                                 * NULL, anche le rispettive conversioni in
                                 * date lo devono essere
                                 */
                                resInvoke1 = read_method.invoke(obj1);
                                resInvoke2 = read_method.invoke(obj2);
                                if (resInvoke1 != null) {
                                    date1 = (Date) resInvoke1;
                                }
                                if (resInvoke2 != null) {
                                    date2 = (Date) resInvoke2;
                                }

                                if (ascending) {

                                    if ((date1 != null) && (date2 != null)) {
                                        returnValue = date1.compareTo(date2);
                                    } else if ((date1 == null) && (date2 != null)) {
                                        returnValue = -1;
                                    } else if ((date1 != null) && (date2 == null)) {
                                        returnValue = 1;
                                    } else if ((date1 == null) && (date2 == null)) {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((date1 != null) && (date2 != null)) {
                                        returnValue = date2.compareTo(date1);
                                    } else if ((date1 != null) && (date2 == null)) {
                                        returnValue = -1;
                                    } else if ((date1 == null) && (date2 != null)) {
                                        returnValue = 1;
                                    } else if ((date1 == null) && (date2 == null)) {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == Integer.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo object Integer">
                                /*
                                 * Pu essere che la propriet degli
                                 * oggetti sia NULL. In quel caso il
                                 * toString() genera errore se non gestito.
                                 * Se resInvoke1 oppure resInvoke2 sono
                                 * NULL, anche le rispettive conversioni in
                                 * interi lo devono essere
                                 */
                                resInvoke1 = read_method.invoke(obj1);
                                resInvoke2 = read_method.invoke(obj2);
                                if (resInvoke1 != null) {
                                    Int1 = (Integer) resInvoke1;
                                }
                                if (resInvoke2 != null) {
                                    Int2 = (Integer) resInvoke2;
                                }

                                if (ascending) {

                                    if ((Int1 != null) && (Int2 != null)) {
                                        returnValue = Int1.compareTo(Int2);
                                    } else if ((Int1 == null) && (Int2 != null)) {
                                        returnValue = -1;
                                    } else if ((Int1 != null) && (Int2 == null)) {
                                        returnValue = 1;
                                    } else if ((Int1 == null) && (Int2 == null)) {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((Int1 != null) && (Int2 != null)) {
                                        returnValue = Int2.compareTo(Int1);
                                    } else if ((Int1 != null) && (Int2 == null)) {
                                        returnValue = -1;
                                    } else if ((Int1 == null) && (Int2 != null)) {
                                        returnValue = 1;
                                    } else if ((Int1 == null) && (Int2 == null)) {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == Double.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo object Double">
                                /*
                                 * Pu essere che la propriet degli
                                 * oggetti sia NULL. In quel caso il
                                 * toString() genera errore se non gestito.
                                 * Se resInvoke1 oppure resInvoke2 sono
                                 * NULL, anche le rispettive conversioni in
                                 * interi lo devono essere
                                 */
                                resInvoke1 = read_method.invoke(obj1);
                                resInvoke2 = read_method.invoke(obj2);
                                if (resInvoke1 != null) {
                                    Double1 = (Double) resInvoke1;
                                }
                                if (resInvoke2 != null) {
                                    Double2 = (Double) resInvoke2;
                                }

                                if (ascending) {

                                    if ((Double1 != null) && (Double2 != null)) {
                                        returnValue = Double1.compareTo(Double2);
                                    } else if ((Double1 == null) && (Double2 != null)) {
                                        returnValue = -1;
                                    } else if ((Double1 != null) && (Double2 == null)) {
                                        returnValue = 1;
                                    } else if ((Double1 == null) && (Double2 == null)) {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((Double1 != null) && (Double2 != null)) {
                                        returnValue = Double2.compareTo(Double1);
                                    } else if ((Double1 != null) && (Double2 == null)) {
                                        returnValue = -1;
                                    } else if ((Double1 == null) && (Double2 != null)) {
                                        returnValue = 1;
                                    } else if ((Double1 == null) && (Double2 == null)) {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            }

                        } else {

                            /*
                             * Nel caso in cui non ci sia il metodo get
                             * della colonna passata, ritorna 0, facendo in
                             * modo che l'ordinamento non ha alcun effetto
                             */
                            returnValue = 0;

                        }

                    }

                } catch (Exception e) {

                    /*
                     * In caso d'errore in Comparator ritorna 0, facendo in
                     * modo che l'ordinamento non ha alcun effetto
                     */

                    returnValue = 0;

                } finally {

                    /* Clean-up oggetti */
                    column_descriptor = null;
                    read_method = null;
                    obj1 = null;
                    obj2 = null;
                    resInvoke1 = null;
                    resInvoke2 = null;
                    date1 = null;
                    date2 = null;
                    str1 = null;
                    str2 = null;
                    Int1 = null;
                    Int2 = null;
                    Float1 = null;
                    Float2 = null;

                }

                return returnValue;

            }
        };

        if (comparator != null) {
            Collections.sort(list, comparator);
        }

    }

    comparator = null;

}

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. ja  v a  2  s  . co  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.dell.asm.asmcore.asmmanager.app.rest.ServiceTemplateService.java

public static <M> void merge(M target, M source) {
    try {/*from   w  w  w . ja  v  a  2s.  c o  m*/
        final BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());

        // Iterate over all the attributes
        for (final PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            // Only copy writable attributes
            if (descriptor.getWriteMethod() != null) {
                final Object originalValue = descriptor.getReadMethod().invoke(target);
                // Only copy values values where the destination values is null
                if (originalValue == null) {
                    final Object defaultValue = descriptor.getReadMethod().invoke(source);
                    descriptor.getWriteMethod().invoke(target, defaultValue);
                }
            }
        }
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public String replaceFile(String fileClass, String fileNameField, String fileStorageField, String fileName,
        FileItem fileItem, String existingId) throws PersistenceException {
    String idField = getIdFieldFromFileStorageClass(fileClass);
    boolean error = false;
    TransactionContext tc = null;/*  w w  w.  j  a  v  a  2  s .c om*/
    Object id = null;
    PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(fileClass);

    try {
        id = getFileId(existingId, idField, pds);
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        Object o;
        Class<?> clazz = Class.forName(fileClass);
        o = em.find(clazz, id);
        for (PropertyDescriptor pd : pds) {
            if (fileNameField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileName);
            } else if (fileStorageField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileItem.get());
            }
        }
        em.merge(o);

        tx.commit();
        //idsByClassName.get(fileClass).iterator().next().getReadMethod().invoke(o, new Object[0]);
    } catch (Exception e) {
        error = true;
        logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
        try {
            if (tc != null)
                tc.rollback();
        } catch (Exception ee) {
        }
    } finally {
        if (tc != null) {
            if (!error)
                close(tc);
            else
                tc.close();
        }
    }
    if (error) {
        try {
            tc = createTransactionalContext();
            EntityManager em = tc.getEm();
            ITransaction tx = tc.getTx();
            tx.begin();
            Class<?> clazz = Class.forName(fileClass);
            em.createQuery("delete from " + fileClass + " o where o." + idField + " = :id")
                    .setParameter("id", id).executeUpdate();
            Object newDoc = clazz.newInstance();
            for (PropertyDescriptor pd : pds) {
                if (fileNameField.equals(pd.getName())) {
                    pd.getWriteMethod().invoke(newDoc, fileName);
                } else if (fileStorageField.equals(pd.getName())) {
                    pd.getWriteMethod().invoke(newDoc, fileItem.get());
                }
            }
            em.persist(newDoc);
            tx.commit();
            for (PropertyDescriptor pd : pds) {
                if (idField.equals(pd.getName())) {
                    existingId = pd.getReadMethod().invoke(newDoc, new String[0]).toString();
                    break;
                }
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
            try {
                if (tc != null)
                    tc.rollback();
            } catch (Exception ee) {
            }
            throw new PersistenceException(e.getMessage(), e);
        } finally {
            if (tc != null)
                close(tc);
        }
    }

    return existingId;
}