Commits

Ning Sun  committed c9da435

use jackson as json backend

  • Participants
  • Parent commits 787b001
  • Branches 0.5-dev

Comments (0)

Files changed (9)

 		</dependency>
 		
 		<dependency>
-		    <groupId>net.sf.json-lib</groupId>
-		    <artifactId>json-lib</artifactId>
-		    <version>2.3</version>
-            <classifier>jdk15</classifier>
-		</dependency> 
+		    <groupId>org.codehaus.jackson</groupId>
+            <artifactId>jackson-mapper-asl</artifactId>
+            <version>1.5.3</version>
+		</dependency>
+
+        <dependency>
+            <groupId>org.codehaus.jackson</groupId>
+            <artifactId>jackson-core-asl</artifactId>
+            <version>1.5.3</version>
+        </dependency>
 		
 		<dependency>
 		    <groupId>org.simpleframework</groupId>

File src/main/java/info/sunng/yan/util/BeanConvertor.java

-/**
- * 
- */
-package info.sunng.yan.util;
-
-import java.io.StringWriter;
-import java.util.List;
-
-import net.sf.json.JSONArray;
-import net.sf.json.JSONObject;
-
-import org.apache.log4j.Logger;
-import org.ho.yaml.Yaml;
-import org.simpleframework.xml.Serializer;
-import org.simpleframework.xml.core.Persister;
-
-/**
- * @author Sun Ning/SNDA
- * @since Dec 21, 2009
- * 
- */
-public class BeanConvertor {
-	
-	private static Logger logger = Logger.getLogger(BeanConvertor.class);
-	
-	private BeanConvertor(){
-		
-	}
-
-    public static String serialize(Object o, String type){
-        if(type != null){
-			if(type.equalsIgnoreCase(HttpContentType.APPLICATION_XML)){
-				return BeanConvertor.toXML(o);
-			}
-
-			if(type.equalsIgnoreCase(HttpContentType.APPLICATION_JSON)){
-				return BeanConvertor.toJSONObject(o);
-			}
-
-			if(type.equalsIgnoreCase(HttpContentType.APPLICATION_YAML)){
-				return BeanConvertor.toYAML(o);
-			}
-		}
-		return o.toString();
-    }
-	
-	public static String toXML(Object o){
-		Serializer serializer = new Persister();
-		StringWriter sw = new StringWriter();
-		try {
-			serializer.write(o, sw);
-		} catch (Exception e) {
-			logger.error(e.getMessage(), e);
-		}
-		return sw.toString();
-	}
-	
-	public static String toJSONObject(Object o){
-		JSONObject json = JSONObject.fromObject(o);
-		return json.toString();
-	}
-	
-	public static String toJSONArray(List<?> data){
-		JSONArray json = JSONArray.fromObject(data);
-		return json.toString();
-	}
-	
-	public static String toYAML(Object o){
-		return Yaml.dump(o, true);
-	}
-
-}

File src/main/java/info/sunng/yan/util/ObjectSerializer.java

+/**
+ * 
+ */
+package info.sunng.yan.util;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.List;
+
+import org.codehaus.jackson.map.ObjectMapper;
+
+import org.apache.log4j.Logger;
+import org.ho.yaml.Yaml;
+import org.simpleframework.xml.Serializer;
+import org.simpleframework.xml.core.Persister;
+
+/**
+ * @author Sun Ning/SNDA
+ * @since Dec 21, 2009
+ * 
+ */
+public class ObjectSerializer {
+	
+	private static Logger logger = Logger.getLogger(ObjectSerializer.class);
+	
+	private ObjectSerializer(){
+		
+	}
+
+    private static ObjectMapper objectMapper = new ObjectMapper();
+
+    public static String serialize(Object o, String type) throws IOException{
+        if(type != null){
+			if(type.equalsIgnoreCase(HttpContentType.APPLICATION_XML)){
+				return ObjectSerializer.toXML(o);
+			}
+
+			if(type.equalsIgnoreCase(HttpContentType.APPLICATION_JSON)){
+				return ObjectSerializer.toJSONObject(o);
+			}
+
+			if(type.equalsIgnoreCase(HttpContentType.APPLICATION_YAML)){
+				return ObjectSerializer.toYAML(o);
+			}
+		}
+		return o.toString();
+    }
+	
+	public static String toXML(Object o){
+		Serializer serializer = new Persister();
+		StringWriter sw = new StringWriter();
+		try {
+			serializer.write(o, sw);
+		} catch (Exception e) {
+			logger.error(e.getMessage(), e);
+		}
+		return sw.toString();
+	}
+	
+	public static String toJSONObject(Object o) throws IOException{
+		return objectMapper.writeValueAsString(o);
+	}
+	
+	public static String toJSONArray(List<?> data) throws IOException{
+		return objectMapper.writeValueAsString(data);
+	}
+	
+	public static String toYAML(Object o){
+		return Yaml.dump(o, true);
+	}
+
+}

File src/main/java/info/sunng/yan/web/ProviderServlet.java

 
 import info.sunng.yan.captcha.CaptchaProviderService;
 import info.sunng.yan.model.ProviderInfoDTO;
