Author: doll
Date: Tue May 20 13:26:06 2008
New Revision: 658412

URL: http://svn.apache.org/viewvc?rev=658412&view=rev
Log:
Reduced the ugly JSON output code for abdera significantly. 
Deleted the 2 unused classes and collapsed the JSONWriter code into JSONFilter. 
There is no longer a named writer that we add in by hand - rather that code is 
just in the filter class eliminating a bunch of redirection. This is still a 
very weird integration so hopefully there is more simplification we can do. 

All json restful tests still pass. 


Removed:
    
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/json/JSONStream.java
    
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/json/JSONUtil.java
    
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/json/JSONWriter.java
Modified:
    
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/RestServerServlet.java
    
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/AbstractSocialEntityCollectionAdapter.java
    
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/json/JSONFilter.java
    
incubator/shindig/trunk/java/social-api/src/test/java/org/apache/shindig/social/abdera/AbstractLargeRestfulTests.java

Modified: 
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/RestServerServlet.java
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/RestServerServlet.java?rev=658412&r1=658411&r2=658412&view=diff
==============================================================================
--- 
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/RestServerServlet.java
 (original)
+++ 
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/RestServerServlet.java
 Tue May 20 13:26:06 2008
@@ -19,12 +19,10 @@
 package org.apache.shindig.social;
 
 import org.apache.shindig.common.servlet.GuiceServletContextListener;
-import org.apache.shindig.social.abdera.json.JSONWriter;
 
 import com.google.inject.Injector;
 import org.apache.abdera.protocol.server.Provider;
 import org.apache.abdera.protocol.server.servlet.AbderaServlet;
-import org.apache.abdera.writer.NamedWriter;
 
 import javax.servlet.ServletConfig;
 import javax.servlet.ServletContext;
@@ -32,7 +30,6 @@
 import javax.servlet.UnavailableException;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
-import java.util.Map;
 import java.util.logging.Logger;
 
 /**
@@ -49,7 +46,8 @@
   private static Logger logger =
       Logger.getLogger(RestServerServlet.class.getName());
 
-  @Override public void init() {
+  @Override
+  public void init() {
     // Abdera provider stuff
     manager = createServiceManager();
     provider = createProvider();
@@ -65,22 +63,6 @@
       e.printStackTrace();
       return null;
     }
-
-    //setup my NamedWriter for "json"
-    getAbdera().getConfiguration().addNamedWriter(new JSONWriter());
-
-    // print all the writers available
-    Map<String, NamedWriter> writersMap =
-        getAbdera().getConfiguration().getNamedWriters();
-    for (NamedWriter writer : writersMap.values()) {
-      StringBuilder sbuf = new StringBuilder();
-      for (String s : writer.getOutputFormats()) {
-        sbuf.append(s).append(", ");
-      }
-      logger.fine("NamedWriter: " + writer.getClass().getName() +
-          " is for writing '" + writer.getName() + "'" +
-          ". Handles the following formats: " + sbuf.toString());
-    }
     return provider;
   }
 
@@ -92,7 +74,7 @@
     if (injector == null) {
       throw new UnavailableException(
           "Guice Injector not found! Make sure you registered " +
-          GuiceServletContextListener.class.getName() + " as a listener");
+              GuiceServletContextListener.class.getName() + " as a listener");
     }
     injector.injectMembers(provider);
     // all providers should implement initialize() so injection could happen
@@ -100,14 +82,14 @@
       Method m = provider.getClass().getMethod("initialize", new Class<?>[0]);
       m.invoke(provider);
     } catch (IllegalArgumentException e) {
-        logger.severe(e.getMessage());
-        e.printStackTrace();
+      logger.severe(e.getMessage());
+      e.printStackTrace();
     } catch (IllegalAccessException e) {
-        logger.severe(e.getMessage());
-        e.printStackTrace();
+      logger.severe(e.getMessage());
+      e.printStackTrace();
     } catch (InvocationTargetException e) {
-        logger.severe(e.getMessage());
-        e.printStackTrace();
+      logger.severe(e.getMessage());
+      e.printStackTrace();
     } catch (SecurityException e) {
       logger.severe(e.getMessage());
       e.printStackTrace();

Modified: 
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/AbstractSocialEntityCollectionAdapter.java
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/AbstractSocialEntityCollectionAdapter.java?rev=658412&r1=658411&r2=658412&view=diff
==============================================================================
--- 
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/AbstractSocialEntityCollectionAdapter.java
 (original)
+++ 
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/AbstractSocialEntityCollectionAdapter.java
 Tue May 20 13:26:06 2008
@@ -61,7 +61,7 @@
     factory = new Abdera().getFactory();
   }
 
-  private enum Format {
+  public enum Format {
     JSON("json"), ATOM("atom");
 
     private final String displayValue;

Modified: 
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/json/JSONFilter.java
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/json/JSONFilter.java?rev=658412&r1=658411&r2=658412&view=diff
==============================================================================
--- 
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/json/JSONFilter.java
 (original)
+++ 
incubator/shindig/trunk/java/social-api/src/main/java/org/apache/shindig/social/abdera/json/JSONFilter.java
 Tue May 20 13:26:06 2008
@@ -17,117 +17,134 @@
 */
 package org.apache.shindig.social.abdera.json;
 
