You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@shindig.apache.org by jo...@apache.org on 2010/04/06 21:42:10 UTC

svn commit: r931285 - in /shindig/trunk: features/src/main/javascript/features/core.io/ features/src/main/javascript/features/xhrwrapper/ features/src/test/javascript/features/core.io/ features/src/test/javascript/features/xhrwrapper/ java/gadgets/src/...

Author: johnh
Date: Tue Apr  6 19:42:09 2010
New Revision: 931285

URL: http://svn.apache.org/viewvc?rev=931285&view=rev
Log:
This is a set of three improvements to XhrWrapper:

- If the gadget was loaded using OAuth or Signed auth, it passes the auth type
and oauth service/token name to gadgets.io.makeRequest.
- Adds a RequestParameter to make g.i.makeRequest return the full headers from
the response, for the sake of a more faithful XHR emulation.
- Creates and switches between copies of the gadgets, shindig and opensocial
namespaces at several strategic points. This is done because some type=url
gadgets include a hardcoded copy of the feature JS instead of including it from
the gadget server, and this hardcopy overwrites the feature JS provided by
Shindig. In many (most?) cases, the code provided by the gadget won't include
all the necessary bits to make XhrWrapper work. With this namespace switching,
the proper functions in the proper objects are called.

Patch provided by Jacobo Tarrio.


Modified:
    shindig/trunk/features/src/main/javascript/features/core.io/io.js
    shindig/trunk/features/src/main/javascript/features/xhrwrapper/xhrwrapper.js
    shindig/trunk/features/src/test/javascript/features/core.io/iotest.js
    shindig/trunk/features/src/test/javascript/features/xhrwrapper/xhrwrappertest.js
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/FetchResponseUtils.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/preload/HttpPreloader.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/RenderingGadgetRewriter.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/servlet/MakeRequestHandler.java
    shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/FetchResponseUtilsTest.java
    shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/render/RenderingGadgetRewriterTest.java

Modified: shindig/trunk/features/src/main/javascript/features/core.io/io.js
URL: http://svn.apache.org/viewvc/shindig/trunk/features/src/main/javascript/features/core.io/io.js?rev=931285&r1=931284&r2=931285&view=diff
==============================================================================
--- shindig/trunk/features/src/main/javascript/features/core.io/io.js (original)
+++ shindig/trunk/features/src/main/javascript/features/core.io/io.js Tue Apr  6 19:42:09 2010
@@ -388,7 +388,8 @@ gadgets.io = function() {
         gadget : urlParams.url,
         container : urlParams.container || urlParams.synd || "default",
         // should we bypass gadget spec cache (e.g. to read OAuth provider URLs)
-        bypassSpecCache : gadgets.util.getUrlParameters().nocache || ""
+        bypassSpecCache : gadgets.util.getUrlParameters().nocache || "",
+        getFullHeaders : !!params.GET_FULL_HEADERS,
       };
 
       // OAuth goodies
@@ -524,6 +525,7 @@ gadgets.io.RequestParameters = gadgets.u
   "AUTHORIZATION",
   "NUM_ENTRIES",
   "GET_SUMMARIES",
+  "GET_FULL_HEADERS",
   "REFRESH_INTERVAL",
   "OAUTH_SERVICE_NAME",
   "OAUTH_USE_TOKEN",

