Example usage for java.lang Class getDeclaredField

List of usage examples for java.lang Class getDeclaredField

Introduction

In this page you can find the example usage for java.lang Class getDeclaredField.

Prototype

@CallerSensitive
public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.

Usage

From source file:com.stratio.qa.specs.CommonG.java

/**
 * Saves the value in the attribute in class extending CommonG.
 *
 * @param element attribute in class where to store the value
 * @param value   value to be stored//from   w  ww  .j  a  va 2  s  .  co  m
 * @throws NoSuchFieldException exception
 * @throws SecurityException exception
 * @throws IllegalArgumentException exception
 * @throws IllegalAccessException exception
 * @throws InstantiationException exception
 * @throws ClassNotFoundException exception
 * @throws NoSuchMethodException exception
 * @throws InvocationTargetException exception
 */

public void setPreviousElement(String element, String value)
        throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException,
        InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
    Reflections reflections = new Reflections("com.stratio");
    Set classes = reflections.getSubTypesOf(CommonG.class);

    Object pp = (classes.toArray())[0];
    String qq = (pp.toString().split(" "))[1];
    Class<?> c = Class.forName(qq.toString());

    Field ff = c.getDeclaredField(element);
    ff.setAccessible(true);
    ff.set(null, value);
}

From source file:cern.c2mon.shared.common.datatag.address.impl.HardwareAddressImpl.java

/**
 * Create a HardwareAddress object from its XML representation.
 *
 * @param pElement DOM element containing the XML representation of a HardwareAddress object, as created by the
 *                 toConfigXML() method.
 * @throws RuntimeException if unable to instantiate the Hardware address
 * @see cern.c2mon.shared.common.datatag.address.HardwareAddress#toConfigXML()
 *//*  ww  w.j a v  a2  s.  c o  m*/