+import org.apache.shindig.social.abdera.AbstractSocialEntityCollectionAdapter;
+
 import org.apache.abdera.Abdera;
 import org.apache.abdera.model.Document;
 import org.apache.abdera.model.Element;
+import org.apache.abdera.model.Entry;
+import org.apache.abdera.model.Feed;
 import org.apache.abdera.protocol.server.Filter;
 import org.apache.abdera.protocol.server.FilterChain;
-import org.apache.abdera.protocol.server.ProviderHelper;
 import org.apache.abdera.protocol.server.RequestContext;
 import org.apache.abdera.protocol.server.ResponseContext;
 import org.apache.abdera.protocol.server.context.ResponseContextWrapper;
 import org.apache.abdera.writer.Writer;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.IOException;
 import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.util.List;
 
 /**
- * TODO: This file is copied and modified from Abdera code as we needed
- * functionality different from the Abdera Json writer code base.
- * This file definitely needs cleanup and heavy refactoring
- *
  * Filter implementation that will convert an Atom document returned by
- * the server into a JSON document if the request specifies a higher
- * preference value for JSON or explicitly requests JSON by including
- * a format=json querystring parameter
+ * the server into a JSON document unless the request specifically asks for
+ * atom by adding a format=atom query string parameter
+ *
+ * TODO: Converting from atom to json is silly. We should just convert from
+ * pojo to atom and pojo to json. Need to fix abdera!
  */