-import info.sunng.yan.util.BeanConvertor;
+import info.sunng.yan.util.ObjectSerializer;
 import info.sunng.yan.util.HttpContentType;
 import info.sunng.yan.util.HttpUtil;
 
         List<ProviderInfoDTO> providers =
                 captchaProviderService.getEnabledProvidersInfo();
 
-        String json = BeanConvertor.toJSONArray(providers);
+        String json = ObjectSerializer.toJSONArray(providers);
 
         res.setContentType(HttpContentType.APPLICATION_JSON);
 

File src/main/java/info/sunng/yan/web/TicketServlet.java

 import info.sunng.yan.model.Ticket;
 import info.sunng.yan.model.Error;
 import info.sunng.yan.session.CaptchaSession;
-import info.sunng.yan.util.BeanConvertor;
+import info.sunng.yan.util.ObjectSerializer;
 import info.sunng.yan.util.HttpUtil;
 
 /**
 		if (!StringUtils.isEmpty(req.getParameter(YanParameters.IP))) {
 			ip = req.getParameter(YanParameters.IP);
 		} else {
-			HttpUtil.writeResponse(res, BeanConvertor.serialize(Error.PARAMETER_OMITTED(),
+			HttpUtil.writeResponse(res, ObjectSerializer.serialize(Error.PARAMETER_OMITTED(),
                         HttpUtil.getContentTypeAttr(req)));
 			return;
 		}
         }
 
         HttpUtil.writeResponse(res,
-				BeanConvertor.serialize(ticket, 
+				ObjectSerializer.serialize(ticket,
 						HttpUtil.getContentTypeAttr(req)));
 
 

File src/main/java/info/sunng/yan/web/ValidationServlet.java

 import info.sunng.yan.model.Error;
 import info.sunng.yan.model.ValidationResult;
 import info.sunng.yan.session.CaptchaSession;
-import info.sunng.yan.util.BeanConvertor;
+import info.sunng.yan.util.ObjectSerializer;
 import info.sunng.yan.util.GlobParser;
 import info.sunng.yan.util.HttpUtil;
 
 				YanParameters.APIKEY_KEY_NAME);
 				
 		if(StringUtils.isEmpty(req.getParameter(YanParameters.IP))){
-			HttpUtil.writeResponse(resp, BeanConvertor.serialize(Error.PARAMETER_OMITTED(),
+			HttpUtil.writeResponse(resp, ObjectSerializer.serialize(Error.PARAMETER_OMITTED(),
                     HttpUtil.getContentTypeAttr((HttpServletRequest)req)));
             return ;
 			
 		}
 		
 		if(StringUtils.isEmpty(req.getParameter(YanParameters.KEY))){
-			HttpUtil.writeResponse(resp, BeanConvertor.serialize(new ValidationResult(false, null),
+			HttpUtil.writeResponse(resp, ObjectSerializer.serialize(new ValidationResult(false, null),
                     HttpUtil.getContentTypeAttr((HttpServletRequest)req)));
 		}
 		
             if(!GlobParser.match(apiKeyEntry.getApikey(), model.getApiKey())){
                 ValidationResult result = new ValidationResult(false,
                         GlobalConfiguration.get("yan.message.apikeyMismatch"));
-                HttpUtil.writeResponse(resp, BeanConvertor.serialize(result,
+                HttpUtil.writeResponse(resp, ObjectSerializer.serialize(result,
                 		HttpUtil.getContentTypeAttr((HttpServletRequest)req)));
             	logger.info("APIKEY mismatch, App:"+appName+" IP:"+ip);
                 return ;
 
         ValidateHandler validator = captchaService.getValidatorByMode(model.getMode());
         if(validator.validate(model, code)){
-            HttpUtil.writeResponse(resp, BeanConvertor.serialize(
+            HttpUtil.writeResponse(resp, ObjectSerializer.serialize(
                     new ValidationResult(true, null),
                     HttpUtil.getContentTypeAttr((HttpServletRequest)req)));
             logger.info("TRUE, App:"+appName+" IP:"+ip);
         }else{
-            HttpUtil.writeResponse(resp, BeanConvertor.serialize(
+            HttpUtil.writeResponse(resp, ObjectSerializer.serialize(
                     new ValidationResult(false, null),
                     HttpUtil.getContentTypeAttr((HttpServletRequest)req)));
 			logger.info("FALSE, App:"+appName+" IP:"+ip);

File src/main/java/info/sunng/yan/web/apikey/APIKeyRSServlet.java

 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import net.sf.json.JSONObject;
-
 import org.apache.commons.io.IOUtils;
 
 import info.sunng.yan.apikey.APIKeyManager;
 import info.sunng.yan.model.ApiKeyEntry;
-import info.sunng.yan.util.BeanConvertor;
+import info.sunng.yan.util.ObjectSerializer;
 import info.sunng.yan.util.HttpUtil;
 import info.sunng.yan.web.YanParameters;
 import com.google.inject.Inject;
 import com.google.inject.Singleton;
+import java.util.HashMap;
+import java.util.Map;
+import javax.servlet.ServletConfig;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.map.type.TypeFactory;
 
 /**
  * Servlet implementation class APIKeyRSServlet
 public class APIKeyRSServlet extends HttpServlet {
 	private static final long serialVersionUID = 1L;
 
+    private ObjectMapper objectMapper;
+
 	@Inject
 	private APIKeyManager apiKeyManager;
 
 		super();
 	}
 
+    @Override
+    public void init(ServletConfig config) throws ServletException {
+        objectMapper = new ObjectMapper();
+    }
+
 	/**
 	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 	 *      response)
 			List<ApiKeyEntry> apiKeys = apiKeyManager.list();
 
 			response.setContentType(HttpContentType.APPLICATION_JSON);
-			HttpUtil.writeResponse(response, BeanConvertor.toJSONArray(apiKeys));
+			HttpUtil.writeResponse(response, ObjectSerializer.toJSONArray(apiKeys));
 			
 		} else {
 			ApiKeyEntry apiKeyEntry = apiKeyManager.getAppByKey(apiKey);
             
 			response.setContentType(HttpContentType.APPLICATION_JSON);
-			HttpUtil.writeResponse(response, BeanConvertor.toJSONObject(apiKeyEntry));			
+			HttpUtil.writeResponse(response, ObjectSerializer.toJSONObject(apiKeyEntry));
 		}
 	}
 
 	protected void doPut(HttpServletRequest request,
 			HttpServletResponse response) throws ServletException, IOException {
 		String jsonData = IOUtils.toString(request.getInputStream());
-		JSONObject object = JSONObject.fromObject(jsonData);
+        Map<String, String> input = objectMapper.readValue(jsonData,
+                TypeFactory.mapType(HashMap.class, String.class, String.class));
 		ApiKeyEntry entry = apiKeyManager.register(
-                object.getString(YanParameters.APP_NAME),
-				object.getString(YanParameters.DOMAIN));
+                input.get(YanParameters.APP_NAME),
+				input.get(YanParameters.DOMAIN));
 		response.setContentType(HttpContentType.APPLICATION_JSON);
-		HttpUtil.writeResponse(response, BeanConvertor.toJSONObject(entry));
+		HttpUtil.writeResponse(response, ObjectSerializer.toJSONObject(entry));
 	}
 
 	/**

File src/main/java/info/sunng/yan/web/apikey/ApiKeyFilter.java

 import info.sunng.yan.apikey.APIKeyService;
 import info.sunng.yan.model.ApiKeyEntry;
 import info.sunng.yan.model.Error;
-import info.sunng.yan.util.BeanConvertor;
+import info.sunng.yan.util.ObjectSerializer;
 import info.sunng.yan.util.HttpUtil;
 import info.sunng.yan.util.Util;
 import info.sunng.yan.web.YanParameters;
 						Util.isLocalhost(request.getRemoteAddr()));
 				
 				if(apiKeyEntry == null){
-					HttpUtil.writeResponse(response, BeanConvertor.serialize(
+					HttpUtil.writeResponse(response, ObjectSerializer.serialize(
 							Error.APIKEY_ERROR(), 
 							HttpUtil.getContentTypeAttr((HttpServletRequest)request)));
 					return;

File src/test/java/info/sunng/yan/util/SerializeUtilTest.java

  */
 package info.sunng.yan.util;
 