public final synchronized HardwareAddress fromConfigXML(Element pElement) {
    Class hwAddressClass = null;
    HardwareAddressImpl hwAddress = null;

    try {
        hwAddressClass = Class.forName(pElement.getAttribute("class"));
        hwAddress = (HardwareAddressImpl) hwAddressClass.newInstance();
    } catch (ClassNotFoundException cnfe) {
        cnfe.printStackTrace();
        throw new RuntimeException("Exception caught when instantiating a hardware address from XML", cnfe);
    } catch (IllegalAccessException iae) {
        iae.printStackTrace();
        throw new RuntimeException("Exception caught when instantiating a hardware address from XML", iae);
    } catch (InstantiationException ie) {
        ie.printStackTrace();
        throw new RuntimeException("Exception caught when instantiating a hardware address from XML", ie);
    }

    NodeList fields = pElement.getChildNodes();
    Node fieldNode = null;
    int fieldsCount = fields.getLength();
    String fieldName;
    String fieldValueString;
    String fieldTypeName = "";

    for (int i = 0; i < fieldsCount; i++) {
        fieldNode = fields.item(i);
        if (fieldNode.getNodeType() == Node.ELEMENT_NODE) {
            fieldName = fieldNode.getNodeName();

            if (fieldNode.getFirstChild() != null) {
                fieldValueString = fieldNode.getFirstChild().getNodeValue();
            } else {
                fieldValueString = "";
            }
            try {
                Field field = hwAddressClass.getDeclaredField(decodeFieldName(fieldName));
                fieldTypeName = field.getType().getName();

                if (fieldTypeName.equals("short")) {
                    field.setShort(hwAddress, Short.parseShort(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Short")) {
                    field.set(hwAddress, new Integer(Integer.parseInt(fieldValueString)));
                } else if (fieldTypeName.equals("int")) {
                    field.setInt(hwAddress, Integer.parseInt(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Integer")) {
                    field.set(hwAddress, new Integer(Integer.parseInt(fieldValueString)));
                } else if (fieldTypeName.equals("float")) {
                    field.setFloat(hwAddress, Float.parseFloat(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Float")) {
                    field.set(hwAddress, new Float(Float.parseFloat(fieldValueString)));
                } else if (fieldTypeName.equals("double")) {
                    field.setDouble(hwAddress, Double.parseDouble(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Double")) {
                    field.set(hwAddress, new Double(Double.parseDouble(fieldValueString)));
                } else if (fieldTypeName.equals("long")) {
                    field.setLong(hwAddress, Long.parseLong(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Long")) {
                    field.set(hwAddress, new Long(Long.parseLong(fieldValueString)));
                } else if (fieldTypeName.equals("byte")) {
                    field.setByte(hwAddress, Byte.parseByte(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Byte")) {
                    field.set(hwAddress, new Byte(Byte.parseByte(fieldValueString)));
                } else if (fieldTypeName.equals("char")) {
                    field.setChar(hwAddress, fieldValueString.charAt(0));
                } else if (fieldTypeName.equals("java.lang.Character")) {
                    field.set(hwAddress, new Character(fieldValueString.charAt(0)));
                } else if (fieldTypeName.equals("boolean")) {
                    field.setBoolean(hwAddress, Boolean.getBoolean(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Boolean")) {
                    field.set(hwAddress, new Boolean(Boolean.getBoolean(fieldValueString)));
                } else if (fieldTypeName.equals("java.util.HashMap")) {
                    field.set(hwAddress, SimpleXMLParser.domNodeToMap(fieldNode));
                } else if (field.getType().isEnum()) {
                    Object[] enumConstants = field.getType().getEnumConstants();
                    for (Object enumConstant : enumConstants) {
                        if (enumConstant.toString().equals(fieldValueString)) {
                            field.set(hwAddress, enumConstant);
                        }
                    }
                } else {
                    field.set(hwAddress, fieldValueString);
                }
            } catch (NoSuchFieldException nsfe) {
                String errorMsg = "fromConfigXML(...) - Error occured while parsing XML <HardwareAddress> tag. "
                        + "The following variable does not exist in " + hwAddressClass.toString() + ": \""
                        + decodeFieldName(fieldName) + "\"";
                log.error(errorMsg);
                throw new IllegalArgumentException(errorMsg);
            } catch (IllegalAccessException iae) {
                iae.printStackTrace();
                throw new RuntimeException(iae);
            } catch (NumberFormatException npe) {
                String errorMsg = "fromConfigXML(...) - Error occured while parsing XML <HardwareAddress> tag. Field \""
                        + fieldName + "\" shall not be empty since we expect a \"" + fieldTypeName
                        + "\" value. Please correct the XML configuration for " + hwAddressClass.toString();
                log.error(errorMsg);
                throw new IllegalArgumentException(errorMsg);
            }
        }
    }
    return hwAddress;
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

private Annotation[] getAnnotations(final PropertyDescriptor ppropertyDescription, final boolean useField) {
    final Class<?> clazz = this.beanHelper.getClazz();
    if (useField) {
        try {// w w  w  . j  av  a 2  s .co  m
            final Field field = clazz.getDeclaredField(ppropertyDescription.getPropertyName());
            return field.getAnnotations();
        } catch (final NoSuchFieldException ignore) { // NOPMD
            // Expected Case
        }
    } else {
        try {
            final Method method = clazz.getMethod(asGetter(ppropertyDescription));
            return method.getAnnotations();
        } catch (final NoSuchMethodException ignore) { // NOPMD
            // Expected Case
        }
    }
    return NO_ANNOTATIONS;
}

From source file:at.treedb.db.Base.java

/**
 * Updates only embedded data types of an entity.
 * //from ww  w. j a v  a2 s . c  o m
 * @param map
 *            map containing the changes
 * @param
 * @throws Exception
 */
public void simpleUpdate(UpdateMap map, boolean strict) throws Exception {
    Class<?> c = this.getClass();

    for (Enum<?> field : map.getMap().keySet()) {
        Update u = map.get(field);
        Field f = c.getDeclaredField(field.name());
        f.setAccessible(true);
        switch (u.getType()) {
        case STRING:
            f.set(this, u.getString());
            break;
        case DOUBLE:
            f.set(this, u.getDouble());
            break;
        case FLOAT:
            f.set(this, u.getFloat());
            break;
        case LONG:
            f.set(this, u.getLong());
            break;
        case INT:
            f.set(this, u.getInt());
            break;
        case LAZY_BINARY:
        case BINARY:
            f.set(this, u.getBinary());
            break;
        case BOOLEAN:
            f.set(this, u.getBoolean());
            break;
        case DATE:
            f.set(this, u.getDate());
            break;
        case ENUM:
            f.set(this, u.getEnum());
            break;
        case BIGDECIMAL:
            f.set(this, u.getBigDecimal());
            break;
        default:
            if (strict) {
                throw new Exception("Base.update(): Type not implemented!");
            }
        }
    }
}

From source file:at.treedb.db.Base.java

/**
 * Updates an entity.//from   ww  w  .j  a v  a  2 s  . co m
 * 
 * @param dao
 *            {@code DAOiface} (data access object)
 * @param user
 *            user who updates the entity
 * @param map
 *            map containing the changes
 * @throws Exception
 */
protected void update(DAOiface dao, User user, UpdateMap map) throws Exception {
    Class<?> c = this.getClass();

    for (Enum<?> field : map.getMap().keySet()) {
        Update u = map.get(field);
        Field f;
        try {
            f = c.getDeclaredField(field.name());
        } catch (java.lang.NoSuchFieldException e) {
            f = c.getSuperclass().getDeclaredField(field.name());
        }
        f.setAccessible(true);
        switch (u.getType()) {
        case STRING:
            f.set(this, u.getString());
            break;
        case DOUBLE:
            f.set(this, u.getDouble());
            break;
        case FLOAT:
            f.set(this, u.getFloat());
            break;
        case LONG:
            f.set(this, u.getLong());
            break;
        case INT:
            f.set(this, u.getInt());
            break;
        case LAZY_BINARY:
        case BINARY:
            f.set(this, u.getBinary());
            break;
        case BOOLEAN:
            f.set(this, u.getBoolean());
            break;
        case DATE:
            f.set(this, u.getDate());
            break;
        case ENUM:
            f.set(this, u.getEnum());
            break;
        case BIGDECIMAL:
            f.set(this, u.getBigDecimal());
            break;
        case ISTRING: {
            DBkey a = f.getAnnotation(DBkey.class);
            if (a == null || !a.value().equals(Istring.class)) {
                throw new Exception("Base.update(): Field type mismatch for an IString");
            }
            ArrayList<IstringDummy> list = u.getIstringDummy();
            // dao.flush();
            for (IstringDummy i : list) {
                Istring istr = null;
                int userId = user != null ? user.getHistId() : 0;
                if (f.getInt(this) == 0) {
                    istr = Istring.create(dao, domain, user, this.getCID(), i.getText(), i.getLanguage());
                } else {
                    istr = Istring.saveOrUpdate(dao, domain, userId, f.getInt(this), i.getText(),
                            i.getLanguage(), i.getCountry(), this.getCID());
                }
                // only for CI make a reference form IString to the owner
                if (this instanceof CI) {
                    istr.setCI(this.getHistId());
                }
                if (f.getInt(this) == 0) {
                    f.setInt(this, istr.getHistId());
                    dao.update(this);
                }
            }
            break;
        }
        case ISTRING_DELETE: {
            DBkey a = f.getAnnotation(DBkey.class);
            if (a == null || !a.value().equals(Istring.class)) {
                throw new Exception("Base.update(): Field type mismatch for an IString");
            }
            ArrayList<IstringDummy> list = u.getIstringDummy();
            for (IstringDummy i : list) {
                if (i.getCountry() == null && i.getLanguage() == null) {
                    Istring.delete(dao, user, f.getInt(this));
                } else if (i.getCountry() == null && i.getLanguage() != null) {
                    Istring.delete(dao, user, f.getInt(this), i.getLanguage());
                } else if (i.getCountry() != null && i.getLanguage() != null) {
                    Istring.delete(dao, user, f.getInt(this), i.getLanguage(), i.getCountry());
                }
            }
            break;
        }
        case IMAGE: {
            DBkey a = f.getAnnotation(DBkey.class);
            if (a == null || !a.value().equals(Image.class)) {
                throw new Exception("Base.update(): Field type mismatch for an Image");
            }
            Image.update(dao, user, f.getInt(this), u.getUpdateMap());
            break;
        }
        case IMAGE_DUMMY: {
            DBkey a = f.getAnnotation(DBkey.class);
            if (a == null || !a.value().equals(Image.class)) {
                throw new Exception("Base.update(): Field type mismatch for an Image");
            }
            int id = f.getInt(this);
            if (id == 0) {
                ImageDummy idummy = u.getImageDummy();
                if (this instanceof User) {
                    User uuser = (User) this;
                    Image i = Image.create(dao, null, user, "userImage_" + Base.getRandomLong(),
                            idummy.getData(), idummy.getMimeType(), idummy.getLicense());
                    uuser.setImage(i.getHistId());
                } else if (this instanceof DBcategory) {
                    DBcategory cat = (DBcategory) this;
                    Image i = Image.create(dao, null, user, "catImage_" + Base.getRandomLong(),
                            idummy.getData(), idummy.getMimeType(), idummy.getLicense());
                    cat.setIcon(i.getHistId());
                } else {
                    throw new Exception("Base.update(): ImageDummy for this relationship is't defined");
                }
            } else {
                Image.update(dao, user, id, u.getImageDummy().getImageUpdateMap());
            }
            break;
        }
        case IMAGE_DELETE: {
            DBkey a = f.getAnnotation(DBkey.class);
            if (a == null || !a.value().equals(Image.class)) {
                throw new Exception("Base.update(): Field type mismatch for an Image");
            }
            Image.delete(dao, user, f.getInt(this));
            f.setInt(this, 0);
            break;
        }
        default:
            throw new Exception("Base.update(): Type not implemented!");
        }
    }
}

From source file:de.innovationgate.utils.WGUtils.java

/**
 * Returns the field reflection object of the field of the given name.
 * This method will find fields of any scope in the given class and all superclasses. 
 * @param theClass The class searched for the field
 * @param name The field name/*from w  w  w.  j  a v a 2  s .  c  o m*/
 * @return The field reflection object or null if the field does not exist
 */
public static Field getClassField(Class<?> theClass, String name) {

    Field field = null;
    while (true) {
        try {
            field = theClass.getDeclaredField(name);
        } catch (Exception e) {
        }

        if (field != null) {
            return field;
        }

        if (theClass.getSuperclass() != null) {
            theClass = theClass.getSuperclass();
        } else {
            return null;
        }
    }

}

From source file:at.treedb.db.Base.java

/**
 * Checks the map containing the changes. Redundant update entries will be
 * removed.//from w  w w .  j a va  2  s  .  co m
 * 
 * @param map
 *            map containing the changes
 * @throws Exception
 */
protected void check(UpdateMap map) throws Exception {
    Class<?> c = this.getClass();
    Enum<?>[] list = map.getMap().keySet().toArray(new Enum[map.getMap().keySet().size()]);
    for (Enum<?> field : list) {
        Update u = map.get(field);
        Field f;
        try {
            f = c.getDeclaredField(field.name());
        } catch (java.lang.NoSuchFieldException e) {
            f = c.getSuperclass().getDeclaredField(field.name());
        }
        f.setAccessible(true);
        switch (u.getType()) {
        case STRING:
            String value = u.getString();
            String s = (String) f.get(this);
            if ((value == null && s == null) || (s != null && value != null && s.equals(value))) {
                map.remove(field);
            }
            break;
        case DOUBLE:
            if (u.getDouble() == (Double) f.get(this)) {
                map.remove(field);
            }
            break;
        case LONG:
            if (u.getLong() == (Long) f.get(this)) {
                map.remove(field);
            }
            break;
        case INT:
            if (u.getInt() == (Integer) f.get(this)) {
                map.remove(field);
            }
            break;
        case BINARY:
            byte[] a = (byte[]) f.get(this);
            byte[] b = u.getBinary();
            if ((a == null && b == null) || (a != null && b != null && Arrays.equals(a, b))) {
                map.remove(field);
            }
            break;
        case BOOLEAN:
            if (u.getBoolean() == (Boolean) f.get(this)) {
                map.remove(field);
            }
            break;
        case DATE:
            Date dvalue = u.getDate();
            Date d = (Date) f.get(this);
            if ((dvalue == null && d == null) || (d != null && dvalue != null && d.equals(dvalue))) {
                map.remove(field);
            }
            break;
        case ENUM:
            if (u.getEnum() == (Enum<?>) f.get(this)) {
                map.remove(field);
            }
            break;
        case BIGDECIMAL:
            if (u.getBigDecimal().equals((BigDecimal) f.get(this))) {
                map.remove(field);
            }
            // no check for these types
        case IMAGE:
        case ISTRING_DELETE:
        case ISTRING:
        case IMAGE_DELETE:
        case IMAGE_DUMMY:
            break;
        default:
            throw new Exception("Base.check(): Type not implemented: " + u.getType().toString());
        }
    }
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

private void mapRequestToObj(HashMap<String, Object> data, Class expectedClass, Object obj) throws Exception {
    if (obj == null) {
        throw new ApplicationException("mapRequestToObj called on NULL obj", "ERR9001");
    }//w  w w  .  j  a v  a 2  s. co  m

    try {
        Method versionMethod = expectedClass.getMethod("getVersion", (Class<?>[]) null);
        Long objVersion = (Long) versionMethod.invoke(obj, (Object[]) null);
        String clientVersion = (String) data.get("version");
        if (objVersion != null && clientVersion != null) {
            try {
                long clientVersionLong = Long.parseLong(clientVersion);
                if (!objVersion.equals(clientVersionLong)) {
                    throw makeApplicationException("Can't save object", "ERR9016", (Serializable[]) null);
                }
            } catch (NumberFormatException nfe) {
                // Version from client isn't number - ignore
            }
        }
    } catch (NoSuchMethodException nme) {
        // No version control
    }

    Method[] methods = expectedClass.getMethods();
    for (Method m : methods) {
        Class<?>[] paramTypes = m.getParameterTypes();

        Class persistentClass = null;
        if (paramTypes.length == 1) {
            if (paramTypes[0].getAnnotation(Entity.class) != null) {
                persistentClass = paramTypes[0];
            } else if (paramTypes[0].getAnnotation(Embeddable.class) != null) {
                persistentClass = paramTypes[0];
            }
        }
        ServiceDescription srvParam = paramTypes.length == 1 ? findServiceByClassName(paramTypes[0].getName())
                : null;
        if ((m.getName().startsWith(SET_PREFIX) && paramTypes.length == 1
                && (paramTypes[0].isAssignableFrom(String.class) || paramTypes[0].equals(Integer.class)
                        || paramTypes[0].equals(Integer.TYPE) || paramTypes[0].equals(Long.class)
                        || paramTypes[0].equals(Long.TYPE) || paramTypes[0].equals(Float.class)
                        || paramTypes[0].equals(Float.TYPE) || paramTypes[0].equals(Boolean.class)
                        || paramTypes[0].equals(Boolean.TYPE) || paramTypes[0].equals(Double.class)
                        || paramTypes[0].equals(Double.TYPE) || paramTypes[0].equals(Date.class)
                        || Enum.class.isAssignableFrom(paramTypes[0])
                        || (srvParam != null && srvParam.getFindById() != null) || persistentClass != null))
                || (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0
                        && (Set.class.isAssignableFrom(m.getReturnType())
                                || List.class.isAssignableFrom(m.getReturnType())))) {
            String fldName;
            if (m.getName().startsWith(GET_TRANSLATE)) {
                fldName = m.getName().substring(GET_TRANSLATE_LENGTH, GET_TRANSLATE_LENGTH + 1).toLowerCase()
                        + m.getName().substring(GET_TRANSLATE_LENGTH + 1);
            } else {
                fldName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4);
            }
            Object value = data.get(fldName);
            if (value == null) {
                fldName = m.getName().substring(3);
                value = data.get(fldName);
            }
            if (value != null) {
                Object typedVal;
                String val = null;
                if (value instanceof String) {
                    val = (String) value;
                }
                log.log(Level.FINER, "        value = " + value);
                if (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0
                        && (Set.class.isAssignableFrom(m.getReturnType())
                                || List.class.isAssignableFrom(m.getReturnType()))) {
                    log.log(Level.FINER, "GET");

                    String attrName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4);
                    Type[] actualTypeArguments = null;
                    Class iterClass = expectedClass;
                    while (iterClass != null) {
                        try {
                            Field field = iterClass.getDeclaredField(attrName);
                            ParameterizedType genericType = (ParameterizedType) field.getGenericType();
                            actualTypeArguments = genericType.getActualTypeArguments();
                            break;
                        } catch (NoSuchFieldException nsfe) {
                            // do nothing iterate again
                        }
                        iterClass = iterClass.getSuperclass();
                        iterClass = iterClass.equals(Object.class) ? null : iterClass;
                    }

                    if (actualTypeArguments != null && actualTypeArguments.length == 1
                            && actualTypeArguments[0] instanceof Class) {
                        Class assocClass = (Class) actualTypeArguments[0];
                        ServiceDescription assocService = findServiceByClassName(assocClass.getName());
                        Collection dbValueSet = (Collection) m.invoke(obj, (Object[]) null);
                        if (value == null || !(value instanceof HashMap)) {
                            log.log(Level.FINE, "No data for db property {0}", attrName);
                        } else if (assocService != null) {
                            HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value;

                            ArrayList<Object> removeIt = new ArrayList<Object>();
                            Iterator dbIterator = dbValueSet.iterator();
                            while (dbIterator.hasNext()) {
                                Object dbVal = dbIterator.next();
                                String dbValId = getIdFromObj(dbVal);

                                if (dbValId != null) {
                                    boolean wasMatchingGuiVal = false;
                                    ArrayList<String> removeKeys = new ArrayList<String>();
                                    for (String key : guiValueMap.keySet()) {
                                        Object object = guiValueMap.get(key);
                                        if (object instanceof HashMap) {
                                            Object guiValue = ((HashMap<String, Object>) object).get("id");
                                            if (guiValue.equals(dbValId)) {
                                                removeKeys.add(key);
                                                wasMatchingGuiVal = true;
                                                mapRequestToObj((HashMap<String, Object>) guiValue, assocClass,
                                                        dbVal);
                                                break;
                                            }
                                        } else if (object instanceof String) {
                                            // Association
                                            if (dbValId.equals(object)) {
                                                removeKeys.add(key);
                                                wasMatchingGuiVal = true;
                                            }
                                        } else {
                                            log.log(Level.WARNING, "Wrong object type from GUI under key {0}",
                                                    key);
                                        }
                                    }
                                    // Remove processed elements
                                    // Direct remove is firing concurrent modification exception
                                    for (String removeKey : removeKeys) {
                                        guiValueMap.remove(removeKey);
                                    }

                                    if (!wasMatchingGuiVal) {
                                        // Is not in list comming from GUI - delete
                                        removeIt.add(dbVal);
                                    }
                                } else {
                                    log.log(Level.WARNING, "No ID in object {0}", dbVal);
                                }
                            }
                            dbValueSet.removeAll(removeIt);

                            // Rest are new records
                            for (String key : guiValueMap.keySet()) {
                                Object object = guiValueMap.get(key);
                                if (object instanceof HashMap) {
                                    Object subObj = makeNewInstance(assocClass,
                                            (HashMap<String, Object>) object);
                                    mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj);
                                    dbValueSet.add(subObj);
                                } else if (object instanceof String) {
                                    // Association
                                    try {
                                        Long id = new Long((String) object);
                                        Object assocObj = assocService.getFindById().invoke(
                                                assocService.getInstance(), ServiceContextStore.get(), id);
                                        if (assocObj != null) {
                                            dbValueSet.add(assocObj);
                                        } else {
                                            log.log(Level.WARNING,
                                                    "Object with ID {0} not availabla via service {1}",
                                                    new Object[] { id, assocService.getName() });
                                        }
                                    } catch (Exception ex) {
                                        log.log(Level.WARNING, "No ID parsable from value {0} under key {1}",
                                                new Object[] { object, key });
                                    }
                                } else {
                                    log.log(Level.WARNING, "Wrong sub type {0}", attrName);
                                }
                            }
                        } else if (assocClass != null) {
                            HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value;

                            ArrayList<Object> removeIt = new ArrayList<Object>();
                            Iterator dbIterator = dbValueSet.iterator();
                            while (dbIterator.hasNext()) {
                                Object dbVal = dbIterator.next();
                                String dbValId = getIdFromObj(dbVal);

                                if (dbValId != null) {
                                    Object matchingGuiVal = null;
                                    for (String key : guiValueMap.keySet()) {
                                        Object object = guiValueMap.get(key);
                                        if (object instanceof HashMap) {
                                            HashMap<String, Object> guiVal = (HashMap<String, Object>) object;
                                            if (dbValId.equals(guiVal.get("id"))) {
                                                guiValueMap.remove(key);
                                                matchingGuiVal = guiVal;
                                                break;
                                            }
                                        } else {
                                            log.log(Level.WARNING, "Wrong object type from GUI under key {0}",
                                                    key);
                                        }
                                    }
                                    if (matchingGuiVal != null) {
                                        // Coming from GUI - update
                                        mapRequestToObj((HashMap<String, Object>) matchingGuiVal, assocClass,
                                                dbVal);
                                    } else {
                                        // Not in GUI - delete
                                        removeIt.add(dbVal);
                                    }
                                } else {
                                    log.log(Level.WARNING, "No ID in object {0}", dbVal);
                                }
                            }
                            dbValueSet.removeAll(removeIt);

                            // Rest are new records
                            for (String key : guiValueMap.keySet()) {
                                Object object = guiValueMap.get(key);
                                if (object instanceof HashMap) {
                                    Object subObj = makeNewInstance(assocClass,
                                            (HashMap<String, Object>) object);
                                    mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj);
                                    dbValueSet.add(subObj);
                                } else {
                                    log.log(Level.WARNING, "Wrong sub type {0}", attrName);
                                }
                            }
                        }
                    } else {
                        log.log(Level.WARNING, "No DB mapping or not of collection type: {0}", attrName);
                    }
                    typedVal = null;
                } else if (paramTypes[0].isAssignableFrom(String.class)) {
                    typedVal = val;
                } else if (paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE)) {
                    typedVal = Integer.parseInt(val);
                } else if (paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE)) {
                    typedVal = Long.parseLong(val);
                } else if (paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE)) {
                    typedVal = Double.parseDouble(val);
                } else if (paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE)) {
                    typedVal = Float.parseFloat(val);
                } else if (paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE)) {
                    typedVal = "true".equalsIgnoreCase(val) || "t".equalsIgnoreCase(val)
                            || "y".equalsIgnoreCase(val);
                } else if (paramTypes[0].isAssignableFrom(Date.class)) {
                    typedVal = dateFormat.parse(val);
                } else if (Enum.class.isAssignableFrom(paramTypes[0])) {
                    try {
                        Method fromValueMethod = paramTypes[0].getMethod("fromValue", String.class);
                        typedVal = fromValueMethod.invoke(null, val);
                    } catch (Exception ex) {
                        typedVal = null;
                    }

                    try {
                        if (typedVal == null) {
                            Method valueOfMethod = paramTypes[0].getMethod("valueOf", String.class);
                            typedVal = valueOfMethod.invoke(null, val);
                        }
                    } catch (Exception ex) {
                        typedVal = null;
                    }
                } else if (persistentClass != null && persistentClass.equals(FileUpload.class)) {
                    FileItem fileItem = uploadServlet.getFileItem(sessionId.get(), fldName, val);
                    if (fileItem != null) {
                        typedVal = fileUploadService.uploadFile(ServiceContextStore.get(), fileItem.getName(),
                                fileItem.getContentType(), fileItem.getInputStream());
                    } else {
                        typedVal = null;
                    }
                } else if (srvParam != null && srvParam.getFindById() != null) {
                    if (value instanceof HashMap) {
                        HashMap<String, Object> embeddedObj = (HashMap<String, Object>) value;
                        typedVal = srvParam.getFindById().invoke(srvParam.getInstance(),
                                ServiceContextStore.get(), new Long((String) embeddedObj.get("id")));
                        mapRequestToObj(embeddedObj, srvParam.getExpectedClass(), typedVal);
                    } else {
                        try {
                            Long parsedId = new Long(val);
                            typedVal = srvParam.getFindById().invoke(srvParam.getInstance(),
                                    ServiceContextStore.get(), parsedId);
                        } catch (NumberFormatException nfe) {
                            // wrong value
                            typedVal = null;
                        }
                    }
                } else if (persistentClass != null) {
                    String getMethodName = "g" + m.getName().substring(1);
                    try {
                        Method getMethod = obj.getClass().getMethod(getMethodName, (Class[]) null);
                        typedVal = getMethod.invoke(obj, (Object[]) null);
                    } catch (NoSuchMethodException nsme) {
                        typedVal = null;
                    }
                    if (typedVal == null) {
                        typedVal = makeNewInstance(persistentClass, (HashMap<String, Object>) value);
                    }
                    mapRequestToObj((HashMap<String, Object>) value, typedVal.getClass(), typedVal);
                } else {
                    log.log(Level.WARNING, "Can't convert value for: {0}.{1} ({2})", new Object[] {
                            expectedClass.getName(), m.getName(),
                            (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) });
                    typedVal = null;
                }
                if (typedVal != null) {
                    m.invoke(obj, typedVal);
                }
            }
        } else if (m.getName().startsWith(SET_PREFIX)) {
            log.log(Level.WARNING, "Unusable setter method: {0}.{1} ({2})",
                    new Object[] { expectedClass.getName(), m.getName(),
                            (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) });
        }
    }
}

From source file:gemlite.core.internal.db.DBSynchronizer.java

/**
 * Set the key column values in {@link PreparedStatement} for a primary key
 * based update or delete operation.//from  w  ww  . ja va2  s.co  m
 */
protected void setKeysInPrepStatement(final Object keyValues, final List<String> keyFields, Class valueClass,
        final PreparedStatement ps, int startIndex) throws SQLException {
    final int numKeyCols = keyFields.size();
    if (logger.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder().append("DBSynchronizer::setKeysInPrepStatement: setting key {");
        for (int col = 0; col < numKeyCols; col++) {
            if (col > 1) {
                sb.append(',');
            }
            // ????
            // ??
            String field = keyFields.get(col);
            try {
                Map map = PropertyUtils.describe(keyValues);
                Object val = map.get(field);
                sb.append(val);
            } catch (Exception e) {
                throw new SQLException(e);
            }
        }
        sb.append('}');
        logger.info(sb.toString());
    }

    for (int colIndex = 0; colIndex < numKeyCols; colIndex++, startIndex++) {
        String field = keyFields.get(colIndex);
        try {
            Map map = PropertyUtils.describe(keyValues);
            Object val = map.get(field);
            String type = valueClass.getDeclaredField(field).getType().getName();
            helper.setColumnInPrepStatement(type, val, ps, this, startIndex);
        } catch (Exception e) {
            throw new SQLException(e);
        }
    }
}