Author: ivol37 at gmail.com
Date: Wed Dec  8 15:43:24 2010
New Revision: 484

Log:
[AMDATU-211] Added new oAuth example bundle with a oAuth protected resource and 
a gadget using 3-legged oAuth to access that resource.

Added:
   
trunk/amdatu-core/config-filebased/src/main/resources/conf/org.amdatu.example.oauth.cfg
   trunk/amdatu-example/oauth/
   trunk/amdatu-example/oauth/pom.xml
   trunk/amdatu-example/oauth/src/
   trunk/amdatu-example/oauth/src/main/
   trunk/amdatu-example/oauth/src/main/java/
   trunk/amdatu-example/oauth/src/main/java/org/
   trunk/amdatu-example/oauth/src/main/java/org/amdatu/
   trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/
   trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/
   trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/osgi/
   
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/osgi/Activator.java
   trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/
   
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/DummyInterface.java
   
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthGadgetsRegistrationServiceImpl.java
   
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthProtectedResource.java
   trunk/amdatu-example/oauth/src/main/resources/
   trunk/amdatu-example/oauth/src/main/resources/jsp/
   trunk/amdatu-example/oauth/src/main/resources/jsp/3leggedOAuthGadget.jspf
   trunk/amdatu-example/oauth/src/main/resources/static/
   trunk/amdatu-example/oauth/src/main/resources/static/img/
   trunk/amdatu-example/oauth/src/main/resources/static/img/oauth_logo.png   
(contents, props changed)
   trunk/amdatu-opensocial/dashboard/src/main/resources/static/img/new.gif   
(contents, props changed)
Modified:
   
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthTokenProviderImpl.java
   trunk/amdatu-authentication/oauth-server/src/main/resources/jsp/authorize.jsp
   trunk/amdatu-example/pom.xml
   
trunk/amdatu-opensocial/shindig/src/main/java/org/amdatu/opensocial/shindig/persistence/CassandraOAuthStore.java
   trunk/amdatu-release/pom.xml
   trunk/src/main/resources/conf/felix-config.properties

Modified: 
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthTokenProviderImpl.java
==============================================================================
--- 
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthTokenProviderImpl.java
   (original)
+++ 
trunk/amdatu-authentication/oauth-server/src/main/java/org/amdatu/authentication/oauth/server/service/OAuthTokenProviderImpl.java
   Wed Dec  8 15:43:24 2010
@@ -63,7 +63,7 @@
             // try to load from local cache if not throw exception
             String consumer_key = requestMessage.getConsumerKey();
             if (consumer_key == null || "".equals(consumer_key)) {
-                throw new OAuthProblemException("No consumer key provided");
+                throw new OAuthProblemException("consumer_key_rejected");
             }
             OAuthServiceConsumer serviceConsumer = 