-import info.sunng.yan.util.BeanConvertor;
+import static org.junit.Assert.*;
+
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 
 import org.junit.Test;
 
 import info.sunng.yan.model.ApiKeyEntry;
+import java.util.HashMap;
+import java.util.Map;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.map.type.TypeFactory;
 
 
 /**
 public class SerializeUtilTest {
 	
 	@Test
-	public void testJsonArray(){
+	public void testJsonArray() throws IOException{
 		List<String> s = new ArrayList<String>();
 		s.add("a");
 		s.add("b");
 		
-		String json = BeanConvertor.toJSONArray(s);
+		String json = ObjectSerializer.toJSONArray(s);
 		System.out.println(json);
 		
 		List<ApiKeyEntry> s2 = new ArrayList<ApiKeyEntry>();
 		a.setAppName("JUnit Test");
 		s2.add(a);
 		
-		System.out.println(BeanConvertor.toJSONArray(s2));
+		System.out.println(ObjectSerializer.toJSONArray(s2));
 	}
 	
 	@Test
-	public void testJsonObject(){
-		System.out.println(BeanConvertor.toJSONObject(null));
+	public void testJsonObject() throws IOException{
+		System.out.println(ObjectSerializer.toJSONObject(null));
 	}
 
+    @Test
+    public void testReadObject() throws IOException {
+        String data = "{ \"appName\":\"helloworld\", \"domain\":\"sunng.info\"}";
+        Map<String, String> result = new ObjectMapper().readValue(
+                data, TypeFactory.mapType(HashMap.class, String.class, String.class));
+
+        assertEquals("helloworld", result.get("appName"));
+        assertEquals("sunng.info", result.get("domain"));
+    }
+
 }