1 package org.snipsnap.serialization; 2 3 import java.util.Map ; 4 import java.util.HashMap ; 5 import java.util.Iterator ; 6 import org.radeox.util.Service; 7 import org.radeox.util.logging.Logger; 8 9 10 public class LabelSerializerFactory { 11 12 13 public LabelSerializerFactory(int outputFormat) { 14 m_outputFormat = String.valueOf(outputFormat); 15 } 16 17 public LabelSerializer createSerializerFor(String labelType) { 18 Class serClass = getClassFor(labelType); 19 if (serClass == null) 20 return null; 21 try { 22 LabelSerializer serializer = (LabelSerializer)serClass.newInstance(); 23 return serializer; 24 } 25 catch (Exception e) { } 26 return null; 27 } 28 29 34 public static synchronized void addDefaultLabelSerializer(String labelType, int format, Class cls) { 35 if (s_defaultClasses == null) 36 s_defaultClasses = new HashMap (); 37 Class [] interfaces = cls.getInterfaces(); 38 boolean ok = false; 39 for (int i = 0; i < interfaces.length; i++) { 40 if (interfaces[i].getName() == "org.snipsnap.serialization.LabelSerializer;") { 41 ok = true; 42 break; 43 } 44 } 45 if (!ok) { 46 Logger.debug("LabelSerializerFactory::addDefaultLabelSerializer: supplied Class does not implement LabelSerializer interface"); 47 return; 48 } 49 s_defaultClasses.put(getKey(labelType, String.valueOf(format)), cls); 50 } 51 52 private Class getClassFor(String labelType) { 53 if (m_classMap.isEmpty()) loadClasses(); 55 String key = getKey(labelType, m_outputFormat); 56 Class cls = (Class )m_classMap.get(key); 57 if (cls == null && s_defaultClasses != null) 58 cls = (Class )s_defaultClasses.get(key); 59 return cls; 60 } 61 62 private void loadClasses() { 63 m_classMap.clear(); 64 try { 65 Iterator it = Service.providers(Class.forName("org.snipsnap.serialization.LabelSerializer")); 67 while (it.hasNext()) { 68 try { 69 LabelSerializer ls = (LabelSerializer)it.next(); 70 int outputFormat = ls.getOutputFormat(); 71 Iterator typesIt = ls.getSupportedLabelTypes().iterator(); 72 while (typesIt.hasNext()) { 73 String key = getKey((String )typesIt.next(), m_outputFormat); 74 m_classMap.put(key, ls.getClass()); 75 } 76 } 77 catch (Exception e) { } 79 } 80 } 81 catch (ClassNotFoundException e) { } 82 } 83 84 private static String getKey(String type, String m_outputFormat) { 85 return m_outputFormat + "_" + type; 86 } 87 88 private String m_outputFormat; 89 private static Map s_defaultClasses = null; 90 private Map m_classMap = new HashMap (); 91 } 92 | Popular Tags |