You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@shindig.apache.org by ss...@apache.org on 2012/05/10 02:48:42 UTC

svn commit: r1336461 [2/3] - in /shindig/trunk/java: common/conf/ gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/ gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/ gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persiste...

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Module.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Module.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Module.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Module.java Thu May 10 00:48:41 2012
@@ -1,24 +1,35 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2;
 
-import java.util.List;
+import com.google.inject.AbstractModule;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import com.google.inject.name.Named;
+import com.google.inject.name.Names;
 
 import org.apache.shindig.common.Nullable;
+import org.apache.shindig.common.crypto.BasicBlobCrypter;
+import org.apache.shindig.common.crypto.BlobCrypter;
+import org.apache.shindig.common.crypto.Crypto;
+import org.apache.shindig.common.logging.i18n.MessageKeys;
 import org.apache.shindig.common.servlet.Authority;
 import org.apache.shindig.gadgets.GadgetException;
 import org.apache.shindig.gadgets.http.HttpFetcher;
@@ -34,11 +45,12 @@ import org.apache.shindig.gadgets.oauth2
 import org.apache.shindig.gadgets.oauth2.persistence.OAuth2Persister;
 import org.apache.shindig.gadgets.oauth2.persistence.sample.JSONOAuth2Persister;
 
-import com.google.inject.AbstractModule;
-import com.google.inject.Inject;
-import com.google.inject.Provider;
-import com.google.inject.Singleton;
-import com.google.inject.name.Named;
+import org.apache.commons.lang3.StringUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.logging.Level;
 
 /**
  * Injects the default OAuth2 implementation for {@link BasicOAuth2Request} and
@@ -73,7 +85,8 @@ public class OAuth2Module extends Abstra
             final List<GrantRequestHandler> grantRequestHandlers,
             final List<ResourceRequestHandler> resourceRequestHandlers,
             final List<TokenEndpointResponseHandler> tokenEndpointResponseHandlers,
-            @Named(OAuth2Module.SEND_TRACE_TO_CLIENT) final boolean sendTraceToClient,
+            @Named(OAuth2Module.SEND_TRACE_TO_CLIENT)
+            final boolean sendTraceToClient,
             final OAuth2RequestParameterGenerator requestParameterGenerator) {
       this.config = config;
       this.fetcher = fetcher;
@@ -101,22 +114,17 @@ public class OAuth2Module extends Abstra
     private final BasicOAuth2Store store;
 
     @Inject
-    public OAuth2StoreProvider(
-            @Named(OAuth2Module.OAUTH2_REDIRECT_URI) final String globalRedirectUri,
-            @Named(OAuth2Module.OAUTH2_IMPORT) final boolean importFromConfig,
-            @Named(OAuth2Module.OAUTH2_IMPORT_CLEAN) final boolean importClean,
-            final Authority authority, final OAuth2Cache cache, final OAuth2Persister persister,
-            final OAuth2Encrypter encrypter,
-            @Nullable @Named("shindig.contextroot") final String contextRoot) {
-
-      String redirectUri = globalRedirectUri;
-      if (authority != null) {
-        redirectUri = redirectUri.replace("%authority%", authority.getAuthority());
-        redirectUri = redirectUri.replace("%contextRoot%", contextRoot);
-        redirectUri = redirectUri.replace("%origin%", authority.getOrigin());
-      }
+    public OAuth2StoreProvider(@Named(OAuth2Module.OAUTH2_REDIRECT_URI)
+    final String globalRedirectUri, @Named(OAuth2Module.OAUTH2_IMPORT)
+    final boolean importFromConfig, @Named(OAuth2Module.OAUTH2_IMPORT_CLEAN)
+    final boolean importClean, final Authority authority, final OAuth2Cache cache,
+            final OAuth2Persister persister, final OAuth2Encrypter encrypter, @Nullable
+            @Named("shindig.contextroot")
+            final String contextRoot, @Named(OAuth2FetcherConfig.OAUTH2_STATE_CRYPTER)
+            final BlobCrypter stateCrypter) {
 
-      this.store = new BasicOAuth2Store(cache, persister, redirectUri);
+      this.store = new BasicOAuth2Store(cache, persister, encrypter, globalRedirectUri, authority,
+              contextRoot, stateCrypter);
 
       if (importFromConfig) {
         try {
@@ -144,10 +152,45 @@ public class OAuth2Module extends Abstra
     }
   }
 
+  @Singleton
+  public static class OAuth2CrypterProvider implements Provider<BlobCrypter> {
+
+    private final BlobCrypter crypter;
+
+    @Inject
+    public OAuth2CrypterProvider(@Named("shindig.signing.oauth2.state-key")
+    final String stateCrypterPath) throws IOException {
+      if (StringUtils.isBlank(stateCrypterPath)) {
+        OAuth2Module.LOG.log(Level.INFO,
+                "Using random key for OAuth2 client-side state encryption", new Object[] {});
+        if (OAuth2Module.LOG.isLoggable(Level.INFO)) {
+          OAuth2Module.LOG.log(Level.INFO, "OAuth2CrypterProvider constructor",
+                  MessageKeys.USING_RANDOM_KEY);
+        }
+        this.crypter = new BasicBlobCrypter(
+                Crypto.getRandomBytes(BasicBlobCrypter.MASTER_KEY_MIN_LEN));
+      } else {
+        if (OAuth2Module.LOG.isLoggable(Level.INFO)) {
+          OAuth2Module.LOG.log(Level.INFO, "OAuth2CrypterProvider constructor",
+                  new Object[] { stateCrypterPath });
+        }
+        this.crypter = new BasicBlobCrypter(new File(stateCrypterPath));
+      }
+    }
+
+    public BlobCrypter get() {
+      return this.crypter;
+    }
+  }
+
   @Override
   protected void configure() {
     this.bind(OAuth2Store.class).toProvider(OAuth2StoreProvider.class);
     this.bind(OAuth2Request.class).toProvider(OAuth2RequestProvider.class);
     this.bind(OAuth2RequestParameterGenerator.class).to(BasicOAuth2RequestParameterGenerator.class);
+    // Used for encrypting client-side OAuth2 state.
+    this.bind(BlobCrypter.class)
+            .annotatedWith(Names.named(OAuth2FetcherConfig.OAUTH2_STATE_CRYPTER))
+            .toProvider(OAuth2CrypterProvider.class);
   }
 }

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Store.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Store.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Store.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Store.java Thu May 10 00:48:41 2012
@@ -1,40 +1,41 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2;
 
+import org.apache.shindig.common.crypto.BlobCrypter;
 import org.apache.shindig.gadgets.GadgetException;
 import org.apache.shindig.gadgets.servlet.OAuth2CallbackServlet;
 
 /**
- * Interface to an OAuth 2.0 Data Store. A shindig gadget server can act as an
- * OAuth 2.0 consumer, using OAuth 2.0 tokens to talk to OAuth 2.0 service
- * providers on behalf of the gadgets it is proxying requests for. An OAuth 2.0
- * consumer needs to permanently store gadgets it has collected, and retrieve
- * the appropriate tokens when proxying a request for a gadget.
+ * Interface to an OAuth 2.0 Data Store. A shindig gadget server can act as an OAuth 2.0 consumer,
+ * using OAuth 2.0 tokens to talk to OAuth 2.0 service providers on behalf of the gadgets it is
+ * proxying requests for. An OAuth 2.0 consumer needs to permanently store gadgets it has collected,
+ * and retrieve the appropriate tokens when proxying a request for a gadget.
  *
- * Access and Refresh {@link OAuth2Token} may be store in memory or pesisted out
- * to a file system or database.
+ * Access and Refresh {@link OAuth2Token} may be store in memory or pesisted out to a file system or
+ * database.
  *
- * OAuth2Store implementors are responsible for handling the gadgeturi,
- * serviceName, user, scope mappings in the manor most effective for their
- * environment.
+ * OAuth2Store implementors are responsible for handling the gadgeturi, serviceName, user, scope
+ * mappings in the manor most effective for their environment.
  *
- * {@link OAuth2Accessor} storage should be cluster safe so it can be referenced
- * by {@link OAuth2CallbackServlet}
+ * {@link OAuth2Accessor} storage should be cluster safe so it can be referenced by
+ * {@link OAuth2CallbackServlet}
  */
 public interface OAuth2Store {
 
@@ -46,31 +47,29 @@ public interface OAuth2Store {
    * @throws GadgetException
    *           if the clear could not happen
    */
-  public boolean clearCache() throws GadgetException;
+  boolean clearCache() throws GadgetException;
 
   /**
-   * Creates, but does not store, an {@link OAuth2Token}. The token can then be
-   * initialized and stored.
+   * Creates, but does not store, an {@link OAuth2Token}. The token can then be initialized and
+   * stored.
    *
    * @return a new {@link OAuth2Token}
    */
-  public OAuth2Token createToken();
+  OAuth2Token createToken();
 
   /**
-   * Given an index, see {@link OAuth2Store.getOAuth2AccessorIndex}, the store
-   * will return the {@link OAuth2Accessor} if it exists in storage but will not
-   * create a new one.
+   * Given an OAuth2CallbackState, see {@link OAuth2Store.getOAuth2CallbackState}, the store will
+   * return the {@link OAuth2Accessor} if it exists in storage but will not create a new one.
    *
-   * @param index
-   *          {@link Integer} index of the accessor to get
-   * @return the {@link OAuth2Accessor} or <code>null</code> if it cannot be
-   *         located
+   * @param state
+   *          {@link OAuth2CallbackState} index of the accessor to get
+   * @return the {@link OAuth2Accessor} or <code>null</code> if it cannot be located
    */
-  public OAuth2Accessor getOAuth2Accessor(Integer index);
+  OAuth2Accessor getOAuth2Accessor(OAuth2CallbackState state);
 
   /**
-   * Will look for an accessor with the supplied mapping and return it. If one
-   * is not already stored a new one will be created and stored.
+   * Will look for an accessor with the supplied mapping and return it. If one is not already stored
+   * a new one will be created and stored.
    *
    * @param gadgetUri
    *          {@link String} URI of the gadget issuing the request
@@ -79,31 +78,19 @@ public interface OAuth2Store {
    * @param user
    *          {@link String user} userid of the page viewer
    * @param scope
-   *          {@link String} optional scope of the request. Supplied by the
-   *          request or the gadget spec
+   *          {@link String} optional scope of the request. Supplied by the request or the gadget
+   *          spec
    * @return the {@link OAuth2Accessor} , never <code>null</code>
    * @throws GadgetException
    *           if a lookup or creation error occurs
    */
-  public OAuth2Accessor getOAuth2Accessor(String gadgetUri, String serviceName, String user,
-      String scope) throws GadgetException;
+  OAuth2Accessor getOAuth2Accessor(String gadgetUri, String serviceName, String user, String scope)
+          throws GadgetException;
 
   /**
-   * Takes an accessor mapping and turns it into an {@link Integer} index.
-   *
-   * @param gadgetUri
-   *          {@link String} URI of the gadget issuing the request
-   * @param serviceName
-   *          {@link String} name of the OAuth2 service from the gadget spec
-   * @param user
-   *          {@link String user} userid of the page viewer
-   * @param scope
-   *          {@link String} optional scope of the request. Supplied by the
-   *          request or the gadget spec
-   * @return {@link Integer} index representing the mappign
+   * Gets the OAuth2 state encrypter/decrypter
    */
-  public Integer getOAuth2AccessorIndex(String gadgetUri, String serviceName, String user,
-      String scope);
+  BlobCrypter getStateCrypter();
 
   /**
    * Gets a token, if it exists, from the store.
@@ -115,17 +102,16 @@ public interface OAuth2Store {
    * @param user
    *          {@link String user} userid of the page viewer
    * @param scope
-   *          {@link String} optional scope of the request. Supplied by the
-   *          request or the gadget spec
+   *          {@link String} optional scope of the request. Supplied by the request or the gadget
+   *          spec
    * @param type
    *          {@link Type} if the token, ACCESS or REFRESH
-   * @return the {@link OAuth2Token} for the supplied mapping, <code>null</code>
-   *         if it isn't stored
+   * @return the {@link OAuth2Token} for the supplied mapping, <code>null</code> if it isn't stored
    * @throws GadgetException
    *           if something goes wrong
    */
-  public OAuth2Token getToken(String gadgetUri, String serviceName, String user, String scope,
-      OAuth2Token.Type type) throws GadgetException;
+  OAuth2Token getToken(String gadgetUri, String serviceName, String user, String scope,
+          OAuth2Token.Type type) throws GadgetException;
 
   /**
    * Cues the store to clear it's current state and reload from persistence.
@@ -133,29 +119,27 @@ public interface OAuth2Store {
    * @return
    * @throws GadgetException
    */
-  public boolean init() throws GadgetException;
+  boolean init() throws GadgetException;
 
   /**
    * Removes an {@link OAuth2Accessor} from the store.
    *
    * @param accessor
    *          to remove
-   * @return the accessor that was removed, or <code>null</code> if the accessor
-   *         was already removed
+   * @return the accessor that was removed, or <code>null</code> if the accessor was already removed
    */
-  public OAuth2Accessor removeOAuth2Accessor(OAuth2Accessor accessor);
+  OAuth2Accessor removeOAuth2Accessor(OAuth2Accessor accessor);
 
   /**
    * Removes an {@link OAuth2Token} from the store.
    *
    * @param token
    *          to remove
-   * @return the token that was removed, or <code>null</code> if the token was
-   *         already removed\
+   * @return the token that was removed, or <code>null</code> if the token was already removed\
    * @throws GadgetException
    *           if something goes wrong
    */
-  public OAuth2Token removeToken(OAuth2Token token) throws GadgetException;
+  OAuth2Token removeToken(OAuth2Token token) throws GadgetException;
 
   /**
    * Either inserts updates an {@link OAuth2Token} in the store.
@@ -165,7 +149,7 @@ public interface OAuth2Store {
    * @throws GadgetException
    *           if something goes wrong
    */
-  public void setToken(OAuth2Token token) throws GadgetException;
+  void setToken(OAuth2Token token) throws GadgetException;
 
   /**
    * Either inserts updates an {@link OAuth2Accessor} in the store.
@@ -173,5 +157,5 @@ public interface OAuth2Store {
    * @param accessor
    *          to store
    */
-  public void storeOAuth2Accessor(OAuth2Accessor accessor);
+  void storeOAuth2Accessor(OAuth2Accessor accessor);
 }

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Token.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Token.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Token.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Token.java Thu May 10 00:48:41 2012
@@ -1,18 +1,20 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2;
 
@@ -22,11 +24,11 @@ import java.util.Map;
 /**
  * Contains all relevant data for a token.
  *
- * OAuth2Token implementations should be {@link Serializable} to facilitate
- * cluster storage and caching across the various phases of OAuth 2.0 flows.
+ * OAuth2Token implementations should be {@link Serializable} to facilitate cluster storage and
+ * caching across the various phases of OAuth 2.0 flows.
  *
- * OAuth2Tokens are stored in the {@link OAuth2Store}, they may be held in
- * memory or in another persistence layer.
+ * OAuth2Tokens are stored in the {@link OAuth2Store}, they may be held in memory or in another
+ * persistence layer.
  *
  */
 public interface OAuth2Token extends Serializable {
@@ -39,20 +41,20 @@ public interface OAuth2Token extends Ser
    *
    * @return the time (in seconds) when the token was issued
    */
-  public long getIssuedAt();
+  long getIssuedAt();
 
   /**
    * issuedAt + expires_in or 0 if no expires_in was sent by server
    *
    * @return the time (in seconds) when the token expires
    */
-  public long getExpiresAt();
+  long getExpiresAt();
 
   /**
    *
    * @return uri of the gadget the token applies to
    */
-  public String getGadgetUri();
+  String getGadgetUri();
 
   /**
    * For use with the MAC token specification.
@@ -61,7 +63,7 @@ public interface OAuth2Token extends Ser
    *
    * @return the Mac algorithm
    */
-  public String getMacAlgorithm();
+  String getMacAlgorithm();
 
   /**
    * For use with the MAC token specification.
@@ -70,7 +72,7 @@ public interface OAuth2Token extends Ser
    *
    * @return the mac ext
    */
-  public String getMacExt();
+  String getMacExt();
 
   /**
    * For use with the MAC token specification.
@@ -79,72 +81,72 @@ public interface OAuth2Token extends Ser
    *
    * @return the mac secret
    */
-  public byte[] getMacSecret();
+  byte[] getMacSecret();
 
   /**
    * Contains any additional properties sent on the token.
    *
    * @return properties sent on the token
    */
-  public Map<String, String> getProperties();
+  Map<String, String> getProperties();
 
   /**
    * See {@link http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-3.3}
    *
    * @return scope the token applies to, or "" for no scope
    */
-  public String getScope();
+  String getScope();
 
   /**
    *
    * @return the token secret (unencrypted or signed)
    */
-  public byte[] getSecret();
+  byte[] getSecret();
 
   /**
    *
    * @return serviceName (in gadget spec) the token applies to
    */
-  public String getServiceName();
+  String getServiceName();
 
   /**
    *
    * @return type of this token e.g. "Bearer"
    */
-  public String getTokenType();
+  String getTokenType();
 
   /**
    *
    * @return if this is an Type.ACCESS or Type.REFRESH token
    */
-  public Type getType();
+  Type getType();
 
   /**
    *
    * @return shindig user the token was issued for
    */
-  public String getUser();
+  String getUser();
 
   /**
    * Setter for expiresAt field
    *
    * @param expiresIn
    */
-  public void setExpiresAt(long expiresAt);
+  void setExpiresAt(long expiresAt);
 
   /**
    * Setter for gadgetUri field
    *
    * @param gadgetUri
    */
-  public void setGadgetUri(String gadgetUri);
+  void setGadgetUri(String gadgetUri);
 
   /**
    * Setter for issuedAt field
    *
    * @param expiresIn
    */
-  public void setIssuedAt(long issuedAt);
+  void setIssuedAt(long issuedAt);
 
   /**
    * For use with the MAC token specification.
@@ -152,7 +154,7 @@ public interface OAuth2Token extends Ser
    * See See http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05
    *
    */
-  public void setMacAlgorithm(final String algorithm);
+  void setMacAlgorithm(final String algorithm);
 
   /**
    * For use with the MAC token specification.
@@ -160,19 +162,19 @@ public interface OAuth2Token extends Ser
    * See See http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05
    *
    */
-  public void setMacSecret(final byte[] secret) throws OAuth2RequestException;
+  void setMacSecret(final byte[] secret) throws OAuth2RequestException;
 
   /**
    * Set the properties on the token
    *
    */
-  public void setProperties(Map<String, String> properties);
+  void setProperties(Map<String, String> properties);
 
   /**
    * Setter for scope field
    *
    */
-  public void setScope(String scope);
+  void setScope(String scope);
 
   /**
    * Setter for secret property
@@ -180,33 +182,33 @@ public interface OAuth2Token extends Ser
    * @param secret
    * @throws OAuth2RequestException
    */
-  public void setSecret(byte[] secret) throws OAuth2RequestException;
+  void setSecret(byte[] secret) throws OAuth2RequestException;
 
   /**
    * Setter for serviceName field
    *
    * @param serviceName
    */
-  public void setServiceName(String serviceName);
+  void setServiceName(String serviceName);
 
   /**
    * Setter for tokenType property
    *
    * @param tokenType
    */
-  public void setTokenType(String tokenType);
+  void setTokenType(String tokenType);
 
   /**
    * Setter for type property
    *
    * @param type
    */
-  public void setType(Type type);
+  void setType(Type type);
 
   /**
    * Setter for user property
    *
    * @param user
    */
-  public void setUser(String user);
+  void setUser(String user);
 }

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/CodeAuthorizationResponseHandler.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/CodeAuthorizationResponseHandler.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/CodeAuthorizationResponseHandler.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/CodeAuthorizationResponseHandler.java Thu May 10 00:48:41 2012
@@ -1,26 +1,26 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2.handler;
 
-import java.io.UnsupportedEncodingException;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
+import com.google.common.collect.Maps;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
 
 import org.apache.shindig.auth.AnonymousSecurityToken;
 import org.apache.shindig.common.uri.Uri;
@@ -34,9 +34,11 @@ import org.apache.shindig.gadgets.oauth2
 import org.apache.shindig.gadgets.oauth2.OAuth2Utils;
 import org.apache.shindig.gadgets.oauth2.logger.FilteredLogger;
 
-import com.google.common.collect.Maps;
-import com.google.inject.Inject;
-import com.google.inject.Provider;
+import java.io.UnsupportedEncodingException;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
 
 /**
  *
@@ -45,9 +47,9 @@ import com.google.inject.Provider;
  * Handles the "code" flow
  */
 public class CodeAuthorizationResponseHandler implements AuthorizationEndpointResponseHandler {
-  private final static String LOG_CLASS = CodeAuthorizationResponseHandler.class.getName();
+  private static final String LOG_CLASS = CodeAuthorizationResponseHandler.class.getName();
   private static final FilteredLogger LOG = FilteredLogger
-      .getFilteredLogger(CodeAuthorizationResponseHandler.LOG_CLASS);
+          .getFilteredLogger(CodeAuthorizationResponseHandler.LOG_CLASS);
 
   private final List<ClientAuthenticationHandler> clientAuthenticationHandlers;
   private final HttpFetcher fetcher;
@@ -56,9 +58,9 @@ public class CodeAuthorizationResponseHa
 
   @Inject
   public CodeAuthorizationResponseHandler(final Provider<OAuth2Message> oauth2MessageProvider,
-      final List<ClientAuthenticationHandler> clientAuthenticationHandlers,
-      final List<TokenEndpointResponseHandler> tokenEndpointResponseHandlers,
-      final HttpFetcher fetcher) {
+          final List<ClientAuthenticationHandler> clientAuthenticationHandlers,
+          final List<TokenEndpointResponseHandler> tokenEndpointResponseHandlers,
+          final HttpFetcher fetcher) {
     this.oauth2MessageProvider = oauth2MessageProvider;
     this.clientAuthenticationHandlers = clientAuthenticationHandlers;
     this.tokenEndpointResponseHandlers = tokenEndpointResponseHandlers;
@@ -66,25 +68,25 @@ public class CodeAuthorizationResponseHa
 
     if (CodeAuthorizationResponseHandler.LOG.isLoggable()) {
       CodeAuthorizationResponseHandler.LOG.log("this.oauth2MessageProvider = {0}",
-          this.oauth2MessageProvider);
+              this.oauth2MessageProvider);
       CodeAuthorizationResponseHandler.LOG.log("this.clientAuthenticationHandlers = {0}",
-          this.clientAuthenticationHandlers);
+              this.clientAuthenticationHandlers);
       CodeAuthorizationResponseHandler.LOG.log("this.tokenEndpointResponseHandlers = {0}",
-          this.tokenEndpointResponseHandlers);
+              this.tokenEndpointResponseHandlers);
       CodeAuthorizationResponseHandler.LOG.log("this.fetcher = {0}", this.fetcher);
     }
   }
 
   private static String getAuthorizationBody(final OAuth2Accessor accessor,
-      final String authorizationCode) throws UnsupportedEncodingException {
+          final String authorizationCode) throws UnsupportedEncodingException {
     final boolean isLogging = CodeAuthorizationResponseHandler.LOG.isLoggable();
     if (isLogging) {
       if (authorizationCode != null) {
         CodeAuthorizationResponseHandler.LOG.entering(CodeAuthorizationResponseHandler.LOG_CLASS,
-            "getAuthorizationBody", "non-null authorizationCode");
+                "getAuthorizationBody", "non-null authorizationCode");
       } else {
         CodeAuthorizationResponseHandler.LOG.entering(CodeAuthorizationResponseHandler.LOG_CLASS,
-            "getAuthorizationBody", null);
+                "getAuthorizationBody", null);
       }
     }
 
