]> git.argeo.org Git - lgpl/argeo-commons.git/blob - JsonObjectFactoryImpl.java
a2f0cc4fa0e97f1490457df01a8e4d85dcec8753
[lgpl/argeo-commons.git] / JsonObjectFactoryImpl.java
1 package org.argeo.server.json;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 import org.apache.commons.logging.Log;
7 import org.apache.commons.logging.LogFactory;
8 import org.argeo.ArgeoException;
9 import org.codehaus.jackson.map.ObjectMapper;
10 import org.osgi.framework.BundleContext;
11 import org.springframework.beans.factory.InitializingBean;
12 import org.springframework.osgi.context.BundleContextAware;
13 import org.springframework.osgi.util.BundleDelegatingClassLoader;
14
15 public class JsonObjectFactoryImpl implements JsonObjectFactory,
16 BundleContextAware, InitializingBean {
17 private final static Log log = LogFactory
18 .getLog(JsonObjectFactoryImpl.class);
19
20 private BundleContext bundleContext;
21 private ClassLoader classLoader = getClass().getClassLoader();
22
23 private ObjectMapper objectMapper = new ObjectMapper();
24 private Map<String, Class<?>> supportedTypes = new HashMap<String, Class<?>>();
25
26 public Boolean supports(String type) {
27 if (supportedTypes.containsKey(type))
28 return true;
29
30 return loadClass(type) != null ? true : false;
31 }
32
33 @SuppressWarnings("unchecked")
34 public <T> T readValue(String type, String str) {
35 final Class<?> clss;
36 if (supportedTypes.containsKey(type))
37 clss = supportedTypes.get(type);
38 else {
39 clss = loadClass(type);
40 if (clss == null)
41 throw new ArgeoException("Cannot find type " + type);
42 }
43
44 try {
45 return (T) objectMapper.readValue(str, clss);
46 } catch (Exception e) {
47 throw new ArgeoException("Cannot deserialize " + str
48 + " (type=" + type + ")", e);
49 }
50 }
51
52 public void setSupportedTypes(Map<String, Class<?>> supportedTypes) {
53 this.supportedTypes = supportedTypes;
54 }
55
56 protected Class<?> loadClass(String type) {
57 try {
58 return classLoader.loadClass(type);
59 } catch (ClassNotFoundException e) {
60 if (log.isDebugEnabled())
61 log.debug("BundleDelegatingClassLoader.loadClass failed: " + e);
62 }
63
64 return null;
65 }
66
67 public void setBundleContext(BundleContext bundleContext) {
68 this.bundleContext = bundleContext;
69 }
70
71 public void afterPropertiesSet() throws Exception {
72 classLoader = BundleDelegatingClassLoader
73 .createBundleClassLoaderFor(bundleContext.getBundle());
74 }
75 }