m_consumerRegistry.getConsumer(consumer_key);
             if (serviceConsumer == null) {

Modified: 
trunk/amdatu-authentication/oauth-server/src/main/resources/jsp/authorize.jsp
==============================================================================
--- 
trunk/amdatu-authentication/oauth-server/src/main/resources/jsp/authorize.jsp   
    (original)
+++ 
trunk/amdatu-authentication/oauth-server/src/main/resources/jsp/authorize.jsp   
    Wed Dec  8 15:43:24 2010
@@ -23,7 +23,7 @@
     <h3>"<%=appDesc%>" is trying to access your information.</h3>
     
     Enter the userId you want to be known as:
-    <form name="authZForm" action=" /newoauth/authorizetoken" method="POST">
+    <form name="authZForm" action="/oauth-server/authorizetoken" method="POST">
         <input type="text" name="userId" value="" size="20" /><br>
         <input type="hidden" name="oauth_token" value="<%= token %>"/>
         <input type="hidden" name="oauth_callback" value="<%= callback %>"/>

Added: 
trunk/amdatu-core/config-filebased/src/main/resources/conf/org.amdatu.example.oauth.cfg
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-core/config-filebased/src/main/resources/conf/org.amdatu.example.oauth.cfg
     Wed Dec  8 15:43:24 2010
@@ -0,0 +1,3 @@
+# The hostname and portnr used to register the gadget
+hostname=${server.hostname}
+portnr=${server.port}
\ No newline at end of file

Added: trunk/amdatu-example/oauth/pom.xml
==============================================================================
--- (empty file)
+++ trunk/amdatu-example/oauth/pom.xml  Wed Dec  8 15:43:24 2010
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/maven-v4_0_0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.amdatu</groupId>
+    <artifactId>org.amdatu.example</artifactId>
+    <version>0.1.0-SNAPSHOT</version>
+  </parent>
+  <groupId>org.amdatu.example</groupId>
+  <artifactId>oauth</artifactId>
+  <packaging>bundle</packaging>
+  <name>Amdatu Example - oAuth</name>
+  <description>Provides example services and gadgets using oAuth 
authentication</description>
+  
+  <dependencies>  
+    <dependency>    
+      <groupId>org.amdatu.opensocial</groupId>
+      <artifactId>gadgetmanagement</artifactId>   
+      <scope>provided</scope>
+      <type>bundle</type>
+    </dependency> 
+    <dependency>
+      <groupId>org.amdatu.opensocial</groupId>
+      <artifactId>shindig</artifactId>
+      <scope>provided</scope>
+      <type>bundle</type>
+    </dependency>
+    <dependency>    
+      <groupId>org.amdatu.authentication.oauth</groupId>
+      <artifactId>api</artifactId>   
+      <version>${platform.version}</version>
+      <scope>provided</scope>
+      <type>bundle</type>
+    </dependency>
+    <dependency>    
+      <groupId>org.amdatu.authentication.oauth</groupId>
+      <artifactId>server</artifactId>   
+      <version>${platform.version}</version>
+      <scope>provided</scope>
+      <type>bundle</type>
+    </dependency>
+    <dependency>
+      <groupId>org.amdatu.web.rest</groupId>
+      <artifactId>jaxrs</artifactId>
+      <version>${platform.version}</version>
+      <scope>provided</scope>
+      <type>bundle</type>
+    </dependency>
+    <dependency>
+      <groupId>org.json</groupId>
+      <artifactId>json</artifactId>
+      <version>20090211</version>
+      <scope>compile</scope>
+    </dependency>
+  </dependencies> 
+  
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.felix</groupId>
+        <artifactId>maven-bundle-plugin</artifactId>
+        <configuration>
+          <instructions>
+            
<Bundle-Activator>org.amdatu.example.oauth.osgi.Activator</Bundle-Activator>
+            <Bundle-SymbolicName>org.amdatu.example.oauth</Bundle-SymbolicName>
+            <Embed-Dependency>*;scope=compile</Embed-Dependency>
+          </instructions>
+        </configuration>
+      </plugin>
+      
+    </plugins>
+    
+    <resources>
+      <resource>
+        <directory>src/main/resources</directory>
+        <filtering>false</filtering>
+        <excludes>
+          <exclude>conf/*.*</exclude>
+        </excludes>
+      </resource>
+      <resource>
+        <directory>src/main/resources</directory>
+        <filtering>true</filtering>
+        <includes>
+          <include>conf/*.*</include>
+        </includes>
+      </resource>
+    </resources>    
+  </build> 
+</project>

Added: 
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/osgi/Activator.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/osgi/Activator.java
       Wed Dec  8 15:43:24 2010
@@ -0,0 +1,67 @@
+/*
+    Copyright (C) 2010 Amdatu.org
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.amdatu.example.oauth.osgi;
+
+import org.amdatu.authentication.oauth.api.OAuthServiceConsumerRegistry;
+import org.amdatu.authentication.oauth.server.OAuthTokenProvider;
+import org.amdatu.example.oauth.service.DummyInterface;
+import org.amdatu.example.oauth.service.OAuthGadgetsRegistrationServiceImpl;
+import org.amdatu.example.oauth.service.OAuthProtectedResource;
+import org.amdatu.opensocial.gadgetmanagement.GadgetManagement;
+import org.amdatu.web.httpcontext.HttpContextServiceFactory;
+import org.amdatu.web.httpcontext.ResourceProvider;
+import org.apache.felix.dm.DependencyActivatorBase;
+import org.apache.felix.dm.DependencyManager;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.http.HttpService;
+import org.osgi.service.log.LogService;
+
+/**
+ * This is the OSGi activator for this bundle.
+ * @author ivol
+ */
+public class Activator extends DependencyActivatorBase {
+    // The resource identifier for this bundle. Resources are only considered 
to be 'ours' when
+    // it is prefixed with this id.
+    public final static String RESOURCE_ID = "examples/oauth";
+
+    @Override
+    public void init(BundleContext context, DependencyManager manager) throws 
Exception {
+        // Create the FriendsGadgetService which has dependencies with the Log 
service
+        // and HTTP service
+        manager.add(createComponent()
+                .setInterface(ResourceProvider.class.getName(), null)
+                .setImplementation(OAuthGadgetsRegistrationServiceImpl.class)
+                
.add(createServiceDependency().setService(LogService.class).setRequired(true))
+                
.add(createServiceDependency().setService(GadgetManagement.class).setRequired(true))
+                
.add(createServiceDependency().setService(HttpContextServiceFactory.class).setRequired(true))
+                
.add(createServiceDependency().setService(OAuthServiceConsumerRegistry.class).setRequired(true))
+                
.add(createServiceDependency().setService(HttpService.class).setRequired(true))
+                
.add(createConfigurationDependency().setPid(OAuthGadgetsRegistrationServiceImpl.PID)));
+        
+        manager.add(createComponent()
+                .setInterface(DummyInterface.class.getName(), null)
+                .setImplementation(OAuthProtectedResource.class)
+                
.add(createServiceDependency().setService(LogService.class).setRequired(true))
+                
.add(createServiceDependency().setService(OAuthTokenProvider.class).setRequired(true))
+                
.add(createServiceDependency().setService(OAuthServiceConsumerRegistry.class).setRequired(true)));
+    }
+
+    @Override
+    public void destroy(BundleContext arg0, DependencyManager arg1) throws 
Exception {
+    }
+}
\ No newline at end of file

Added: 
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/DummyInterface.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/DummyInterface.java
       Wed Dec  8 15:43:24 2010
@@ -0,0 +1,21 @@
+/*
+    Copyright (C) 2010 Amdatu.org
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.amdatu.example.oauth.service;
+
+public interface DummyInterface {
+
+}

Added: 
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthGadgetsRegistrationServiceImpl.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthGadgetsRegistrationServiceImpl.java
  Wed Dec  8 15:43:24 2010
@@ -0,0 +1,162 @@
+/*
+    Copyright (C) 2010 Amdatu.org
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.amdatu.example.oauth.service;
+
+import static org.amdatu.example.oauth.osgi.Activator.RESOURCE_ID;
+
+import java.net.URL;
+import java.util.Dictionary;
+import java.util.Map;
+
+import org.amdatu.authentication.oauth.api.ConsumerAlreadyExistsException;
+import org.amdatu.authentication.oauth.api.ConsumerNotFoundException;
+import org.amdatu.authentication.oauth.api.ConsumerRegistryStorageException;
+import org.amdatu.authentication.oauth.api.OAuthServiceConsumer;
+import org.amdatu.authentication.oauth.api.OAuthServiceConsumerRegistry;
+import org.amdatu.opensocial.gadgetmanagement.GadgetManagement;
+import org.amdatu.opensocial.shindig.GadgetCategory;
+import org.amdatu.opensocial.shindig.GadgetDefinition;
+import org.amdatu.web.httpcontext.HttpContextServiceFactory;
+import org.amdatu.web.httpcontext.ResourceProvider;
+import org.apache.felix.dm.Component;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.cm.ConfigurationException;
+import org.osgi.service.cm.ManagedService;
+import org.osgi.service.log.LogService;
+
+/**
+ * This service registers the oAuth example gadgets.
+ * @author ivol
+ */
+public class OAuthGadgetsRegistrationServiceImpl implements ResourceProvider, 
ManagedService {
+    // The PID and configuration properties
+    public final static String PID = "org.amdatu.example.oauth";
+    private final static String HOSTNAME = "hostname";
+    private final static String PORTNR = "portnr";
+
+    // oAuth properties of this gadget as service consumer
+    private final static String CONSUMER_CALLBACK_URL = 
"/gadgets/oauthcallback";
+    private final static String CONSUMER_KEY = "example.amdatu.org";
+    private final static String CONSUMER_SECRET = 
"HDHPBbhBHpoqwuyrvbxkvuBHOBEVxnlIOv";
+    private final static String CONSUMER_NAME = "Amdatu example consumer";
+    private final static String SERVICE_NAME = "oauth-example";
+
+    // Service and other dependencies, injected by the OSGi framework
+    private volatile HttpContextServiceFactory m_httpContextFactoryService;
+    private volatile LogService m_logService;
+    private volatile GadgetManagement m_gadgetManagement;
+    private volatile OAuthServiceConsumerRegistry m_consumerRegistry;
+
+    // Instance variables, injected by the OSGi framework
+    private BundleContext m_bundleContext;
+
+    // Other instance variables
+    private Component m_httpContextComponent;
+    private String m_hostname;
+    private String m_portnr;
+    /**
+     * The init() method is invoked by the Felix dependency manager.
+     */
+    public void init() {
+        // Create our own http context service
+        m_httpContextComponent = 
m_httpContextFactoryService.create(m_bundleContext, this);
+
+        if (m_hostname == null || m_portnr == null) {
+            // FIXME: For some reason update() is only invoked the very first 
time this service is created. When
+            // you stop/start the bundle, updated() will not be invoked (at 
all!) and so hostname and portnr remain
+            // null.
+        } else {
+            String baseUrl = "http://"; + m_hostname + ":" + m_portnr;
+            String gadgetUrl = baseUrl + "/" + RESOURCE_ID + 
"/jsp/3leggedOAuthGadget.jspf";
+            GadgetDefinition gadgetDef = new GadgetDefinition(gadgetUrl, 
GadgetCategory.AMDATU_EXAMPLES, false);
+
+            // Set oAuth parameters
+            gadgetDef.setServiceName(SERVICE_NAME);
+            gadgetDef.setConsumerPublicKey(CONSUMER_KEY);
+            gadgetDef.setConsumerPrivateKey(CONSUMER_SECRET);
+            gadgetDef.setCallbackUrl(CONSUMER_CALLBACK_URL);
+
+            m_gadgetManagement.addGadget(gadgetDef);
+
+            // Register the service consumer in our own oAuth server such that 
our own oAuth server
+            // can also handle oAuth of this gadget
+            registerConsumer();
+        }
+        m_logService.log(LogService.LOG_INFO, getClass().getName() + " service 
initialized");
+    }
+
+    /**
+     * The destroy() method is invoked by the Felix dependency manager.
+     */
+    public void destroy() {
+        // Stop our private HTTP Context service
+        m_httpContextComponent.stop();
+
+        m_logService.log(LogService.LOG_INFO, getClass().getName() + " service 
destroyed");
+    }
+
+    public URL getResource(String name) {
+        return null;
+    }
+
+    public String getResourceId() {
+        return RESOURCE_ID;
+    }
+
+    public void updated(Dictionary dictionary) throws ConfigurationException {
+        if (dictionary != null) {
+            checkAvailability(dictionary, new String[] {HOSTNAME, PORTNR});
+            m_hostname = (String) dictionary.get(HOSTNAME);
+            m_portnr = (String) dictionary.get(PORTNR);
+        }
+    }
+
+    private void checkAvailability(Dictionary dictionary, String[] 
mandatoryKeys) throws ConfigurationException {
+        for (String mandatoryKey : mandatoryKeys) {
+            if (dictionary.get(mandatoryKey) == null) {
+                throw new ConfigurationException("Missing configuration key", 
mandatoryKey);
+            }
+        }
+    }
+
+    private void registerConsumer() {
+        try {
+            if (m_consumerRegistry.getConsumer(CONSUMER_KEY) == null) {
+                m_consumerRegistry.addConsumer(new 
InternalOAuthServiceConsumer());
+            } else {
+                m_consumerRegistry.updateConsumer(new 
InternalOAuthServiceConsumer());
+            }
+        }
+        catch (ConsumerAlreadyExistsException e) {
+            m_logService.log(LogService.LOG_DEBUG, "Could not properly add 
service consumer '" + CONSUMER_KEY + "' in the service consumer registry");
+        }
+        catch (ConsumerRegistryStorageException e) {
+            m_logService.log(LogService.LOG_DEBUG, "Could not properly add or 
update service consumer '" + CONSUMER_KEY + "' in the service consumer 
registry");
+        }
+        catch (ConsumerNotFoundException e) {
+            m_logService.log(LogService.LOG_DEBUG, "Could not properly update 
service consumer '" + CONSUMER_KEY + "' in the service consumer registry");
+        }
+    }
+
+    class InternalOAuthServiceConsumer implements OAuthServiceConsumer {
+        public String getCallbackUrl() {return CONSUMER_CALLBACK_URL;}
+        public String getConsumerKey() {return CONSUMER_KEY;}
+        public String getConsumerSecret() {return CONSUMER_SECRET;}
+        public String getName() {return CONSUMER_NAME;}
+        public Map<String, String> getProperties() {return null;}
+    }
+}

Added: 
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthProtectedResource.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-example/oauth/src/main/java/org/amdatu/example/oauth/service/OAuthProtectedResource.java
       Wed Dec  8 15:43:24 2010
@@ -0,0 +1,98 @@
+/*
+    Copyright (C) 2010 Amdatu.org
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.amdatu.example.oauth.service;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import net.oauth.OAuthAccessor;
+import net.oauth.OAuthConsumer;
+import net.oauth.OAuthException;
+import net.oauth.OAuthMessage;
+import net.oauth.server.OAuthServlet;
+
+import org.amdatu.authentication.oauth.api.OAuthServiceConsumerRegistry;
+import org.amdatu.authentication.oauth.server.OAuthTokenProvider;
+import org.osgi.service.log.LogService;
+
+/**
+ * Full path to this resource becomes: /rest/services/resource/resource
+ * 
+ * @author ivol
+ * 
+ */
+ at Path("resource")
+public class OAuthProtectedResource implements DummyInterface {
+    private volatile LogService m_logService;
+    private volatile OAuthTokenProvider m_tokenProvider;
+    private volatile OAuthServiceConsumerRegistry m_consumerRegistry;
+
+    @GET
+    @Produces( { MediaType.TEXT_HTML })
+    public Response getResource(@Context HttpServletRequest request) {
+        try {
+            String response = "<p>oAuth validation successfull. OAuth 
parameters received by service provider:<br/><br/>";
+            response += "<table><tr><th align=\"left\">parameter</th><th 
align=\"left\">value</th></tr>";
+            OAuthAccessor accessor = validateOAuth(request);
+            response += "<tr><td>request token</td><td>" + 
accessor.requestToken + "</td></tr>";
+            response += "<tr><td>token secret</td><td>" + accessor.tokenSecret 
+ "</td></tr>";
+            response += "<tr><td>access token</td><td>" + accessor.accessToken 
+ "</td></tr>";
+            response += "<tr><td>consumer key</td><td>" + 
accessor.consumer.consumerKey + "</td></tr>";
+            response += "<tr><td>consumer secret</td><td>" + 
accessor.consumer.consumerSecret + "</td></tr>";
+            response += "<tr><td>consumer callback url</td><td>" + 
accessor.consumer.callbackURL + "</td></tr>";
+            response += "</table></p>";
+            return Response.ok(response, MediaType.TEXT_HTML).build();
+        }
+        catch (IOException e) {
+            return Response.serverError().build();
+        }
+        catch (OAuthException e) {
+            return Response.serverError().build();
+        }
+        catch (URISyntaxException e) {
+            return Response.serverError().build();
+        }
+    }
+
+    private OAuthAccessor validateOAuth(HttpServletRequest request) throws 
IOException, OAuthException,
+        URISyntaxException {
+        OAuthMessage requestMessage = OAuthServlet.getMessage(request, null);
+
+        // In case of tow-legged or three-legged oAuth, the oAuth message 
contains a request or access token
+        // A Signed request however doesn't provide a token, we first verify 
the type of oAuth request
+        OAuthAccessor accessor;
+        if (requestMessage.getToken() == null || 
"".equals(requestMessage.getToken())) {
+            // This is a signed request
+            OAuthConsumer consumer = 
m_tokenProvider.getConsumer(requestMessage);
+            accessor = new OAuthAccessor(consumer);
+        }
+        else {
+            // This is 2-legged or 3-legged oAuth
+            accessor = m_tokenProvider.getAccessor(requestMessage);
+        }
+        m_tokenProvider.getOAuthValidator().validateMessage(requestMessage, 
accessor);
+        return accessor;
+    }
+}

Added: trunk/amdatu-example/oauth/src/main/resources/jsp/3leggedOAuthGadget.jspf
==============================================================================
--- (empty file)
+++ trunk/amdatu-example/oauth/src/main/resources/jsp/3leggedOAuthGadget.jspf   
Wed Dec  8 15:43:24 2010
@@ -0,0 +1,123 @@
+<%@ page language="java" session="false" buffer="none" %>
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"; %>
+
+<c:set var="baseUrl" 
value="http://${pageContext.request.serverName}:${pageContext.request.serverPort}"/>
+
+<?xml version="1.0" encoding="UTF-8" ?>
+<!--
+ * 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.
+-->
+<Module>
+  <ModulePrefs 
+    title="3-legged OAuth Example Gadget" 
+    description="Displays information protected by 3-legged oAuth"
+    author="Ivo Ladage-van Doorn"
+    screenshot="/examples/oauth/static/img/oauth_logo.png"
+    icon="/examples/oauth/static/img/oauth_logo.png">
+    
+    <Require feature="opensocial-0.9"/>
+    <Require feature="oauthpopup" />
+    <Require feature="dynamic-height"/>
+    <OAuth>
+      <Service name="oauth-example">
+        <Request url="${baseUrl}/oauth-server/requesttoken" />
+        <Access url="${baseUrl}/oauth-server/accesstoken" />
+        <Authorization url="${baseUrl}/oauth-server/authorizetoken" />
+      </Service>
+    </OAuth>       
+  </ModulePrefs>
+  <Content type="html">
+    <![CDATA[
+    <link rel="stylesheet" href="/dashboard/static/css/dashboard.css">
+    
+    <div id="main" style="display: none">
+    </div>
+
+    <div id="approval" style="display: none">
+      <p>
+        <img src="${baseUrl}/dashboard/static/img/new.gif">
+        <a href="#" id="personalize">Personalize this gadget</a>
+      </p>
+    </div>
+
+    <div id="waiting" style="display: none">
+      <p>
+        Please click <a href="#" id="approvaldone">I've approved access</a>
+        once you've approved access to your data.
+      </p>
+    </div>
+
+    <script type="text/javascript">
+      function $(x) {
+        return document.getElementById(x);
+      }
+
+      function showOneSection(toshow) {
+        var sections = [ 'main', 'approval', 'waiting' ];
+        for (var i=0; i < sections.length; ++i) {
+          var s = sections[i];
+          var el = $(s);
+          if (s === toshow) {
+            el.style.display = "block";
+          } else {
+            el.style.display = "none";
+          }
+        }
+      }
+
+      function fetchData() {
+        var url = "${baseUrl}/rest/services/resource/resource";
+        var params = {};
+        params[gadgets.io.RequestParameters.CONTENT_TYPE] = 
gadgets.io.ContentType.TEXT;
+        params[gadgets.io.RequestParameters.AUTHORIZATION] = 
gadgets.io.AuthorizationType.OAUTH;
+        params[gadgets.io.RequestParameters.METHOD] = 
gadgets.io.MethodType.GET;
+        params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = 
"oauth-example";
+
+        gadgets.io.makeRequest(url, function (response) {
+          if (response.oauthApprovalUrl) {
+            var onOpen = function() {
+              showOneSection('waiting');
+            };
+            var onClose = function() {
+              fetchData();
+            };
+            var popup = new gadgets.oauth.Popup(response.oauthApprovalUrl,
+                null, onOpen, onClose);
+            $('personalize').onclick = popup.createOpenerOnClick();
+            $('approvaldone').onclick = popup.createApprovedOnClick();
+            showOneSection('approval');
+          } else if (response.data) {
+            document.getElementById('main').innerHTML = response.data;
+            showOneSection('main');
+            gadgets.window.adjustHeight(250);
+          } else {
+            var whoops = document.createTextNode(
+                'OAuth error: ' + response.oauthError + ': ' +
+                response.oauthErrorText);
+            $('main').appendChild(whoops);
+            showOneSection('main');
+          }
+        }, params);
+      }
+
+      gadgets.util.registerOnLoadHandler(fetchData);
+    </script>
+    
+    ]]>
+  </Content>
+</Module>

Added: trunk/amdatu-example/oauth/src/main/resources/static/img/oauth_logo.png
==============================================================================
Binary file. No diff available.

Modified: trunk/amdatu-example/pom.xml
==============================================================================
--- trunk/amdatu-example/pom.xml        (original)
+++ trunk/amdatu-example/pom.xml        Wed Dec  8 15:43:24 2010
@@ -107,6 +107,7 @@
     <module>course-gadget</module>
     <module>course-service</module>
     <module>friends-gadget</module>
+    <module>oauth</module>
   </modules>
 
 </project>
\ No newline at end of file

Added: trunk/amdatu-opensocial/dashboard/src/main/resources/static/img/new.gif
==============================================================================
Binary file. No diff available.

Modified: 
trunk/amdatu-opensocial/shindig/src/main/java/org/amdatu/opensocial/shindig/persistence/CassandraOAuthStore.java
==============================================================================
--- 
trunk/amdatu-opensocial/shindig/src/main/java/org/amdatu/opensocial/shindig/persistence/CassandraOAuthStore.java
    (original)
+++ 
trunk/amdatu-opensocial/shindig/src/main/java/org/amdatu/opensocial/shindig/persistence/CassandraOAuthStore.java
    Wed Dec  8 15:43:24 2010
@@ -66,6 +66,8 @@
     }
     
     // load the initial consumers
+    // TODO: this doesn't work properly in flexible environment where gadgets 
are added and removed from the store
+    // continuously.
     private void loadConsumers() {
         GadgetDefinition[] gadgets = m_gadgetStore.getGadgets();
         for (GadgetDefinition gadget : gadgets) {
@@ -99,6 +101,19 @@
             BasicOAuthStoreConsumerKeyAndSecret keyAndSecret) {
         m_consumerInfos.put(providerKey, keyAndSecret);
     }
+    
+    // FIXME: for now we provide an update method that in case a token is 
retrieved for a recently added gadget
+    private void update() {
+        GadgetDefinition[] gadgets = m_gadgetStore.getGadgets();
+        for (GadgetDefinition gadget : gadgets) {
+            BasicOAuthStoreConsumerIndex pk = new 
BasicOAuthStoreConsumerIndex();
+            pk.setGadgetUri(gadget.getUrl());
+            pk.setServiceName(gadget.getServiceName());
+            if (m_consumerInfos.get(pk) == null) {
+                addConsumerInfo(gadget);
+            }
+        }
+    }
 
     public ConsumerInfo getConsumerKeyAndSecret(SecurityToken securityToken, 
String serviceName,
             OAuthServiceProvider provider) throws GadgetException {
@@ -108,7 +123,12 @@
         pk.setServiceName(serviceName);
         BasicOAuthStoreConsumerKeyAndSecret cks = m_consumerInfos.get(pk);
         if (cks == null) {
-            cks = m_gadgetStore.getDefaultKey();
+            // Check if the gadget has recently been added
+            update();
+            cks = m_consumerInfos.get(pk);
+            if (cks == null) {
+                cks = m_gadgetStore.getDefaultKey();
+            }
         }
         if (cks == null) {
             throw new 
GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, "No key for gadget "

Modified: trunk/amdatu-release/pom.xml
==============================================================================
--- trunk/amdatu-release/pom.xml        (original)
+++ trunk/amdatu-release/pom.xml        Wed Dec  8 15:43:24 2010
@@ -158,6 +158,13 @@
       <scope>compile</scope>
       <type>bundle</type>
     </dependency>
+    <dependency>
+      <groupId>org.amdatu.example</groupId>
+      <artifactId>oauth</artifactId>
+      <version>${platform.version}</version>
+      <scope>compile</scope>
+      <type>bundle</type>
+    </dependency>    
 
     <!-- Open Social bundles -->
     <dependency>

Modified: trunk/src/main/resources/conf/felix-config.properties
==============================================================================
--- trunk/src/main/resources/conf/felix-config.properties       (original)
+++ trunk/src/main/resources/conf/felix-config.properties       Wed Dec  8 
15:43:24 2010
@@ -123,7 +123,8 @@
           
reference:file:amdatu-application/org.amdatu.authentication.oauth.consumerregistry-fs-${platform.version}.jar
 
felix.auto.start.20=reference:file:amdatu-examples/org.amdatu.example.friends.gadget-${platform.version}.jar
 \
           
reference:file:amdatu-examples/org.amdatu.example.course.gadget-${platform.version}.jar
 \
-          
reference:file:amdatu-examples/org.amdatu.example.course.service-${platform.version}.jar
+          
reference:file:amdatu-examples/org.amdatu.example.course.service-${platform.version}.jar
 \
+          
reference:file:amdatu-examples/org.amdatu.example.oauth-${platform.version}.jar
 
 # Sets the initial start level of the framework upon startup.
 org.osgi.framework.startlevel.beginning=30

Reply via email to