@@ -104,20 +106,20 @@ public class CodeAuthorizationResponseHa
     queryParams.put(OAuth2Message.CLIENT_SECRET, secret);
 
     // add any additional parameters
-    for (Map.Entry<String, String> entry : accessor.getAdditionalRequestParams().entrySet()) {
+    for (final Map.Entry<String, String> entry : accessor.getAdditionalRequestParams().entrySet()) {
       queryParams.put(entry.getKey(), entry.getValue());
     }
 
     ret = OAuth2Utils.buildUrl(ret, queryParams, null);
 
     final char firstChar = ret.charAt(0);
-    if ((firstChar == '?') || (firstChar == '&')) {
+    if (firstChar == '?' || firstChar == '&') {
       ret = ret.substring(1);
     }
 
     if (isLogging) {
       CodeAuthorizationResponseHandler.LOG.exiting(CodeAuthorizationResponseHandler.LOG_CLASS,
-          "getAuthorizationBody");
+              "getAuthorizationBody");
     }
     return ret;
   }
@@ -127,11 +129,11 @@ public class CodeAuthorizationResponseHa
   }
 
   public OAuth2HandlerError handleRequest(final OAuth2Accessor accessor,
-      final HttpServletRequest request) {
+          final HttpServletRequest request) {
     final boolean isLogging = CodeAuthorizationResponseHandler.LOG.isLoggable();
     if (isLogging) {
       CodeAuthorizationResponseHandler.LOG.entering(CodeAuthorizationResponseHandler.LOG_CLASS,
-          "handleRequest", new Object[] { accessor, (request != null) });
+              "handleRequest", new Object[] { accessor, request != null });
     }
 
     OAuth2HandlerError ret = null;