Modified: shindig/trunk/features/src/main/javascript/features/xhrwrapper/xhrwrapper.js
URL: http://svn.apache.org/viewvc/shindig/trunk/features/src/main/javascript/features/xhrwrapper/xhrwrapper.js?rev=931285&r1=931284&r2=931285&view=diff
==============================================================================
--- shindig/trunk/features/src/main/javascript/features/xhrwrapper/xhrwrapper.js (original)
+++ shindig/trunk/features/src/main/javascript/features/xhrwrapper/xhrwrapper.js Tue Apr  6 19:42:09 2010
@@ -70,7 +70,7 @@ shindig.xhrwrapper = shindig.xhrwrapper 
    *     gadgets.io.makeRequest to make the actual network accesses.
    */
   shindig.xhrwrapper.XhrWrapper = function() {
-    this.config_ = gadgets.config.get('shindig.xhrwrapper');
+    this.config_ = originalNS.gadgets.config.get('shindig.xhrwrapper');
 
     // XMLHttpRequest event listeners
     this.onreadystatechange = null;
@@ -166,15 +166,36 @@ shindig.xhrwrapper = shindig.xhrwrapper 
    *     request.
    */
   shindig.xhrwrapper.XhrWrapper.prototype.send = function(opt_data) {
-    this.aborted_ = false;
-    var that = this;
-    var params = {};
-    params[gadgets.io.RequestParameters.METHOD] = this.method_;
-    params[gadgets.io.RequestParameters.HEADERS] = this.requestHeaders_;
-    params[gadgets.io.RequestParameters.POST_DATA] = opt_data;
-    gadgets.io.makeRequest(this.url_.toString(),
-                           function(response) { that.callback_(response); },
-                           params);
+    // Switch to the original namespaces for call to gadgets.io.makeRequest.
+    switchOriginalNS_();
+    try {
+      this.aborted_ = false;
+      var that = this;
+      var params = {};
+      params[gadgets.io.RequestParameters.METHOD] = this.method_;
+      params[gadgets.io.RequestParameters.HEADERS] = this.requestHeaders_;
+      params[gadgets.io.RequestParameters.GET_FULL_HEADERS] = true;
+      params[gadgets.io.RequestParameters.POST_DATA] = opt_data;
+      if (this.config_.authorization) {
+        if (this.config_.authorization == 'oauth') {
+          params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.OAUTH;
+          params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = this.config_.oauthService;
+          if (this.config_.oauthTokenName) {
+            params[gadgets.io.RequestParameters.OAUTH_TOKEN_NAME] = this.config_.oauthTokenName;
+          }
+        } else if (this.config_.authorization == 'signed') {
+          params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
+        }
+      }
+
+      gadgets.io.makeRequest(this.url_.toString(),
+                             function(response) { that.callback_(response); },
+                             params);
+    } catch (e) {
+      throw e;
+    } finally {
+      switchGadgetNS_();
+    }
   };
 
   /**
@@ -201,10 +222,14 @@ shindig.xhrwrapper = shindig.xhrwrapper 
     this.readyState = 4;
     this.responseHeaders_ = response.headers;
     this.responseText = response.text;
+    // Switch to the original namespaces for call to opensocial.xmlutil.parseXML
+    switchOriginalNS_();
     try {
       this.responseXML = opensocial.xmlutil.parseXML(response.text);
     } catch (x) {
       this.responseXML = null;
+    } finally {
+      switchGadgetNS_();
     }
     this.status = response.rc;
     if (response.errors) {
@@ -373,6 +398,74 @@ shindig.xhrwrapper = shindig.xhrwrapper 
     }
   };
 
+  /*
+   * XhrWrapper is designed to take type=url gadgets and convert them to
+   * type=html gadgets with minimal changes. Some of those gadgets, instead
+   * of loading the feature JavaScript on demand, have it hardcoded.
+   * When such a gadget is loaded as a type=html gadget, the code hardcoded
+   * in the gadget will overwrite the code from Shindig.
+   *
+   * This is bad because when this code tries to call gadgets.io.makeRequest,
+   * it will call the wrong function, or it might even be undefined.
+   * 
+   * Therefore, we save the original namespaces before the gadget has a chance
+   * to overwrite them, then switch between them as necessary.
+   * 
+   * This works like this:
+   * 
+   * switchOriginalNS_();
+   * try {
+   *   functionThatNeedsTheOriginalNamespaces();
+   * } catch (e) {
+   *   throw e;
+   * } finally {
+   *   // Make sure we switch back to the gadget namespaces.
+   *   switchGadgetNS_();
+   * }
+   */
+  var originalNS = {};
+  var gadgetNS = {};
+  var namespaces = ['gadgets', 'opensocial', 'shindig']; 
+
+  /**
+   * Copies the Shindig namespaces between two objects.
+   * 
+   * @param {Object} from Object to copy from, or null for the global object.
+   * @param {Object} to Object to copy to, or null for the global object.
+   * @private
+   */
+  function copyNS_(from, to) {
+    // NB "this" is the global object.
+    var orig = from ? from : this;
+    var dest = to ? to : this;
+    for (var i in namespaces) {
+      var nsName = namespaces[i];
+      if (typeof orig[nsName] != 'undefined') {
+        dest[nsName] = orig[nsName];
+      }
+    }
+  };
+
+  /**
+   * Switches from the gadget's namespaces to the original namespaces.
+   * @private
+   */
+  function switchOriginalNS_() {
+    copyNS_(null, gadgetNS);
+    copyNS_(originalNS, null);
+  };
+
+  /**
+   * Switches from the original namespaces to the gadget's namespaces.
+   * @private
+   */
+  function switchGadgetNS_() {
+    copyNS_(gadgetNS, null);
+  };
+
+  // Save the original namespaces.
+  copyNS_(null, originalNS);
+  
   // Replace the browser's XMLHttpRequest and ActiveXObject constructors with
   // xhrwrapper's.
   if (window.XMLHttpRequest) {

Modified: shindig/trunk/features/src/test/javascript/features/core.io/iotest.js
URL: http://svn.apache.org/viewvc/shindig/trunk/features/src/test/javascript/features/core.io/iotest.js?rev=931285&r1=931284&r2=931285&view=diff
==============================================================================
--- shindig/trunk/features/src/test/javascript/features/core.io/iotest.js (original)
+++ shindig/trunk/features/src/test/javascript/features/core.io/iotest.js Tue Apr  6 19:42:09 2010
@@ -124,6 +124,7 @@ IoTest.prototype.setStandardArgs = funct
   this.setArg(req, inBody, "signOwner", "true");
   this.setArg(req, inBody, "getSummaries", "false");
   this.setArg(req, inBody, "gadget", "http://www.gadget.com/gadget.xml");
+  this.setArg(req, inBody, "getFullHeaders", "false");
   this.setArg(req, inBody, "container", "foo");
   this.setArg(req, inBody, "headers", "");
   this.setArg(req, inBody, "numEntries", "3");

Modified: shindig/trunk/features/src/test/javascript/features/xhrwrapper/xhrwrappertest.js
URL: http://svn.apache.org/viewvc/shindig/trunk/features/src/test/javascript/features/xhrwrapper/xhrwrappertest.js?rev=931285&r1=931284&r2=931285&view=diff
==============================================================================
--- shindig/trunk/features/src/test/javascript/features/xhrwrapper/xhrwrappertest.js (original)
+++ shindig/trunk/features/src/test/javascript/features/xhrwrapper/xhrwrappertest.js Tue Apr  6 19:42:09 2010
@@ -161,6 +161,47 @@ XhrWrapperTest.prototype.testRepointWron
   this.checkRequest('GET', 'http://foo.bar/baz/foo/bar/baz.xml');
 };
 
+XhrWrapperTest.prototype.testOauthParamsUsed = function() {
+  gadgets.config.init({
+      'shindig.xhrwrapper': {
+          'contentUrl': 'http://foo.bar/baz/bax.html',
+          'authorization': 'oauth',
+          'oauthService': 'testOauthService'
+    	}
+  });
+  xhr = new shindig.xhrwrapper.XhrWrapper();
+  xhr.open('GET', '/foo/bar/baz.xml');
+  xhr.send();
+  this.checkOAuth('testOauthService');
+
+  gadgets.config.init({
+      'shindig.xhrwrapper': {
+          'contentUrl': 'http://foo.bar/baz/bax.html',
+          'authorization': 'oauth',
+          'oauthService': 'testOauthService',
+          'oauthTokenName': 'testOauthToken'
+    	}
+  });
+  xhr = new shindig.xhrwrapper.XhrWrapper();
+  xhr.open('GET', '/foo/bar/baz.xml');
+  xhr.send();
+  this.checkOAuth('testOauthService', 'testOauthToken');
+};
+
+XhrWrapperTest.prototype.testSignedAuthParamsUsed = function() {
+	  gadgets.config.init({
+	      'shindig.xhrwrapper': {
+	          'contentUrl': 'http://foo.bar/baz/bax.html',
+	          'authorization': 'signed'
+	    	}
+	  });
+	  xhr = new shindig.xhrwrapper.XhrWrapper();
+	  xhr.open('GET', '/foo/bar/baz.xml');
+	  xhr.send();
+
+	  this.assertEquals('SIGNED', this.madeRequest.params['AUTHORIZATION']);
+	};
+
 XhrWrapperTest.prototype.mockMakeRequest = function(info) {
   var that = this;
   return function(url, callback, opt_params) {
@@ -189,3 +230,8 @@ XhrWrapperTest.prototype.checkRequest = 
   this.assertEquals(url, this.madeRequest.url);
 };
 
+XhrWrapperTest.prototype.checkOAuth = function(service, opt_token) {
+  this.assertEquals('OAUTH', this.madeRequest.params['AUTHORIZATION']);
+  this.assertEquals(service, this.madeRequest.params['OAUTH_SERVICE_NAME']);
+  this.assertEquals(opt_token, this.madeRequest.params['OAUTH_TOKEN_NAME']);
+};
\ No newline at end of file

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/FetchResponseUtils.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/FetchResponseUtils.java?rev=931285&r1=931284&r2=931285&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/FetchResponseUtils.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/FetchResponseUtils.java Tue Apr  6 19:42:09 2010
@@ -21,6 +21,7 @@ package org.apache.shindig.gadgets;
 import org.apache.shindig.gadgets.http.HttpResponse;
 
 import com.google.common.collect.Maps;
+import com.google.common.collect.Multimap;
 
 import java.util.Collection;
 import java.util.Map;
@@ -44,10 +45,12 @@ public class FetchResponseUtils {
    * @param response the response body
    * @param id the response id, or null if not needed
    * @param body string to use as the body of the response.
+   * @param getFullHeaders whether all response headers should be included,
+   *     or only a small set
    * @return a JSONObject representation of the response body.
    */
   public static Map<String, Object> getResponseAsJson(HttpResponse response, String id,
-      String body) {
+      String body, boolean getFullHeaders) {
     Map<String, Object> resp = Maps.newHashMap();
     if (id != null) {
       resp.put("id", id);
@@ -55,8 +58,12 @@ public class FetchResponseUtils {
     resp.put("rc", response.getHttpStatusCode());
     resp.put("body", body);
     Map<String, Collection<String>> headers = Maps.newHashMap();
-    addHeaders(headers, response, "set-cookie");
-    addHeaders(headers, response, "location");
+    if (getFullHeaders) {
+      addAllHeaders(headers, response);
+    } else {
+      addHeaders(headers, response, "set-cookie");
+      addHeaders(headers, response, "location");
+    }
     if (!headers.isEmpty()) {
       resp.put("headers", headers);
     }
@@ -67,6 +74,14 @@ public class FetchResponseUtils {
     return resp;
   }
 
+  private static void addAllHeaders(Map<String, Collection<String>> headers,
+      HttpResponse response) {
+    Multimap<String, String> responseHeaders = response.getHeaders();
+    for (String name : responseHeaders.keySet()) {
+      headers.put(name.toLowerCase(), responseHeaders.get(name));
+    }
+  }
+
   private static void addHeaders(Map<String, Collection<String>> headers, HttpResponse response,
       String name) {
     Collection<String> values = response.getHeaders(name);

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/preload/HttpPreloader.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/preload/HttpPreloader.java?rev=931285&r1=931284&r2=931285&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/preload/HttpPreloader.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/preload/HttpPreloader.java Tue Apr  6 19:42:09 2010
@@ -104,8 +104,8 @@ public class HttpPreloader implements Pr
     private final Map<String, Object> data;
 
     public HttpPreloadData(HttpResponse response, String key) {
-      this.data
-          = FetchResponseUtils.getResponseAsJson(response, key, response.getResponseAsString());
+      this.data = FetchResponseUtils.getResponseAsJson(response, key,
+          response.getResponseAsString(), false);
     }
 
     public Collection<Object> toJson() {

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/RenderingGadgetRewriter.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/RenderingGadgetRewriter.java?rev=931285&r1=931284&r2=931285&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/RenderingGadgetRewriter.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/RenderingGadgetRewriter.java Tue Apr  6 19:42:09 2010
@@ -23,6 +23,7 @@ import org.apache.shindig.common.JsonSer
 import org.apache.shindig.common.uri.Uri;
 import org.apache.shindig.common.xml.DomUtil;
 import org.apache.shindig.config.ContainerConfig;
+import org.apache.shindig.gadgets.AuthType;
 import org.apache.shindig.gadgets.Gadget;
 import org.apache.shindig.gadgets.GadgetContext;
 import org.apache.shindig.gadgets.GadgetException;
@@ -31,6 +32,7 @@ import org.apache.shindig.gadgets.Unsupp
 import org.apache.shindig.gadgets.UrlGenerator;
 import org.apache.shindig.gadgets.features.FeatureRegistry;
 import org.apache.shindig.gadgets.features.FeatureResource;
+import org.apache.shindig.gadgets.oauth.OAuthArguments;
 import org.apache.shindig.gadgets.preload.PreloadException;
 import org.apache.shindig.gadgets.preload.PreloadedData;
 import org.apache.shindig.gadgets.rewrite.GadgetRewriter;
@@ -387,12 +389,33 @@ public class RenderingGadgetRewriter imp
     boolean isUsingXhrWrapper = gadget.getAllFeatures().contains("xhrwrapper");
     if (isUsingXhrWrapper) {
       Map<String, String> xhrWrapperConfig = Maps.newHashMapWithExpectedSize(2);
-      Uri contentsUri = gadget.getCurrentView().getHref();
+      View view = gadget.getCurrentView();
+      Uri contentsUri = view.getHref();
       xhrWrapperConfig.put("contentUrl", contentsUri == null ? "" : contentsUri.toString());
+      if (AuthType.OAUTH.equals(view.getAuthType())) {
+        addOAuthConfig(xhrWrapperConfig, view);
+      } else if (AuthType.SIGNED.equals(view.getAuthType())) {
+        xhrWrapperConfig.put("authorization", "signed");
+      }
       config.put("shindig.xhrwrapper", xhrWrapperConfig);
     }
   }
 
+  private void addOAuthConfig(Map<String, String> xhrWrapperConfig, View view) {
+    Map<String, String> oAuthConfig = Maps.newHashMapWithExpectedSize(3);
+    try {
+      OAuthArguments oAuthArguments = new OAuthArguments(view);
+      oAuthConfig.put("authorization", "oauth");
+      oAuthConfig.put("oauthService", oAuthArguments.getServiceName());
+      if (!"".equals(oAuthArguments.getTokenName())) {
+        oAuthConfig.put("oauthTokenName", oAuthArguments.getTokenName());
+      }
+      xhrWrapperConfig.putAll(oAuthConfig);
+    } catch (GadgetException e) {
+      // Do not add any OAuth configuration if an exception was thrown
+    }
+  }
+
   private void addSecurityTokenConfig(GadgetContext context, Map<String, Object> config) {
     SecurityToken authToken = context.getToken();
     if (authToken != null) {

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/servlet/MakeRequestHandler.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/servlet/MakeRequestHandler.java?rev=931285&r1=931284&r2=931285&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/servlet/MakeRequestHandler.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/servlet/MakeRequestHandler.java Tue Apr  6 19:42:09 2010
@@ -64,6 +64,7 @@ public class MakeRequestHandler extends 
   public static final String NUM_ENTRIES_PARAM = "numEntries";
   public static final String DEFAULT_NUM_ENTRIES = "3";
   public static final String GET_SUMMARIES_PARAM = "getSummaries";
+  public static final String GET_FULL_HEADERS_PARAM = "getFullHeaders";
   public static final String AUTHZ_PARAM = "authz";
 
   private final RequestPipeline requestPipeline;
@@ -217,6 +218,8 @@ public class MakeRequestHandler extends 
    */
   protected String convertResponseToJson(SecurityToken authToken, HttpServletRequest request,
       HttpResponse results) throws GadgetException {
+    boolean getFullHeaders =
+        Boolean.parseBoolean(getParameter(request, GET_FULL_HEADERS_PARAM, "false"));
     String originalUrl = request.getParameter(ProxyBase.URL_PARAM);
     String body = results.getResponseAsString();
     if (body.length() > 0) {
@@ -224,7 +227,8 @@ public class MakeRequestHandler extends 
         body = processFeed(originalUrl, request, body);
       }
     }
-    Map<String, Object> resp = FetchResponseUtils.getResponseAsJson(results, null, body);
+    Map<String, Object> resp =
+        FetchResponseUtils.getResponseAsJson(results, null, body, getFullHeaders);
 
     if (authToken != null) {
       String updatedAuthToken = authToken.getUpdatedToken();

Modified: shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/FetchResponseUtilsTest.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/FetchResponseUtilsTest.java?rev=931285&r1=931284&r2=931285&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/FetchResponseUtilsTest.java (original)
+++ shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/FetchResponseUtilsTest.java Tue Apr  6 19:42:09 2010
@@ -36,7 +36,7 @@ public class FetchResponseUtilsTest {
     HttpResponse response = new HttpResponseBuilder()
         .setHttpStatusCode(999)
         .create();
-    Map<String, Object> obj = FetchResponseUtils.getResponseAsJson(response, "key", "body");
+    Map<String, Object> obj = FetchResponseUtils.getResponseAsJson(response, "key", "body", false);
 
     JsonAssert.assertObjectEquals("{'rc':999,'id':'key',body:'body'}", obj);
   }
@@ -48,7 +48,7 @@ public class FetchResponseUtilsTest {
         .setMetadata("metaname", "metavalue")
         .setMetadata("more meta", "more value")
         .create();
-    Map<String, Object> obj = FetchResponseUtils.getResponseAsJson(response, null, "body");
+    Map<String, Object> obj = FetchResponseUtils.getResponseAsJson(response, null, "body", false);
 
     JsonAssert.assertObjectEquals(
         "{rc:999,body:'body',metaname:'metavalue','more meta':'more value'}", obj);
@@ -61,7 +61,7 @@ public class FetchResponseUtilsTest {
         .setHeader("Set-Cookie", "cookie")
         .setHeader("location", "here")
         .create();
-    Map<String, Object> obj = FetchResponseUtils.getResponseAsJson(response, "key", "body");
+    Map<String, Object> obj = FetchResponseUtils.getResponseAsJson(response, "key", "body", false);
     JsonAssert.assertObjectEquals(
         "{rc:999,id:'key',body:'body',headers:{set-cookie:['cookie'],location:['here']}}", obj);
   }
@@ -74,7 +74,7 @@ public class FetchResponseUtilsTest {
         .addHeader("Set-Cookie", "cookie2")
         .addHeader("Set-Cookie", "cookie3")
         .create();
-    Map<String, Object> obj = FetchResponseUtils.getResponseAsJson(response, "key", "body");
+    Map<String, Object> obj = FetchResponseUtils.getResponseAsJson(response, "key", "body", false);
     JsonAssert.assertObjectEquals(
         "{rc:999,id:'key',body:'body',headers:{set-cookie:['cookie','cookie2','cookie3']}}", obj);
   }

Modified: shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/render/RenderingGadgetRewriterTest.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/render/RenderingGadgetRewriterTest.java?rev=931285&r1=931284&r2=931285&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/render/RenderingGadgetRewriterTest.java (original)
+++ shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/render/RenderingGadgetRewriterTest.java Tue Apr  6 19:42:09 2010
@@ -620,21 +620,79 @@ public class RenderingGadgetRewriterTest
 
   @Test
   public void xhrWrapperConfigurationInjected() throws Exception {
+    checkXhrWrapperConfigurationInjection(
+        "No shindig.xhrwrapper configuration present in rewritten HTML.", null, null, null);
+
+    checkXhrWrapperConfigurationInjection(
+        "No shindig.xhrwrapper.authorization=signed configuration present in rewritten HTML.",
+        "signed", null, null);
+
+    checkXhrWrapperConfigurationInjection(
+        "No shindig.xhrwrapper.oauthService configuration present in rewritten HTML.",
+        "oauth", "serviceName", null);
+
+    checkXhrWrapperConfigurationInjection(
+        "No shindig.xhrwrapper.oauthTokenName configuration present in rewritten HTML.",
+        "oauth", "serviceName", "tokenName");
+  }
+  
+  private void checkXhrWrapperConfigurationInjection(String message, String auth, String oauthService, String oauthToken)
+      throws Exception {
+    String oAuthBlock = "";
+    String authzAttr = "";
+    if (auth != null) {
+      authzAttr = " authz='" + auth + "'";
+      if ("oauth".equals(auth)) {
+        if (oauthService != null) {
+          oAuthBlock =
+              "<OAuth><Service name='" + oauthService + "'>" +
+              "<Access url='http://foo' method='GET' />" +
+              "<Request url='http://bar' method='GET' />" +
+              "<Authorization url='http://baz' />" +
+              "</Service></OAuth>";
+          authzAttr += " oauth_service_name='" + oauthService + "'";
+        }
+        if (oauthToken != null) {
+          authzAttr += " oauth_token_name='" + oauthToken + "'";
+        }
+      }
+    }
+
     String gadgetXml =
       "<Module><ModulePrefs title=''>" +
       "  <Require feature='xhrwrapper' />" +
+      oAuthBlock +
       "</ModulePrefs>" +
-      "<Content type='html' href='http://foo.com/bar/baz.html' />" +
+      "<Content type='html' href='http://foo.com/bar/baz.html'" + authzAttr + " />" +
       "</Module>";
     
+    String expected = "{" +
+        (oauthService == null ? "" : "\"oauthService\":\"serviceName\",") +
+        "\"contentUrl\":\"http://foo.com/bar/baz.html\"" +
+        (auth == null ? "" : ",\"authorization\":\"" + auth + "\"") +
+        (oauthToken == null ? "" : ",\"oauthTokenName\":\"tokenName\"") +
+        "}";
+    
     Gadget gadget = makeGadgetWithSpec(gadgetXml);
     gadget.setCurrentView(gadget.getSpec().getView("default"));
-    
     String rewritten = rewrite(gadget, BODY_CONTENT);
     
-    boolean containsConfig =
-        rewritten.contains("\"shindig.xhrwrapper\":{\"contentUrl\":\"http://foo.com/bar/baz.html\"}");
-    assertTrue("No shindig.xhrwrapper configuration present in rewritten HTML.", containsConfig);
+    assertXhrConfigContains(message, expected, rewritten);
+  }
+  
+  private void assertXhrConfigContains(String message, String expected, String content) throws Exception {
+    // TODO: make this test a little more robust. This check ensures that ordering is not taken
+    // into account during config comparison.
+    String prefix = "gadgets.config.init(";
+    int configIdx = content.indexOf(prefix);
+    assertTrue("gadgets.config.init not found in rewritten content", configIdx != -1);
+    int endIdx = content.indexOf(")", configIdx + prefix.length());
+    assertTrue("unexpected error, gadgets.config.init not closed", endIdx != -1);
+    String configJson = content.substring(configIdx + prefix.length(), endIdx);
+    JSONObject config = new JSONObject(configJson);
+    JSONObject xhrConfig = config.getJSONObject("shindig.xhrwrapper");
+    JSONObject expectedJson = new JSONObject(expected);
+    assertEquals(message, xhrConfig.toString(), expectedJson.toString());
   }
 
   @Test