-public class JSONFilter
-  implements Filter {
-
-  public ResponseContext filter(
-    RequestContext request,
-    FilterChain chain) {
-      ResponseContext resp = chain.next(request);
-      String format = request.getParameter("format");
-      if (format != null && format.equalsIgnoreCase("atom")) {
-        return resp;
-      }
-      // if there is no content, it could be either due to some error such as
-      // 404 or, there is no content to be translated into json. return
-      // TODO verify this claim
-      if (resp.getContentType() == null) {
-        return resp;
-      }
-
-      return jsonPreferred(request,resp.getContentType().toString()) ||
-        format == null || format.equalsIgnoreCase("json") ?
-        new JsonResponseContext(resp,request.getAbdera()) :
-        resp;
-  }
+public class JSONFilter implements Filter {
+  private final String FORMAT_FIELD = "format";
+  private final String ATOM = AbstractSocialEntityCollectionAdapter.Format
+      .ATOM.getDisplayValue();
+
+  public ResponseContext filter(RequestContext request, FilterChain chain) {
+    ResponseContext resp = chain.next(request);
+    String format = request.getParameter(FORMAT_FIELD);
+    if (format != null && format.equalsIgnoreCase(ATOM)) {
+      return resp;
+    }
+    // If there is no content, it could be either due to some error such as
+    // a 404 or, there is no content to be translated into json. Return.
+    // TODO: verify this claim
+    if (resp.getContentType() == null) {
+      return resp;
+    }
 
-  private boolean jsonPreferred(RequestContext request, String type) {
-    return ProviderHelper.isPreferred(
-      request,
-      "application/json",
-      type);
+    return new JsonResponseContext(resp, request.getAbdera());
   }
 
-  private class JsonResponseContext
-    extends ResponseContextWrapper {
-
+  private class JsonResponseContext extends ResponseContextWrapper {
     private final Abdera abdera;
 
-    public JsonResponseContext(
-      ResponseContext response,
-      Abdera abdera) {
-        super(response);
-        setContentType("application/json");
-        this.abdera = abdera;
+    public JsonResponseContext(ResponseContext response, Abdera abdera) {
+      super(response);
+      setContentType("application/json");
+      this.abdera = abdera;
     }
 
     @Override
-    public void writeTo(
-      OutputStream out,
-      Writer writer) {
-      try {
-        toJson(out,writer);
-      } catch (Exception se) {
-        if (se instanceof RuntimeException)
-          throw (RuntimeException)se;
-        throw new RuntimeException(se);
-      }
+    public void writeTo(OutputStream out) throws java.io.IOException {
+      ByteArrayOutputStream temp = new ByteArrayOutputStream();
+      super.writeTo(temp);
+      convertToJson(temp, out);
     }
 
     @Override
-    public void writeTo(
-      OutputStream out) {
-      try {
-        toJson(out,null);
-      } catch (Exception se) {
-        if (se instanceof RuntimeException)
-          throw (RuntimeException)se;
-        throw new RuntimeException(se);
-      }
+    public void writeTo(OutputStream out, Writer writer)
+        throws java.io.IOException {
+      ByteArrayOutputStream temp = new ByteArrayOutputStream();
+      super.writeTo(temp, writer);
+      convertToJson(temp, out);
     }
 
-    private void toJson(OutputStream aout,Writer writer) throws Exception {
-      Document<Element> doc = null;
-      try {
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        if (writer == null)
-          super.writeTo(out);
-        else
-          super.writeTo(out,writer);
-        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
-        doc = abdera.getParser().parse(in);
-      } catch (Exception e) {}
-      if (doc != null) {
-        doc.writeTo("json",aout);
-      } else {
-        throw new RuntimeException(
-          "There was an error serializing the entry to JSON");
+    private void convertToJson(ByteArrayOutputStream superOut, OutputStream 
out)
+        throws IOException {
+      ByteArrayInputStream in = new ByteArrayInputStream(
+          superOut.toByteArray());
+      Document<Element> doc = abdera.getParser().parse(in);
+
+      OutputStreamWriter streamWriter = new OutputStreamWriter(out);
+      streamWriter.write(getJsonFromDocument(doc));
+      streamWriter.flush();
+    }
+
+    private String getJsonFromDocument(Document<Element> doc) {
+      // The JSON format for OpenSocial rest doesn't do any hoisting.
+      // Thus, we just want to pull the main content object out.
+      // TODO: There's gotta be a better way to do this with abdera...
+
+      Element root = doc.getRoot();
+
+      if (root instanceof Entry) {
+        Entry entry = (Entry) root;
+        return entry.getContentElement().getValue();
+
+      } else if (root instanceof Feed) {
+        Feed feed = (Feed) root;
+        List<Entry> entries = feed.getEntries();
+
+        JSONObject json = new JSONObject();
+
+        try {
+          // TODO: Add the top level items for real
+          json.put("startIndex", 0);
+          json.put("totalResults", entries.size());
+
+          JSONArray jsonArray = new JSONArray();
+          for (Entry entry : feed.getEntries()) {
+            String contentValue = entry.getContentElement().getValue();
+            JSONObject jsonItem = new JSONObject(contentValue);
+            jsonArray.put(jsonItem);
+          }
+          json.put("entry", jsonArray);
+
+        } catch (JSONException e) {
+          throw new RuntimeException(
+              "The atom Document could not be converted to JSON", e);
+        }
+
+        return json.toString();
       }
+
+      throw new UnsupportedOperationException("Converting a non-Entry "
+          + "non-Feed abdera Document to JSON is not supported");
     }
   }
 }

Modified: 
incubator/shindig/trunk/java/social-api/src/test/java/org/apache/shindig/social/abdera/AbstractLargeRestfulTests.java
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/java/social-api/src/test/java/org/apache/shindig/social/abdera/AbstractLargeRestfulTests.java?rev=658412&r1=658411&r2=658412&view=diff
==============================================================================
--- 
incubator/shindig/trunk/java/social-api/src/test/java/org/apache/shindig/social/abdera/AbstractLargeRestfulTests.java
 (original)
+++ 
incubator/shindig/trunk/java/social-api/src/test/java/org/apache/shindig/social/abdera/AbstractLargeRestfulTests.java
 Tue May 20 13:26:06 2008
@@ -112,6 +112,7 @@
       line = reader.readLine();
     }
 
+    logger.fine(json.toString());
     return new JSONObject(json.toString());
   }
 


Reply via email to