@@ -142,10 +144,10 @@ public class CodeAuthorizationResponseHa
       ret = new OAuth2HandlerError(OAuth2Error.AUTHORIZATION_CODE_PROBLEM, "request is null", null);
     } else if (!accessor.isValid() || accessor.isErrorResponse() || !accessor.isRedirecting()) {
       ret = new OAuth2HandlerError(OAuth2Error.AUTHORIZATION_CODE_PROBLEM, "accessor is invalid",
-          null);
+              null);
     } else if (!accessor.getGrantType().equalsIgnoreCase(OAuth2Message.AUTHORIZATION)) {
       ret = new OAuth2HandlerError(OAuth2Error.AUTHORIZATION_CODE_PROBLEM,
-          "grant_type is not code", null);
+              "grant_type is not code", null);
     }
 
     if (ret == null) {
@@ -157,25 +159,25 @@ public class CodeAuthorizationResponseHa
       } catch (final Exception e) {
         if (CodeAuthorizationResponseHandler.LOG.isLoggable()) {
           CodeAuthorizationResponseHandler.LOG.log(
-              "Exception exchanging authorization code for access_token", e);
+                  "Exception exchanging authorization code for access_token", e);
         }
         ret = new OAuth2HandlerError(OAuth2Error.AUTHORIZATION_CODE_PROBLEM,
-            "Exception exchanging authorization code for access_token", e);
+                "Exception exchanging authorization code for access_token", e);
       }
     }
 
     if (isLogging) {
       CodeAuthorizationResponseHandler.LOG.exiting(CodeAuthorizationResponseHandler.LOG_CLASS,
-          "handleRequest", ret);
+              "handleRequest", ret);
     }
 
     return ret;
   }
 
   public OAuth2HandlerError handleResponse(final OAuth2Accessor accessor,
-      final HttpResponse response) {
+          final HttpResponse response) {
     return new OAuth2HandlerError(OAuth2Error.AUTHORIZATION_CODE_PROBLEM,
-        "doesn't handle responses", null);
+            "doesn't handle responses", null);
   }
 
   public boolean handlesRequest(final OAuth2Accessor accessor, final HttpServletRequest request) {
@@ -198,36 +200,43 @@ public class CodeAuthorizationResponseHa
   }
 
   private OAuth2HandlerError setAuthorizationCode(final String authorizationCode,
-      final OAuth2Accessor accessor) {
+          final OAuth2Accessor accessor) {
 
     final boolean isLogging = CodeAuthorizationResponseHandler.LOG.isLoggable();
     if (isLogging) {
       if (authorizationCode != null) {
         CodeAuthorizationResponseHandler.LOG.entering(CodeAuthorizationResponseHandler.LOG_CLASS,
-            "setAuthorizationCode", new Object[] { "non-null authorizationCode", accessor });
+                "setAuthorizationCode", new Object[] { "non-null authorizationCode", accessor });
       } else {
         CodeAuthorizationResponseHandler.LOG.entering(CodeAuthorizationResponseHandler.LOG_CLASS,
-            "setAuthorizationCode", new Object[] { null, accessor });
+                "setAuthorizationCode", new Object[] { null, accessor });
       }
     }
 
     OAuth2HandlerError ret = null;
 
     final String tokenUrl = CodeAuthorizationResponseHandler.getCompleteTokenUrl(accessor
-        .getTokenUrl());
+            .getTokenUrl());
 
     final HttpRequest request = new HttpRequest(Uri.parse(tokenUrl));
     request.setMethod("POST");
     request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
