Mostrando entradas con la etiqueta dto. Mostrar todas las entradas
Mostrando entradas con la etiqueta dto. Mostrar todas las entradas

jueves, 1 de agosto de 2013

Utileria. Convertir un DTO en String.


Aveces hace falta para sacar en consola o en el log, los valores de un objeto

    /**
     * Transforma un DTO a cadena.
     * @param obj
     * @return
     * @throws SecurityException 
     * @throws NoSuchMethodException 
     */
    public static String dtoToString(Object obj){
    if(obj!=null){
    StringBuilder out = new StringBuilder();
        out.append("[");
        Field[] props = obj.getClass().getDeclaredFields();
        for(Field prop:props){
    try{
    String methodName= "get";
        methodName += String.valueOf(prop.getName().charAt(0)).toUpperCase();
    methodName += prop.getName().substring(1);
    Method getter = obj.getClass().getMethod(methodName);
    Object value = getter.invoke(obj, new Object[0]);
        out.append(prop.getName()+":"+value);
        out.append(", ");
    }catch(Exception e){
    }    
        }
        out.append("]");
        return out.toString();
    }else{
    return "No dto object";
    }
    }


Utileria. Para poblar un pojo con datos provenientes de un resultSet.

Esta es una clase utileria para poblar un objeto DTO con datos provenientes de un resultset en java

package com.inditex.isu4.core.services.factory;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * Factoria de construccion de DTO's
 * @author etereum
 *
 */
public class DTOFactory{

private static Logger log = Logger.getLogger(DTOFactory.class);

/**
* Contrulle la lista de DTO's apartir del tipo de dto que se pase como parametro.
* @param dtoType
* @param rs
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SecurityException
*/
public static <T> List<T> getDTOListFromRS(T dtoType, ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException{
log.debug("getDTOListFromRS....");
List<T> dataList = new ArrayList<T>();
Constructor[] factories = dtoType.getClass().getDeclaredConstructors();
Constructor factory = null;
for (int i = 0; i < factories.length; i++) {
factory = factories[i];
   if (factory.getGenericParameterTypes().length == 0)
break;
}
while(rs.next()){
   Object dto = factory.newInstance();
   Field[] props = dto.getClass().getDeclaredFields();
  for(Field prop:props){
 try{
Object value = rs.getObject(prop.getName());
  String methodName= "set";
      methodName += String.valueOf(prop.getName().charAt(0)).toUpperCase();
  methodName += prop.getName().substring(1);
  Class<?> classType =null;
  if(value ==null){
  continue;
  }else if(value instanceof String){
      classType=String.class;
  }else if(value instanceof Integer){
      classType=Integer.class;
  }else if(value instanceof Date){
  classType=Date.class;
  }
  Method setter = dto.getClass().getMethod(methodName, classType);
  setter.invoke(dto, value);
 }catch(Exception e){
 log.warn("No fue posible asignar el valor. ["+prop+"]");
   log.warn("Exception.getDTOListFromRS", e);
   }
           }
dataList.add((T)dto);
}
log.debug("getDTOListFromRS.OK.");
return dataList;
}

}