requestToObject

[code]
/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */
    package br.com.projeto.controller;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;

/**
*

  • @author pirm
    */
    public class UtilJavaBean {

    public static Object requestToObject(Class classe, HttpServletRequest request) {
    Object object = null;
    try {
    object = classe.getConstructor().newInstance();
    } catch (Exception ex) {
    Logger.getLogger(UtilJavaBean.class.getName()).log(Level.SEVERE, null, ex);
    }

     Enumeration<String> enumerationStringParameterNames = request.getParameterNames();
     while (enumerationStringParameterNames.hasMoreElements()) {
         String stringParameterName = enumerationStringParameterNames.nextElement();
         StringBuilder stringBuilderField = new StringBuilder();
         for (int i = 0; i < stringParameterName.length(); i++) {
             stringBuilderField.append(stringParameterName.charAt(i));
             if (stringBuilderField.toString().equals(classe.getSimpleName())) {
                 /*
                  * Quando o nome do stringParameterName for igual ao nome da Class
                  */
                 stringBuilderField = new StringBuilder();
                 Object objectReturned = object;
                 for (int j = (i + 2); j < stringParameterName.length(); j++) {
                     char c = stringParameterName.charAt(j);
                     if (c != '.') {
                         stringBuilderField.append(c);
                     } else {
                         /*
                          * É UM OBJETO
                          */
                         objectReturned = parameterNameToObject(true, objectReturned, stringBuilderField.toString(), stringParameterName, request);
                         stringBuilderField = new StringBuilder();
                     }
                 }
                 /*
                  * É UM ATRIBUTO
                  */
                 parameterNameToObject(false, objectReturned, stringBuilderField.toString(), stringParameterName, request);
             }
         }
     }
     return object;
    

    }

    private static Object parameterNameToObject(boolean isObject, Object object, String stringField, String parameterName, HttpServletRequest request) {
    if (isObject) {
    /*
    * É UM OBJETO JAVABEAN
    /
    Object objectAttribute = javaBeanGetFieldValue(object, stringField);
    if (objectAttribute == null) {
    //System.out.println(“Objecto é nulo … criando objeto !”);
    Object objectOut = fieldToObject(object, stringField);
    parceFieldValue(object, stringField, objectOut);
    return objectOut;
    } else {
    //System.out.println(“Objecto não é nulo … retornando objeto através do método”);
    return javaBeanGetFieldValue(object, stringField);
    }
    } else {
    /

    * É UM ATRIBUTO
    */
    String[] arrayStringAttributeValue = request.getParameterValues(parameterName);
    parceFieldValue(object, stringField, arrayStringAttributeValue);
    }
    return null;
    }

    public static Object javaBeanGetFieldValue(Object object, String stringField) {
    StringBuilder stringBuilderGet = new StringBuilder();
    stringBuilderGet.append(“get”);
    for (int i = 0; i < stringField.length(); i++) {
    if (i == 0) {
    Character c = stringField.charAt(i);
    stringBuilderGet.append(c.toString().toUpperCase());
    } else {
    stringBuilderGet.append(stringField.charAt(i));
    }
    }
    StringBuilder stringBuilderIs = new StringBuilder();
    stringBuilderIs.append(“is”);
    for (int i = 0; i < stringField.length(); i++) {
    if (i == 0) {
    Character c = stringField.charAt(i);
    stringBuilderIs.append(c.toString().toUpperCase());
    } else {
    stringBuilderIs.append(stringField.charAt(i));
    }
    }
    Method[] arrayMethod = object.getClass().getDeclaredMethods();
    for (Method method : arrayMethod) {
    if (method.getName().equals(stringBuilderGet.toString())) {
    try {
    //System.out.println(“usando metodo … " + stringBuilderGet + " para pegar o valor”);
    return object.getClass().getDeclaredMethod(stringBuilderGet.toString()).invoke(object);
    } catch (Exception ex) {
    Logger.getLogger(UtilJavaBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    } else if (method.getName().equals(stringBuilderIs.toString())) {
    try {
    //System.out.println(“usando metodo … " + stringBuilderIs + " para pegar o valor”);
    return object.getClass().getDeclaredMethod(stringBuilderIs.toString()).invoke(object);
    } catch (Exception ex) {
    Logger.getLogger(UtilJavaBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    }
    }
    return null;
    }

    public static void javaBeanSetFieldValue(Object object, String stringField, Object objectValue) {
    StringBuilder stringBuilderMethod = new StringBuilder();
    stringBuilderMethod.append(“set”);
    for (int i = 0; i < stringField.length(); i++) {
    if (i == 0) {
    Character c = stringField.charAt(i);
    stringBuilderMethod.append(c.toString().toUpperCase());
    } else {
    stringBuilderMethod.append(stringField.charAt(i));
    }
    }
    Method[] arrayMethod = object.getClass().getDeclaredMethods();
    Class classField = null;
    for (Method method : arrayMethod) {
    if (method.getName().equals(stringBuilderMethod.toString())) {
    classField = method.getParameterTypes()[0];
    }
    }
    try {
    object.getClass().getDeclaredMethod(stringBuilderMethod.toString(), classField).invoke(object, objectValue);
    } catch (Exception ex) {
    Logger.getLogger(UtilJavaBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    }

    private static Object fieldToObject(Object object, String stringField) {
    Field[] arrayField = object.getClass().getDeclaredFields();
    for (Field field : arrayField) {
    if (field.getName().equals(stringField)) {
    try {
    Class classField = field.getType();
    if (classField.equals(List.class)) {
    classField = ArrayList.class;
    } else if (classField.equals(Map.class)) {
    classField = HashMap.class;
    } else if (classField.equals(Set.class)) {
    classField = HashSet.class;
    }
    return classField.getConstructor().newInstance();
    } catch (Exception ex) {
    Logger.getLogger(UtilJavaBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    }
    }
    return null;
    }

    private static void parceFieldValue(Object object, String stringField, Object objectValue) {
    StringBuilder stringBuilderMethod = new StringBuilder();
    stringBuilderMethod.append(“set”);
    for (int i = 0; i < stringField.length(); i++) {
    if (i == 0) {
    Character c = stringField.charAt(i);
    stringBuilderMethod.append(c.toString().toUpperCase());
    } else {
    stringBuilderMethod.append(stringField.charAt(i));
    }
    }
    Method[] arrayMethod = object.getClass().getDeclaredMethods();
    for (Method method : arrayMethod) {
    if (method.getName().equals(stringBuilderMethod.toString())) {
    try {
    String stringClassField = method.getParameterTypes()[0].getSimpleName();
    if (stringClassField.equals(“byte”) || stringClassField.equals(“Byte”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    String stringValue = arrayStringValue[0];
    javaBeanSetFieldValue(object, stringField, Byte.parseByte(stringValue));
    }
    } else if (stringClassField.equals(“short”) || stringClassField.equals(“Short”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    String stringValue = arrayStringValue[0];
    javaBeanSetFieldValue(object, stringField, Short.parseShort(stringValue));
    }
    } else if (stringClassField.equals(“int”) || stringClassField.equals(“Integer”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    String stringValue = arrayStringValue[0];
    javaBeanSetFieldValue(object, stringField, Integer.parseInt(stringValue));
    }
    } else if (stringClassField.equals(“long”) || stringClassField.equals(“Long”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    String stringValue = arrayStringValue[0];
    javaBeanSetFieldValue(object, stringField, Long.parseLong(stringValue));
    }
    } else if (stringClassField.equals(“float”) || stringClassField.equals(“Float”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    String stringValue = arrayStringValue[0];
    javaBeanSetFieldValue(object, stringField, Float.parseFloat(stringValue));
    }
    } else if (stringClassField.equals(“double”) || stringClassField.equals(“Double”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    String stringValue = arrayStringValue[0];
    javaBeanSetFieldValue(object, stringField, Double.parseDouble(stringValue));
    }
    } else if (stringClassField.equals(“char”) || stringClassField.equals(“Character”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    String stringValue = arrayStringValue[0];
    javaBeanSetFieldValue(object, stringField, stringValue.charAt(0));
    }
    } else if (stringClassField.equals(“boolean”) || stringClassField.equals(“Boolean”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    String stringValue = arrayStringValue[0];
    javaBeanSetFieldValue(object, stringField, Boolean.parseBoolean(stringValue));
    }
    } else if (stringClassField.equals(“String”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    String stringValue = arrayStringValue[0];
    if (arrayStringValue.length > 1) {
    StringBuilder stringBuilder1 = new StringBuilder();
    for (int i = 0; i < arrayStringValue.length; i++) {
    if (i != (arrayStringValue.length - 1)) {
    stringBuilder1.append(arrayStringValue[i]).append(",");
    } else {
    stringBuilder1.append(arrayStringValue[i]);
    }
    }
    stringValue = stringBuilder1.toString();
    }
    javaBeanSetFieldValue(object, stringField, stringValue);
    }
    } else if (stringClassField.equals(“byte[]”) || stringClassField.equals(“Byte[]”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    byte[] array = new byte[arrayStringValue.length];
    for (int i = 0; i < arrayStringValue.length; i++) {
    array[i] = Byte.parseByte(arrayStringValue[i]);
    }
    javaBeanSetFieldValue(object, stringField, array);
    }
    } else if (stringClassField.equals(“short[]”) || stringClassField.equals(“Short[]”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    short[] array = new short[arrayStringValue.length];
    for (int i = 0; i < arrayStringValue.length; i++) {
    array[i] = Short.parseShort(arrayStringValue[i]);
    }
    javaBeanSetFieldValue(object, stringField, array);
    }
    } else if (stringClassField.equals(“int[]”) || stringClassField.equals(“Integer[]”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    int[] array = new int[arrayStringValue.length];
    for (int i = 0; i < arrayStringValue.length; i++) {
    array[i] = Integer.parseInt(arrayStringValue[i]);
    }
    javaBeanSetFieldValue(object, stringField, array);
    }
    } else if (stringClassField.equals(“long[]”) || stringClassField.equals(“Long[]”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    long[] array = new long[arrayStringValue.length];
    for (int i = 0; i < arrayStringValue.length; i++) {
    array[i] = Long.parseLong(arrayStringValue[i]);
    }
    javaBeanSetFieldValue(object, stringField, array);
    }
    } else if (stringClassField.equals(“float[]”) || stringClassField.equals(“Float[]”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    float[] array = new float[arrayStringValue.length];
    for (int i = 0; i < arrayStringValue.length; i++) {
    array[i] = Float.parseFloat(arrayStringValue[i]);
    }
    javaBeanSetFieldValue(object, stringField, array);
    }
    } else if (stringClassField.equals(“double[]”) || stringClassField.equals(“Double[]”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    double[] array = new double[arrayStringValue.length];
    for (int i = 0; i < arrayStringValue.length; i++) {
    array[i] = Double.parseDouble(arrayStringValue[i]);
    }
    javaBeanSetFieldValue(object, stringField, array);
    }
    } else if (stringClassField.equals(“char[]”) || stringClassField.equals(“Character[]”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    char[] array = new char[arrayStringValue.length];
    for (int i = 0; i < arrayStringValue.length; i++) {
    array[i] = arrayStringValue[i].charAt(0);
    }
    javaBeanSetFieldValue(object, stringField, array);
    }
    } else if (stringClassField.equals(“boolean[]”) || stringClassField.equals(“Boolean[]”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    boolean[] array = new boolean[arrayStringValue.length];
    for (int i = 0; i < arrayStringValue.length; i++) {
    array[i] = Boolean.parseBoolean(arrayStringValue[i]);
    }
    javaBeanSetFieldValue(object, stringField, array);
    }
    } else if (stringClassField.equals(“String[]”)) {
    javaBeanSetFieldValue(object, stringField, clearArray((String[]) objectValue));
    } else if (stringClassField.equals(“List”) || stringClassField.equals(“ArrayList”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    List list = new ArrayList();
    list.addAll(Arrays.asList(arrayStringValue));
    javaBeanSetFieldValue(object, stringField, list);
    }
    } else if (stringClassField.equals(“Set”) || stringClassField.equals(“HashSet”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    Set set = new HashSet();
    for (String string : arrayStringValue) {
    set.add(string);
    }
    javaBeanSetFieldValue(object, stringField, set);
    }
    } else if (stringClassField.equals(“Map”) || stringClassField.equals(“HashMap”)) {
    String[] arrayStringValue = clearArray((String[]) objectValue);
    if (arrayStringValue != null) {
    Map map = new HashMap();
    for (int i = 0; i < arrayStringValue.length; i++) {
    map.put(i, arrayStringValue[i]);
    }
    javaBeanSetFieldValue(object, stringField, map);
    }
    } else {
    javaBeanSetFieldValue(object, stringField, objectValue);
    }
    } catch (Exception ex) {
    Logger.getLogger(UtilJavaBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    }
    }
    }

    private static String[] clearArray(String[] arrayString) {
    List listString = new ArrayList();
    for (String string : arrayString) {
    if (string != null && (string.length() > 0)) {
    listString.add(string.trim());
    }
    }
    if (!listString.isEmpty()) {
    String[] arrayStringOut = new String[listString.size()];
    for (int intIndex = 0; intIndex < arrayStringOut.length; intIndex++) {
    arrayStringOut[intIndex] = listString.get(intIndex);
    }
    return arrayStringOut;
    } else {
    return null;
    }
    }

    public static void beanToBean(T t1, T t2) {
    if (t1.getClass().getName().equals(t2.getClass().getName())) {
    Field[] arrayField = t1.getClass().getDeclaredFields();
    for (int intIndex = 0; intIndex < arrayField.length; intIndex++) {
    javaBeanSetFieldValue(t2, arrayField[intIndex].getName(), javaBeanGetFieldValue(t1, arrayField[intIndex].getName()));
    }
    }
    }
    }[/code]