package org.hwo.configuration; import static org.hwo.logging.Logging.log; import java.lang.reflect.Field; import java.util.Enumeration; import java.util.Hashtable; import java.util.LinkedList; import java.util.StringTokenizer; import org.hwo.ByteArrayHexlifier; public class ConfigurableObjects { public static Field[] getConfigurableAttributes(Class clazz){ LinkedList cfl = new LinkedList(); if (clazz.getAnnotation(ConfigurableObject.class)!=null){ Field[] fields = clazz.getDeclaredFields(); for (Field f: fields){ if (f.getAnnotation(ConfigurableAttribute.class)!=null){ f.setAccessible(true); cfl.add(f); } } if (clazz.getSuperclass()!=null){ for (Field f:getConfigurableAttributes(clazz.getSuperclass())) cfl.add(f); } } return cfl.toArray(new Field[0]); } public static Field[] getConfigurableAttributes(Object o){ return getConfigurableAttributes(o.getClass()); } public static String getValueAsString(Object value){ String s = value.toString(); return ByteArrayHexlifier.hexlify(s); } public static Object getValueFromString(String _value,Class type) throws ClassCastException{ String value = ByteArrayHexlifier.unhexlify(_value); if (type.equals(String.class)) return new String(value); if (type.equals(Integer.class)) return Integer.parseInt(value); if (type.equals(Float.class)) return Float.parseFloat(value); if (type.equals(Double.class)) return Double.parseDouble(value); if (type.equals(Boolean.class)) return Boolean.parseBoolean(value); if (type.isEnum()){ for (Object e:type.getEnumConstants()){ if (e.toString().equals(value)) return e; } } throw new ClassCastException(); } public static String getConfiguration(Object o){ if (IConfigurableObject.class.isInstance(o)) return ((IConfigurableObject)o).getConfiguration(); Field[] fields = getConfigurableAttributes(o); Hashtable values = new Hashtable(); for (Field f: fields){ try { String sv = getValueAsString(f.get(o)); if (sv != null){ values.put(f.getName(), sv); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } StringBuilder sb = new StringBuilder(); Enumeration keys = values.keys(); while (keys.hasMoreElements()){ String name = keys.nextElement(); sb.append(String.format("%s=%s", name, values.get(name))); if (keys.hasMoreElements()) sb.append(";"); } return sb.toString(); } public static void setConfiguration(Object o,String configuration){ StringTokenizer st = new StringTokenizer(configuration, ";"); LinkedList l = new LinkedList(); while (st.hasMoreTokens()){ String t = st.nextToken(); if ((l.peekLast()!=null)&&(l.peekLast().endsWith("\\"))){ String last = l.removeLast(); l.add(last.substring(0, last.length()-1) + ";" + t); } else { l.addFirst(t); } } Hashtable hash = new Hashtable(); for (int n=0;n