-    request.setSecurityToken( new AnonymousSecurityToken( "", 0L, accessor.getGadgetUri(), 0L ));
+    request.setSecurityToken(new AnonymousSecurityToken("", 0L, accessor.getGadgetUri(), 0L));
 
-    for (final ClientAuthenticationHandler clientAuthenticationHandler : this.clientAuthenticationHandlers) {
-      if (clientAuthenticationHandler.geClientAuthenticationType().equalsIgnoreCase(
-          accessor.getClientAuthenticationType())) {
-        final OAuth2HandlerError error = clientAuthenticationHandler.addOAuth2Authentication(
-            request, accessor);
-        if (error != null) {
-          ret = error;
+    if (!isUriAllowed(request.getUri(), accessor.getAllowedDomains())) {
+      ret = new OAuth2HandlerError(OAuth2Error.AUTHORIZATION_CODE_PROBLEM,
+              "Exception exchanging authorization code for access_token - domain not allowed", null);
+    }
+
+    if (ret == null) {
+      for (final ClientAuthenticationHandler clientAuthenticationHandler : this.clientAuthenticationHandlers) {
+        if (clientAuthenticationHandler.geClientAuthenticationType().equalsIgnoreCase(
+                accessor.getClientAuthenticationType())) {
+          final OAuth2HandlerError error = clientAuthenticationHandler.addOAuth2Authentication(
+                  request, accessor);
+          if (error != null) {
+            ret = error;
+          }
         }
       }
     }
@@ -235,15 +244,15 @@ public class CodeAuthorizationResponseHa
     if (ret == null) {
       try {
         final byte[] body = CodeAuthorizationResponseHandler.getAuthorizationBody(accessor,
-            authorizationCode).getBytes("UTF-8");
+                authorizationCode).getBytes("UTF-8");
         request.setPostBody(body);
       } catch (final UnsupportedEncodingException e) {
         if (CodeAuthorizationResponseHandler.LOG.isLoggable()) {
           CodeAuthorizationResponseHandler.LOG.log(
-              "UnsupportedEncodingException getting authorization body", e);
+                  "UnsupportedEncodingException getting authorization body", e);
         }
         ret = new OAuth2HandlerError(OAuth2Error.AUTHORIZATION_CODE_PROBLEM,
-            "error getting authorization body", e);
+                "error getting authorization body", e);
       }
 
       HttpResponse response = null;
@@ -254,16 +263,16 @@ public class CodeAuthorizationResponseHa
           CodeAuthorizationResponseHandler.LOG.log("error exchanging code for access_token", e);
         }
         ret = new OAuth2HandlerError(OAuth2Error.AUTHORIZATION_CODE_PROBLEM,
-            "error exchanging code for access_token", e);
+                "error exchanging code for access_token", e);
       }
 
-      if ((ret == null) && (response != null)) {
+      if (ret == null && response != null) {
         if (response.getHttpStatusCode() != HttpResponse.SC_OK) {
           final OAuth2Message msg = this.oauth2MessageProvider.get();
           msg.parseJSON(response.getResponseAsString());
           if (msg.getError() != null) {
             ret = new OAuth2HandlerError(msg.getError(), "error exchanging code for access_token",
-                null);
+                    null);
           }
         }
 
@@ -283,9 +292,30 @@ public class CodeAuthorizationResponseHa
 
     if (isLogging) {
       CodeAuthorizationResponseHandler.LOG.exiting(CodeAuthorizationResponseHandler.LOG_CLASS,
-          "setAuthorizationCode", ret);
+              "setAuthorizationCode", ret);
     }
 
     return ret;
   }
+
+  private static boolean isUriAllowed(final Uri uri, final String[] allowedDomains) {
+    if (allowedDomains == null || allowedDomains.length == 0) {
+      // if white list is not specified, allow client to access any domain
+      return true;
+    }
+    String host = uri.getAuthority();
+    final int pos = host.indexOf(':');
+    if (pos != -1) {
+      host = host.substring(0, pos);
+    }
+    for (String domain : allowedDomains) {
+      if (domain != null) {
+        domain = domain.trim();
+        if (domain.startsWith(".") && host.endsWith(domain) || domain.equals(host)) {
+          return true;
+        }
+      }
+    }
+    return false;
+  }
 }

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/CodeGrantTypeHandler.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/CodeGrantTypeHandler.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/CodeGrantTypeHandler.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/CodeGrantTypeHandler.java Thu May 10 00:48:41 2012
@@ -1,32 +1,35 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2.handler;
 
