001package es.ucm.fdi.gaia.jcolibri.connector.plaintextutils; 002 003import java.math.BigDecimal; 004import java.net.URL; 005import java.text.SimpleDateFormat; 006import java.util.Date; 007 008import org.apache.logging.log4j.LogManager; 009 010import es.ucm.fdi.gaia.jcolibri.connector.TypeAdaptor; 011 012/** 013 * Converts data types between its textual representation and Java types. By 014 * default it only manages a few data types: 015 * <ul> 016 * <li>BigDecimal 017 * <li>Boolean 018 * <li>Byte 019 * <li>Date 020 * <li>Double 021 * <li>Float 022 * <li>Int 023 * <li>Long 024 * <li>Object 025 * <li>Short 026 * <li>String 027 * <li>URL 028 * </ul> 029 * Even so, developers can store any class in the text file if the class 030 * implements the jcolibri.connectors.TypeAdaptor interface. 031 * 032 * @author Juan Antonio Recio Garc�a 033 * @version 2.0 034 * @see TypeAdaptor 035 */ 036public class PlainTextTypeConverter { 037 038 /** 039 * Coverts a string representation of the data in an object. 040 * 041 * @param data 042 * string representation of the data. 043 * @param type 044 * type of the data. 045 * @return the object trepresented by data and type. 046 */ 047 @SuppressWarnings({ "unchecked", "rawtypes" }) 048 public static Object convert(String data, Class type) { 049 050 try { 051 052 if(data == null || data.equals("null")) 053 return null; 054 else 055 if (type.equals(BigDecimal.class)) 056 return new BigDecimal(data); 057 else if (type.equals(Boolean.class)) 058 return new Boolean(data); 059 else if (type.equals(Byte.class)) 060 return new Byte(data); 061 else if (type.equals(Date.class)) 062 return new SimpleDateFormat().parse(data); 063 else if (type.equals(Double.class)) 064 return new Double(data); 065 else if (type.equals(Float.class)) 066 return new Float(data); 067 else if (type.equals(Integer.class)) 068 return new Integer(data); 069 else if (type.equals(Long.class)) 070 return new Long(data); 071 else if (type.equals(Object.class)) 072 return data; 073 else if (type.equals(Short.class)) 074 return new Short(data); 075 else if (type.equals(String.class)) 076 return data; 077 else if (type.equals(URL.class)) 078 return data; 079 else if (Enum.class.isAssignableFrom(type)) 080 return Enum.valueOf(type, data); 081 else { 082 TypeAdaptor adaptor = (TypeAdaptor)type.newInstance(); 083 adaptor.fromString(data); 084 return adaptor; 085 } 086 087 088 } catch (Exception e) { 089 LogManager.getLogger(PlainTextTypeConverter.class).error("Error converting types: " + e.getMessage()); 090 } 091 092 return null; 093 } 094}