-import java.util.Map;
+import com.google.common.collect.Maps;
 
+import org.apache.shindig.common.crypto.BlobCrypterException;
 import org.apache.shindig.gadgets.http.HttpRequest;
 import org.apache.shindig.gadgets.oauth2.OAuth2Accessor;
+import org.apache.shindig.gadgets.oauth2.OAuth2CallbackState;
 import org.apache.shindig.gadgets.oauth2.OAuth2Error;
 import org.apache.shindig.gadgets.oauth2.OAuth2Message;
 import org.apache.shindig.gadgets.oauth2.OAuth2RequestException;
 import org.apache.shindig.gadgets.oauth2.OAuth2Utils;
 
-import com.google.common.collect.Maps;
-import com.google.inject.Inject;
+import java.util.Map;
 
 /**
  *
@@ -37,9 +40,6 @@ import com.google.inject.Inject;
 public class CodeGrantTypeHandler implements GrantRequestHandler {
   private static final OAuth2Error ERROR = OAuth2Error.CODE_GRANT_PROBLEM;
 
-  @Inject
-  public CodeGrantTypeHandler() {}
-
   public HttpRequest getAuthorizationRequest(final OAuth2Accessor accessor,
           final String completeAuthorizationUrl) throws OAuth2RequestException {
     throw new OAuth2RequestException(CodeGrantTypeHandler.ERROR,
@@ -63,22 +63,26 @@ public class CodeGrantTypeHandler implem
     queryParams.put(OAuth2Message.RESPONSE_TYPE, this.getGrantType());
     queryParams.put(OAuth2Message.CLIENT_ID, accessor.getClientId());
     final String redirectUri = accessor.getRedirectUri();
-    if ((redirectUri != null) && (redirectUri.length() > 0)) {
+    if (redirectUri != null && redirectUri.length() > 0) {
       queryParams.put(OAuth2Message.REDIRECT_URI, redirectUri);
     }
 
-    final String state = accessor.getState();
-    if ((state != null) && (state.length() > 0)) {
-      queryParams.put(OAuth2Message.STATE, state);
+    final OAuth2CallbackState state = accessor.getState();
+    if (state != null) {
+      try {
+        queryParams.put(OAuth2Message.STATE, state.getEncryptedState());
+      } catch (final BlobCrypterException e) {
+        throw new OAuth2RequestException(OAuth2Error.CODE_GRANT_PROBLEM, "encryption problem", e);
+      }
     }
 
     final String scope = accessor.getScope();
-    if ((scope != null) && (scope.length() > 0)) {
+    if (scope != null && scope.length() > 0) {
       queryParams.put(OAuth2Message.SCOPE, scope);
     }
 
     // add any additional parameters
-    for (Map.Entry<String, String> entry : accessor.getAdditionalRequestParams().entrySet()) {
+    for (final Map.Entry<String, String> entry : accessor.getAdditionalRequestParams().entrySet()) {
       queryParams.put(entry.getKey(), entry.getValue());
     }
 

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/OAuth2HandlerModule.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/OAuth2HandlerModule.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/OAuth2HandlerModule.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/OAuth2HandlerModule.java Thu May 10 00:48:41 2012
@@ -1,37 +1,39 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2.handler;
 
-import java.util.List;
-
-import org.apache.shindig.gadgets.oauth2.logger.FilteredLogger;
-
 import com.google.common.collect.ImmutableList;
 import com.google.inject.AbstractModule;
 import com.google.inject.Provides;
 import com.google.inject.Singleton;
 
+import org.apache.shindig.gadgets.oauth2.logger.FilteredLogger;
+
+import java.util.List;
+
 /**
  * Injects the default handlers.
  *
  */
 public class OAuth2HandlerModule extends AbstractModule {
   private static final FilteredLogger LOG = FilteredLogger
-      .getFilteredLogger(OAuth2HandlerModule.class.getName());
+          .getFilteredLogger(OAuth2HandlerModule.class.getName());
 
   @Override
   protected void configure() {
@@ -42,39 +44,39 @@ public class OAuth2HandlerModule extends
 
   @Provides
   @Singleton
-  static List<AuthorizationEndpointResponseHandler> provideAuthorizationEndpointResponseHandlers(
-      final CodeAuthorizationResponseHandler codeAuthorizationResponseHandler) {
+  public static List<AuthorizationEndpointResponseHandler> provideAuthorizationEndpointResponseHandlers(
+          final CodeAuthorizationResponseHandler codeAuthorizationResponseHandler) {
     return ImmutableList
-        .of((AuthorizationEndpointResponseHandler) codeAuthorizationResponseHandler);
+            .of((AuthorizationEndpointResponseHandler) codeAuthorizationResponseHandler);
   }
 
   @Provides
   @Singleton
-  static List<ClientAuthenticationHandler> provideClientAuthenticationHandlers(
-      final BasicAuthenticationHandler basicAuthenticationHandler,
-      final StandardAuthenticationHandler standardAuthenticationHandler) {
+  public static List<ClientAuthenticationHandler> provideClientAuthenticationHandlers(
+          final BasicAuthenticationHandler basicAuthenticationHandler,
+          final StandardAuthenticationHandler standardAuthenticationHandler) {
     return ImmutableList.of(basicAuthenticationHandler, standardAuthenticationHandler);
   }
 
   @Provides
   @Singleton
-  static List<GrantRequestHandler> provideGrantRequestHandlers(
-      final ClientCredentialsGrantTypeHandler clientCredentialsGrantTypeHandler,
-      final CodeGrantTypeHandler codeGrantTypeHandler) {
+  public static List<GrantRequestHandler> provideGrantRequestHandlers(
+          final ClientCredentialsGrantTypeHandler clientCredentialsGrantTypeHandler,
+          final CodeGrantTypeHandler codeGrantTypeHandler) {
     return ImmutableList.of(clientCredentialsGrantTypeHandler, codeGrantTypeHandler);
   }
 
   @Provides
   @Singleton
-  static List<TokenEndpointResponseHandler> provideTokenEndpointResponseHandlers(
-      final TokenAuthorizationResponseHandler tokenAuthorizationResponseHandler) {
+  public static List<TokenEndpointResponseHandler> provideTokenEndpointResponseHandlers(
+          final TokenAuthorizationResponseHandler tokenAuthorizationResponseHandler) {
     return ImmutableList.of((TokenEndpointResponseHandler) tokenAuthorizationResponseHandler);
   }
 
   @Provides
   @Singleton
-  static List<ResourceRequestHandler> provideTokenHandlers(
-      final BearerTokenHandler bearerTokenHandler, final MacTokenHandler macTokenHandler) {
+  public static List<ResourceRequestHandler> provideTokenHandlers(
+          final BearerTokenHandler bearerTokenHandler, final MacTokenHandler macTokenHandler) {
     return ImmutableList.of(bearerTokenHandler, macTokenHandler);
   }
 }
\ No newline at end of file

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/TokenAuthorizationResponseHandler.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/TokenAuthorizationResponseHandler.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/TokenAuthorizationResponseHandler.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/TokenAuthorizationResponseHandler.java Thu May 10 00:48:41 2012
@@ -1,22 +1,25 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2.handler;
 
-import java.util.Map;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
 
 import org.apache.shindig.gadgets.http.HttpResponse;
 import org.apache.shindig.gadgets.oauth2.OAuth2Accessor;
@@ -25,10 +28,10 @@ import org.apache.shindig.gadgets.oauth2
 import org.apache.shindig.gadgets.oauth2.OAuth2Store;
 import org.apache.shindig.gadgets.oauth2.OAuth2Token;
 import org.apache.shindig.gadgets.oauth2.logger.FilteredLogger;
+
 import org.json.JSONObject;
 
-import com.google.inject.Inject;
-import com.google.inject.Provider;
+import java.util.Map;
 
 /**
  *
@@ -37,9 +40,9 @@ import com.google.inject.Provider;
  * Handles the "client_credentials" flow
  */
 public class TokenAuthorizationResponseHandler implements TokenEndpointResponseHandler {
-  private final static String LOG_CLASS = CodeAuthorizationResponseHandler.class.getName();
+  private static final String LOG_CLASS = CodeAuthorizationResponseHandler.class.getName();
   private static final FilteredLogger LOG = FilteredLogger
-      .getFilteredLogger(TokenAuthorizationResponseHandler.LOG_CLASS);
+          .getFilteredLogger(TokenAuthorizationResponseHandler.LOG_CLASS);
 
   private static final OAuth2Error ERROR = OAuth2Error.TOKEN_RESPONSE_PROBLEM;
 
@@ -48,28 +51,28 @@ public class TokenAuthorizationResponseH
 
   @Inject
   public TokenAuthorizationResponseHandler(final Provider<OAuth2Message> oauth2MessageProvider,
-      final OAuth2Store store) {
+          final OAuth2Store store) {
     this.oauth2MessageProvider = oauth2MessageProvider;
     this.store = store;
 
     if (TokenAuthorizationResponseHandler.LOG.isLoggable()) {
       TokenAuthorizationResponseHandler.LOG.log("this.oauth2MessageProvider = {0}",
-          this.oauth2MessageProvider);
+              this.oauth2MessageProvider);
       TokenAuthorizationResponseHandler.LOG.log("this.store = {0}", this.store);
     }
   }
 
   public OAuth2HandlerError handleResponse(final OAuth2Accessor accessor,
-      final HttpResponse response) {
+          final HttpResponse response) {
     final boolean isLogging = TokenAuthorizationResponseHandler.LOG.isLoggable();
 
     if (isLogging) {
       if (response != null) {
         TokenAuthorizationResponseHandler.LOG.entering(TokenAuthorizationResponseHandler.LOG_CLASS,
-            "getAuthorizationBody", new Object[] { accessor, "non-null response" });
+                "getAuthorizationBody", new Object[] { accessor, "non-null response" });
       } else {
         TokenAuthorizationResponseHandler.LOG.entering(TokenAuthorizationResponseHandler.LOG_CLASS,
-            "getAuthorizationBody", new Object[] { accessor, null });
+                "getAuthorizationBody", new Object[] { accessor, null });
       }
     }
 
@@ -80,20 +83,19 @@ public class TokenAuthorizationResponseH
         ret = TokenAuthorizationResponseHandler.getError("response is null");
       }
 
-      if ((ret == null)
-          && ((accessor == null) || (!accessor.isValid()) || (accessor.isErrorResponse()))) {
+      if (ret == null && (accessor == null || !accessor.isValid() || accessor.isErrorResponse())) {
         ret = TokenAuthorizationResponseHandler.getError("accessor is invalid " + accessor);
       }
 
-      if ((ret == null) && (response != null)) {
+      if (ret == null && response != null) {
         final int responseCode = response.getHttpStatusCode();
         if (responseCode != HttpResponse.SC_OK) {
           ret = TokenAuthorizationResponseHandler.getError("can't handle error response code "
-              + responseCode);
+                  + responseCode);
         }
 
         if (ret == null) {
-          final long issuedAt = System.currentTimeMillis() / 1000;
+          final long issuedAt = System.currentTimeMillis();
 
           final String contentType = response.getHeader("Content-Type");
           final String responseString = response.getResponseAsString();
@@ -110,14 +112,14 @@ public class TokenAuthorizationResponseH
             if (isLogging) {
               TokenAuthorizationResponseHandler.LOG.log("Unhandled Content-Type {0}", contentType);
               TokenAuthorizationResponseHandler.LOG.exiting(
-                  TokenAuthorizationResponseHandler.LOG_CLASS, "handleResponse", null);
+                      TokenAuthorizationResponseHandler.LOG_CLASS, "handleResponse", null);
             }
             ret = TokenAuthorizationResponseHandler.getError("Unhandled Content-Type "
-                + contentType);
+                    + contentType);
           }
 
           final OAuth2Error error = msg.getError();
-          if ((error == null) && (accessor != null)) {
+          if (error == null && accessor != null) {
             final String accessToken = msg.getAccessToken();
             final String refreshToken = msg.getRefreshToken();
             final String expiresIn = msg.getExpiresIn();
@@ -134,7 +136,7 @@ public class TokenAuthorizationResponseH
               final OAuth2Token storedAccessToken = this.store.createToken();
               storedAccessToken.setIssuedAt(issuedAt);
               if (expiresIn != null) {
-                storedAccessToken.setExpiresAt(issuedAt + Long.decode(expiresIn));
+                storedAccessToken.setExpiresAt(issuedAt + Long.decode(expiresIn) * 1000);
               } else {
                 storedAccessToken.setExpiresAt(0);
               }
@@ -175,22 +177,22 @@ public class TokenAuthorizationResponseH
     } catch (final Exception e) {
       if (isLogging) {
         TokenAuthorizationResponseHandler.LOG.log(
-            "exception thrown handling authorization response", e);
+                "exception thrown handling authorization response", e);
       }
       return TokenAuthorizationResponseHandler.getError(
-          "exception thrown handling authorization response", e);
+              "exception thrown handling authorization response", e);
     }
 
     if (isLogging) {
       TokenAuthorizationResponseHandler.LOG.exiting(TokenAuthorizationResponseHandler.LOG_CLASS,
-          "handleResponse", ret);
+              "handleResponse", ret);
     }
 
     return ret;
   }
 
   public boolean handlesResponse(final OAuth2Accessor accessor, final HttpResponse response) {
-    if ((accessor == null) || (!accessor.isValid()) || (accessor.isErrorResponse())) {
+    if (accessor == null || !accessor.isValid() || accessor.isErrorResponse()) {
       return false;
     }
 

Added: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/MapCache.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/MapCache.java?rev=1336461&view=auto
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/MapCache.java (added)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/MapCache.java Thu May 10 00:48:41 2012
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.shindig.gadgets.oauth2.persistence;
+
+import org.apache.shindig.gadgets.oauth2.OAuth2Accessor;
+import org.apache.shindig.gadgets.oauth2.OAuth2CallbackState;
+import org.apache.shindig.gadgets.oauth2.OAuth2Token;
+import org.apache.shindig.gadgets.oauth2.OAuth2Token.Type;
+
+import java.util.Collection;
+import java.util.Map;
+
+public abstract class MapCache implements OAuth2Cache {
+  protected abstract Map<String, OAuth2Client> getClientMap();
+
+  protected abstract Map<String, OAuth2Token> getTokenMap();
+
+  protected abstract Map<String, OAuth2Accessor> getAccessorMap();
+
+  public void clearClients() throws OAuth2CacheException {
+    this.getClientMap().clear();
+  }
+
+  public void clearTokens() throws OAuth2CacheException {
+    this.getTokenMap().clear();
+  }
+
+  public void clearAccessors() {
+    this.getAccessorMap().clear();
+  }
+
+  public void storeTokens(final Collection<OAuth2Token> storeTokens) throws OAuth2CacheException {
+    for (final OAuth2Token token : storeTokens) {
+      this.storeToken(token);
+    }
+  }
+
+  public boolean isPrimed() {
+    return false;
+  }
+
+  public OAuth2Client getClient(final String gadgetUri, final String serviceName) {
+    OAuth2Client ret = null;
+    final String clientKey = this.getClientKey(gadgetUri, serviceName);
+    if (clientKey != null) {
+      ret = this.getClientMap().get(clientKey);
+    }
+
+    return ret;
+  }
+
+  public OAuth2Accessor getOAuth2Accessor(final OAuth2CallbackState state) {
+    OAuth2Accessor ret = null;
+    final String accessorKey = this.getAccessorKey(state);
+    if (accessorKey != null) {
+      ret = this.getAccessorMap().get(accessorKey);
+    }
+
+    return ret;
+  }
+
+  public OAuth2Token getToken(final String gadgetUri, final String serviceName, final String user,
+          final String scope, final Type type) {
+    OAuth2Token ret = null;
+    final String tokenKey = this.getTokenKey(gadgetUri, serviceName, user, scope, type);
+    if (tokenKey != null) {
+      ret = this.getTokenMap().get(tokenKey);
+    }
+
+    return ret;
+  }
+
+  public OAuth2Client removeClient(final OAuth2Client client) {
+    OAuth2Client ret = null;
+    final String clientKey = this.getClientKey(client);
+    if (clientKey != null) {
+      ret = this.getClientMap().remove(clientKey);
+    }
+
+    return ret;
+  }
+
+  public OAuth2Accessor removeOAuth2Accessor(final OAuth2Accessor accessor) {
+    OAuth2Accessor ret = null;
+    final String accessorKey = this.getAccessorKey(accessor);
+    if (accessorKey != null) {
+      ret = this.getAccessorMap().remove(accessorKey);
+    }
+
+    return ret;
+  }
+
+  public OAuth2Token removeToken(final OAuth2Token token) {
+    OAuth2Token ret = null;
+    final String tokenKey = this.getTokenKey(token);
+    if (tokenKey != null) {
+      ret = this.getTokenMap().remove(tokenKey);
+    }
+
+    return ret;
+  }
+
+  public void storeClient(final OAuth2Client client) throws OAuth2CacheException {
+    if (client != null) {
+      final String clientKey = this.getClientKey(client.getGadgetUri(), client.getServiceName());
+      this.getClientMap().put(clientKey, client);
+    }
+  }
+
+  public void storeClients(final Collection<OAuth2Client> clients) throws OAuth2CacheException {
+    if (clients != null) {
+      for (final OAuth2Client client : clients) {
+        this.storeClient(client);
+      }
+    }
+  }
+
+  public void storeOAuth2Accessor(final OAuth2Accessor accessor) {
+    if (accessor != null) {
+      final String accessorKey = this.getAccessorKey(accessor);
+      this.getAccessorMap().put(accessorKey, accessor);
+    }
+  }
+
+  public void storeToken(final OAuth2Token token) throws OAuth2CacheException {
+    if (token != null) {
+      final String tokenKey = this.getTokenKey(token);
+      this.getTokenMap().put(tokenKey, token);
+    }
+  }
+
+  protected String getClientKey(final OAuth2Client client) {
+    return this.getClientKey(client.getGadgetUri(), client.getServiceName());
+  }
+
+  protected String getClientKey(final String gadgetUri, final String serviceName) {
+    if (gadgetUri == null || serviceName == null) {
+      return null;
+    }
+    final StringBuilder buf = new StringBuilder(gadgetUri.length() + serviceName.length() + 1);
+    buf.append(gadgetUri);
+    buf.append(':');
+    buf.append(serviceName);
+    return buf.toString();
+  }
+
+  protected String getAccessorKey(final OAuth2CallbackState state) {
+    return this.getAccessorKey(state.getGadgetUri(), state.getServiceName(), state.getUser(),
+            state.getScope());
+  }
+
+  private String getAccessorKey(final String gadgetUri, final String serviceName,
+          final String user, final String scope) {
+    if (gadgetUri == null || serviceName == null || user == null) {
+      return null;
+    }
+
+    final String s;
+    if (scope == null) {
+      s = "";
+    } else {
+      s = scope;
+    }
+
+    final StringBuilder buf = new StringBuilder(gadgetUri.length() + serviceName.length()
+            + user.length() + s.length() + 3);
+    buf.append(gadgetUri);
+    buf.append(':');
+    buf.append(serviceName);
+    buf.append(':');
+    buf.append(user);
+    buf.append(':');
+    buf.append(s);
+
+    return buf.toString();
+  }
+
+  protected String getAccessorKey(final OAuth2Accessor accessor) {
+    return this.getAccessorKey(accessor.getGadgetUri(), accessor.getServiceName(),
+            accessor.getUser(), accessor.getScope());
+  }
+
+  protected String getTokenKey(final String gadgetUri, final String serviceName, final String user,
+          final String scope, final Type type) {
+    if (gadgetUri == null || serviceName == null || user == null) {
+      return null;
+    }
+
+    final String s;
+    if (scope == null) {
+      s = "";
+    } else {
+      s = scope;
+    }
+
+    final String t = type.name();
+
+    final StringBuilder buf = new StringBuilder(gadgetUri.length() + serviceName.length()
+            + user.length() + s.length() + t.length() + 4);
+    buf.append(gadgetUri);
+    buf.append(':');
+    buf.append(serviceName);
+    buf.append(':');
+    buf.append(user);
+    buf.append(':');
+    buf.append(s);
+    buf.append(':');
+    buf.append(t);
+
+    return buf.toString();
+  }
+
+  protected String getTokenKey(final OAuth2Token token) {
+    return this.getTokenKey(token.getGadgetUri(), token.getServiceName(), token.getUser(),
+            token.getScope(), token.getType());
+  }
+}

Propchange: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/MapCache.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Cache.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Cache.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Cache.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Cache.java Thu May 10 00:48:41 2012
@@ -1,27 +1,29 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2.persistence;
 
-import java.util.Collection;
-
 import org.apache.shindig.gadgets.oauth2.OAuth2Accessor;
-import org.apache.shindig.gadgets.oauth2.OAuth2Store;
+import org.apache.shindig.gadgets.oauth2.OAuth2CallbackState;
 import org.apache.shindig.gadgets.oauth2.OAuth2Token;
 
+import java.util.Collection;
+
 /**
  * Used by {@link OAuth2Store} to cache OAuth2 data.
  *
@@ -34,107 +36,80 @@ public interface OAuth2Cache {
    *
    * @throws OAuth2CacheException
    */
-  void clearClients() throws OAuth2CacheException;
+  void clearAccessors() throws OAuth2CacheException;
 
   /**
-   * Clears all cached {@link OAuth2Token}s.
+   * Clears all cached {@link OAuth2Client}s.
    *
    * @throws OAuth2CacheException
    */
-  void clearTokens() throws OAuth2CacheException;
+  void clearClients() throws OAuth2CacheException;
 
   /**
-   * Find an {@link OAuth2Client} by {@link Integer} index.
+   * Clears all cached {@link OAuth2Token}s.
    *
-   * @param index
-   * @return OAuth2Client
+   * @throws OAuth2CacheException
    */
-  OAuth2Client getClient(Integer index);
+  void clearTokens() throws OAuth2CacheException;
 
   /**
-   * Generate an {@link OAuth2Client} index for the given mapping.
+   * Find an {@link OAuth2Client}.
    *
    * @param gadgetUri
    * @param serviceName
-   * @return client index
+   * @return OAuth2Client
    */
-  Integer getClientIndex(String gadgetUri, String serviceName);
+  OAuth2Client getClient(String gadgetUri, String serviceName);
 
   /**
-   * Find an {@link OAuth2Accessor} by index.
+   * Find an {@link OAuth2Accessor} by state.
    *
-   * @param index
+   * @param state
    * @return OAuth2Accessor
    */
-  OAuth2Accessor getOAuth2Accessor(Integer index);
+  OAuth2Accessor getOAuth2Accessor(OAuth2CallbackState state);
 
   /**
-   * Generate in index for an {@link OAuth2Accessor} by the given parameters.
+   * Find an {@link OAuth2Token} based on index
    *
    * @param gadgetUri
    * @param serviceName
    * @param user
    * @param scope
-   * @return index for the OAuth2Accessor
-   */
-  Integer getOAuth2AccessorIndex(String gadgetUri, String serviceName, String user, String scope);
-
-  /**
-   * Find an {@link OAuth2Token} based on index
-   *
-   * @param index
+   * @param type
    * @return an OAuth2Token
    */
-  OAuth2Token getToken(Integer index);
+  OAuth2Token getToken(String gadgetUri, String serviceName, String user, String scope,
+          OAuth2Token.Type type);
 
   /**
-   * Returns the {@link Integer} index for the given {@link OAuth2Token}.
-   *
-   * @param token
-   * @return index of the OAuth2Token
+   * @return true if the cache has already been primed. (presumably by another node.)
    */
-  Integer getTokenIndex(OAuth2Token token);
+  boolean isPrimed();
 
   /**
-   * Generate index for {@link OAuth2Token} based on parameters
+   * Remove the given client;
    *
-   * @param gadgetUri
-   * @param serviceName
-   * @param user
-   * @param scope
-   * @param type
-   * @return index of OAuth2Token
-   */
-  Integer getTokenIndex(String gadgetUri, String serviceName, String user, String scope,
-      OAuth2Token.Type type);
-
-  /**
-   * Removes the {@link OAuth2Client} from the cache.
-   *
-   * @param index
-   * @return the removed client, or <code>null</code> if none was found
-   * @throws OAuth2CacheException
+   * @param client
+   * @return the client that was removed, or <code>null</code> if removal failed
    */
-  OAuth2Client removeClient(Integer index) throws OAuth2CacheException;
+  OAuth2Client removeClient(OAuth2Client client);
 
   /**
-   * Removes the given {@link OAuth2Accessor} from the cache.
+   * Remove the given accessor.
    *
-   * @param index
-   * @return the removed {@link OAuth2Accessor} or <code>null</code> if none was
-   *         found
+   * @param accessor
+   * @return the accessor that was removed, or <code>null</code> if removal failed
    */
-  OAuth2Accessor removeOAuth2Accessor(Integer index);
+  OAuth2Accessor removeOAuth2Accessor(OAuth2Accessor accessor);
 
   /**
-   * Removes the given {@link OAuth2Token} from the cache.
+   * Remove the given token;
    *
-   * @param index
-   * @return the removed {@link OAuth2Token} or <code>null</code> if none was
-   *         found
-   * @throws OAuth2CacheException
+   * @param token
+   * @return the token that was removed, or <code>null</code> if removal failed
    */
-  OAuth2Token removeToken(Integer index) throws OAuth2CacheException;
+  OAuth2Token removeToken(OAuth2Token token);
 
   /**
    * Stores the given client.
@@ -143,7 +118,7 @@ public interface OAuth2Cache {
    * @param client
    * @throws OAuth2CacheException
    */
-  Integer storeClient(OAuth2Client client) throws OAuth2CacheException;
+  void storeClient(OAuth2Client client) throws OAuth2CacheException;
 
   /**
    * Store all clients in the collection.
@@ -158,12 +133,12 @@ public interface OAuth2Cache {
    *
    * @param accessor
    */
-  Integer storeOAuth2Accessor(OAuth2Accessor accessor);
+  void storeOAuth2Accessor(OAuth2Accessor accessor);
 
   /**
-   * Stores the given token and returns it's index.
+   * Stores the given token.
    */
-  Integer storeToken(OAuth2Token token) throws OAuth2CacheException;
+  void storeToken(OAuth2Token token) throws OAuth2CacheException;
 
   /**
    * Stores all tokens in the collection.

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Client.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Client.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Client.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Client.java Thu May 10 00:48:41 2012
@@ -1,38 +1,39 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2.persistence;
 
-import java.io.Serializable;
+import com.google.inject.Inject;
 
 import org.apache.shindig.gadgets.oauth2.OAuth2Accessor;
 import org.apache.shindig.gadgets.oauth2.OAuth2Message;
 
-import com.google.inject.Inject;
+import java.io.Serializable;
+import java.util.Arrays;
 
 /**
  * Data class for client data stored in persistence.
  *
- * Uses the injected {@link OAuth2Encrypter} protect the client_secret in the
- * persistence store.
+ * Uses the injected {@link OAuth2Encrypter} protect the client_secret in the persistence store.
  *
  */
 public class OAuth2Client implements Serializable {
-  private static final long serialVersionUID = -6090033505867216220L;
-
+  private static final long serialVersionUID = -7374658882342619184L;
   private boolean allowModuleOverride;
   private boolean authorizationHeader;
   private String authorizationUrl;
@@ -40,7 +41,7 @@ public class OAuth2Client implements Ser
   private String clientId;
   private byte[] clientSecret;
   private byte[] encryptedSecret;
-  private transient final OAuth2Encrypter encrypter;
+  private final transient OAuth2Encrypter encrypter;
   private String gadgetUri;
   private String grantType = OAuth2Message.NO_GRANT_TYPE;
   private String redirectUri;
@@ -49,6 +50,11 @@ public class OAuth2Client implements Ser
   private OAuth2Accessor.Type type = OAuth2Accessor.Type.UNKNOWN;
   private boolean urlParameter;
   private boolean sharedToken = false;
+  private String[] allowedDomains = new String[] {};
+
+  public OAuth2Client() {
+    this(null);
+  }
 
   @Inject
   public OAuth2Client(final OAuth2Encrypter encrypter) {
@@ -159,7 +165,7 @@ public class OAuth2Client implements Ser
 
   @Override
   public int hashCode() {
-    if ((this.serviceName != null) && (this.gadgetUri != null)) {
+    if (this.serviceName != null && this.gadgetUri != null) {
       return (this.serviceName + ':' + this.gadgetUri).hashCode();
     }
 
@@ -186,7 +192,7 @@ public class OAuth2Client implements Ser
     this.allowModuleOverride = alllowModuleOverride;
   }
 
-  public void setAuthorizationHeader(boolean authorizationHeader) {
+  public void setAuthorizationHeader(final boolean authorizationHeader) {
     this.authorizationHeader = authorizationHeader;
   }
 
@@ -204,12 +210,16 @@ public class OAuth2Client implements Ser
 
   public void setClientSecret(final byte[] secret) throws OAuth2EncryptionException {
     this.clientSecret = secret;
-    this.encryptedSecret = this.encrypter.encrypt(secret);
+    if (this.encrypter != null) {
+      this.encryptedSecret = this.encrypter.encrypt(secret);
+    }
   }
 
   public void setEncryptedSecret(final byte[] encryptedSecret) throws OAuth2EncryptionException {
     this.encryptedSecret = encryptedSecret;
-    this.clientSecret = this.encrypter.decrypt(encryptedSecret);
+    if (this.encrypter != null) {
+      this.clientSecret = this.encrypter.decrypt(encryptedSecret);
+    }
   }
 
   public void setGadgetUri(final String gadgetUri) {
@@ -240,19 +250,38 @@ public class OAuth2Client implements Ser
     this.type = type;
   }
 
-  public void setUrlParameter(boolean urlParameter) {
+  public void setUrlParameter(final boolean urlParameter) {
     this.urlParameter = urlParameter;
   }
 
+  /**
+   * sets the domains of allowed resource servers
+   *
+   * @param allowedDomains
+   */
+  public void setAllowedDomains(final String[] allowedDomains) {
+    this.allowedDomains = allowedDomains;
+  }
+
+  /**
+   * gets the domains of allowed resource servers
+   *
+   * @return allowed domains
+   */
+  public String[] getAllowedDomains() {
+    return this.allowedDomains;
+  }
+
   @Override
   public String toString() {
     return "org.apache.shindig.gadgets.oauth2.persistence.sample.OAuth2ClientImpl: serviceName = "
-        + this.serviceName + " , redirectUri = " + this.redirectUri + " , gadgetUri = "
-        + this.gadgetUri + " , clientId = " + this.clientId + " , grantType = " + this.grantType
-        + " , type = " + this.type.name() + " , grantType = " + this.grantType + " , tokenUrl = "
-        + this.tokenUrl + " , authorizationUrl = " + this.authorizationUrl
-        + " , this.clientAuthenticationType = " + this.clientAuthenticationType
-        + " , this.sharedToken = " + this.sharedToken;
+            + this.serviceName + " , redirectUri = " + this.redirectUri + " , gadgetUri = "
+            + this.gadgetUri + " , clientId = " + this.clientId + " , grantType = "
+            + this.grantType + " , type = " + this.type.name() + " , grantType = " + this.grantType
+            + " , tokenUrl = " + this.tokenUrl + " , authorizationUrl = " + this.authorizationUrl
+            + " , this.clientAuthenticationType = " + this.clientAuthenticationType
+            + " , this.sharedToken = " + this.sharedToken + ", this.allowedDomains = "
+            + Arrays.asList(this.allowedDomains);
   }
 
   @Override
@@ -260,12 +289,13 @@ public class OAuth2Client implements Ser
     final OAuth2Client ret = new OAuth2Client(this.encrypter);
     ret.setAllowModuleOverride(this.allowModuleOverride);
     ret.setAuthorizationHeader(this.authorizationHeader);
-    ret.setAuthorizationUrl(authorizationUrl);
+    ret.setAuthorizationUrl(this.authorizationUrl);
     ret.setClientAuthenticationType(this.clientAuthenticationType);
     ret.setClientId(this.clientId);
     try {
-    ret.setClientSecret(this.clientSecret);
-      } catch (OAuth2EncryptionException e) {
+      ret.setClientSecret(this.clientSecret);
+    } catch (final OAuth2EncryptionException e) {
+      // no op
     }
     ret.setGadgetUri(this.gadgetUri);
     ret.setGrantType(this.grantType);
@@ -275,6 +305,7 @@ public class OAuth2Client implements Ser
     ret.setTokenUrl(this.tokenUrl);
     ret.setType(this.type);
     ret.setUrlParameter(this.urlParameter);
+    ret.setAllowedDomains(this.getAllowedDomains());
 
     return ret;
   }