Author: [email protected]
Date: Fri Jun 24 10:29:10 2011
New Revision: 1194

Log:
Added OAuth twitter example

Added:
   sandbox/ivol/twitter-example/
   sandbox/ivol/twitter-example/pom.xml
   sandbox/ivol/twitter-example/src/
   sandbox/ivol/twitter-example/src/main/
   sandbox/ivol/twitter-example/src/main/java/
   sandbox/ivol/twitter-example/src/main/java/org/
   sandbox/ivol/twitter-example/src/main/java/org/amdatu/
   sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/
   sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/
   sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/AmdatuTwitterClient.java
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/TweetService.java
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/TwitterServiceProvider.java
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/osgi/
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/osgi/Activator.java
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/AmdatuTwitterClientImpl.java
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/TweetGadgetImpl.java
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/TweetServiceImpl.java
   
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/TwitterServiceProviderImpl.java
   sandbox/ivol/twitter-example/src/main/resources/
   sandbox/ivol/twitter-example/src/main/resources/jsp/
   sandbox/ivol/twitter-example/src/main/resources/jsp/TweetGadget.jsp
   sandbox/ivol/twitter-example/src/main/resources/jsp/TweetPage.jsp
   sandbox/ivol/twitter-example/src/main/resources/static/
   sandbox/ivol/twitter-example/src/main/resources/static/images/
   sandbox/ivol/twitter-example/src/main/resources/static/images/twitter.png   
(contents, props changed)
   
sandbox/ivol/twitter-example/src/main/resources/static/images/twitter_small.png 
  (contents, props changed)

Added: sandbox/ivol/twitter-example/pom.xml
==============================================================================
--- (empty file)
+++ sandbox/ivol/twitter-example/pom.xml        Fri Jun 24 10:29:10 2011
@@ -0,0 +1,131 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Copyright (c) 2010, 2011 The Amdatu Foundation
+
+  Licensed 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.verning permissions and limitations
+  under the License.
+-->
+<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.auth</groupId>
+    <artifactId>org.amdatu.auth</artifactId>
+    <version>0.2.0-SNAPSHOT</version>
+  </parent>
+  <artifactId>org.amdatu.auth.example.oauth.twitter</artifactId>
+  <packaging>bundle</packaging>
+  <name>Amdatu Auth - Twitter oAuth example</name>
+  <description>Provides an example Twitter client application using OAuth. The 
example sends twitter messages on behalf of a Twitter user.</description>
+
+  <properties>
+    <amdatu.opensocial.version>0.2.0-SNAPSHOT</amdatu.opensocial.version>
+  </properties>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.amdatu.web</groupId>
+      <artifactId>org.amdatu.web.dispatcher</artifactId>
+      <type>bundle</type>
+    </dependency>
+    <dependency>
+      <groupId>org.amdatu.web</groupId>
+      <artifactId>org.amdatu.web.httpcontext</artifactId>
+      <type>bundle</type>
+    </dependency>
+    <dependency>
+      <groupId>org.amdatu.web</groupId>
+      <artifactId>org.amdatu.web.jsp</artifactId>
+      <type>bundle</type>
+    </dependency>
+    <dependency>
+      <groupId>org.amdatu.web</groupId>
+      <artifactId>org.amdatu.web.resource</artifactId>
+      <type>bundle</type>
+    </dependency>
+    <dependency>
+      <groupId>org.amdatu.opensocial</groupId>
+      <artifactId>org.amdatu.opensocial.gadgetmanagement</artifactId>
+      <version>${amdatu.opensocial.version}</version>
+      <scope>provided</scope>
+      <type>bundle</type>
+    </dependency>
+    <dependency>
+      <groupId>org.amdatu.auth</groupId>
+      <artifactId>org.amdatu.auth.oauth.api</artifactId>
+      <type>bundle</type>
+    </dependency>
+    <dependency>
+      <groupId>org.amdatu.auth</groupId>
+      <artifactId>org.amdatu.auth.oauth.client</artifactId>
+      <type>bundle</type>
+    </dependency>
+    <dependency>
+      <groupId>org.amdatu.web</groupId>
+      <artifactId>org.amdatu.web.jaxrs</artifactId>
+      <type>bundle</type>
+    </dependency>
+    <dependency>
+      <groupId>org.amdatu.libraries</groupId>
+      <artifactId>org.amdatu.libraries.utilities</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>commons-httpclient</groupId>
+      <artifactId>commons-httpclient</artifactId>
+      <version>3.1</version>
+      <scope>compile</scope>
+    </dependency>
+    <dependency>
+      <groupId>commons-codec</groupId>
+      <artifactId>commons-codec</artifactId>
+      <version>1.4</version>
+      <scope>compile</scope>
+    </dependency>
+    <dependency>
+      <groupId>commons-logging</groupId>
+      <artifactId>commons-logging</artifactId>
+      <version>1.1.1</version>
+      <scope>compile</scope>
+    </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.auth.example.oauth.twitter.osgi.Activator</Bundle-Activator>
+            
<Bundle-SymbolicName>org.amdatu.auth.example.oauth.twitter</Bundle-SymbolicName>
+            <Embed-Dependency>*;scope=compile</Embed-Dependency>
+            <Import-Package>
+              !org.apache.avalon.framework.logger,
+              !org.apache.log,
+              !org.apache.log4j,
+              *
+            </Import-Package>
+            <Export-Package></Export-Package>
+          </instructions>
+        </configuration>
+      </plugin>
+
+    </plugins>
+  </build>
+</project>

Added: 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/AmdatuTwitterClient.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/AmdatuTwitterClient.java
   Fri Jun 24 10:29:10 2011
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2010, 2011 The Amdatu Foundation
+ *
+ * Licensed 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.amdatu.auth.example.oauth.twitter;
+
+import net.oauth.OAuthConsumer;
+import net.oauth.OAuthServiceProvider;
+
+import org.amdatu.authentication.oauth.api.OAuthServiceConsumer;
+
+public interface AmdatuTwitterClient extends OAuthServiceConsumer {
+    OAuthConsumer toOAuthConsumer(OAuthServiceProvider provider);
+}

Added: 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/TweetService.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/TweetService.java
  Fri Jun 24 10:29:10 2011
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2010, 2011 The Amdatu Foundation
+ *
+ * Licensed 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.amdatu.auth.example.oauth.twitter;
+
+public interface TweetService {
+
+}

Added: 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/TwitterServiceProvider.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/TwitterServiceProvider.java
        Fri Jun 24 10:29:10 2011
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2010, 2011 The Amdatu Foundation
+ *
+ * Licensed 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.amdatu.auth.example.oauth.twitter;
+
+import org.amdatu.authentication.oauth.api.OAuthServiceProvider;
+
+
+public interface TwitterServiceProvider extends OAuthServiceProvider {
+    net.oauth.OAuthServiceProvider toOAuthProvider();
+}

Added: 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/osgi/Activator.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/osgi/Activator.java
        Fri Jun 24 10:29:10 2011
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2010, 2011 The Amdatu Foundation
+ *
+ * Licensed 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.amdatu.auth.example.oauth.twitter.osgi;
+
+import java.util.Dictionary;
+import java.util.Hashtable;
+
+import org.amdatu.auth.example.oauth.twitter.AmdatuTwitterClient;
+import org.amdatu.auth.example.oauth.twitter.TweetService;
+import org.amdatu.auth.example.oauth.twitter.TwitterServiceProvider;
+import org.amdatu.auth.example.oauth.twitter.service.AmdatuTwitterClientImpl;
+import org.amdatu.auth.example.oauth.twitter.service.TweetGadgetImpl;
+import org.amdatu.auth.example.oauth.twitter.service.TweetServiceImpl;
+import 
org.amdatu.auth.example.oauth.twitter.service.TwitterServiceProviderImpl;
+import org.amdatu.authentication.oauth.api.OAuthServiceConsumerRegistry;
+import org.amdatu.libraries.utilities.osgi.ServiceDependentActivator;
+import org.amdatu.opensocial.gadgetmanagement.GadgetManagement;
+import org.amdatu.web.dispatcher.DispatcherService;
+import org.amdatu.web.httpcontext.ResourceProvider;
+import org.amdatu.web.jsp.JspSupport;
+import org.amdatu.web.resource.ResourceSupport;
+import org.amdatu.web.rest.jaxrs.JaxRsSpi;
+import org.apache.felix.dm.DependencyManager;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.log.LogService;
+
+/**
+ * This is the activator for the authentication bundle.
+ *
+ * @author ivol
+ */
+public class Activator extends ServiceDependentActivator {
+    /**
+     * URL alias hosting the resources of this Twitter example.
+     */
+    public static final String ALIAS = "/example/twitter";
+    
+    /**
+     * URL alias hosting the JSPs of this Twitter example.
+     */
+    public static final String JSP_ALIAS = ALIAS + "/jsp";
+
+    /**
+     * URL alias hosting the statics of this Twitter example.
+     */
+    public static final String RES_ALIAS = ALIAS + "/static";
+    
+    /**
+     * Context id of the Example HTTP Context.
+     */
+    public static final String CONTEXTID = "amdatu-example";
+    
+    @Override
+    protected Class<?>[] getRequiredServices() {
+        return new Class<?>[] {JaxRsSpi.class};
+    }
+    
+    @Override
+    public void initWithDependencies(final BundleContext context, final 
DependencyManager manager) throws Exception {
+        // Register the tweet gadget
+        Dictionary<String, Object> properties = new Hashtable<String, 
Object>();
+        properties.put(DispatcherService.CONTEXT_ID_KEY, CONTEXTID);
+        properties.put(JspSupport.JSP_ALIAS_KEY, JSP_ALIAS);
+        properties.put(ResourceSupport.RESOURCE_ALIAS_KEY, RES_ALIAS);
+
+        
manager.add(createComponent().setInterface(ResourceProvider.class.getName(), 
properties)
+            .setImplementation(TweetGadgetImpl.class)
+            
.add(createServiceDependency().setService(LogService.class).setRequired(true))
+            
.add(createServiceDependency().setService(GadgetManagement.class).setRequired(true)));
+        
+        // Create and register the tweet service.
+        manager.add(createComponent()
+                .setInterface(TweetService.class.getName(), null)
+                .setImplementation(TweetServiceImpl.class)
+                
.add(createServiceDependency().setService(LogService.class).setRequired(true))
+                
.add(createServiceDependency().setService(AmdatuTwitterClient.class).setRequired(true))
+                
.add(createServiceDependency().setService(TwitterServiceProvider.class).setRequired(true)));
+        
+        // Create and register the Amdatu Twitter Client (the OAuth service 
consumer).
+        manager.add(createComponent()
+                .setInterface(AmdatuTwitterClient.class.getName(), null)
+                .setImplementation(AmdatuTwitterClientImpl.class)
+                
.add(createServiceDependency().setService(LogService.class).setRequired(true))
+                
.add(createServiceDependency().setService(OAuthServiceConsumerRegistry.class).setRequired(true)));
  
+        
+        // Create and register the Twitter Service Provider (the OAuth service 
provider).
+        manager.add(createComponent()
+                .setInterface(TwitterServiceProvider.class.getName(), null)
+                .setImplementation(TwitterServiceProviderImpl.class)
+                
.add(createServiceDependency().setService(LogService.class).setRequired(true)));
           
+    }
+
+    @Override
+    public void destroy(final BundleContext context, final DependencyManager 
manager) throws Exception {
+    }
+}

Added: 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/AmdatuTwitterClientImpl.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/AmdatuTwitterClientImpl.java
       Fri Jun 24 10:29:10 2011
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2010, 2011 The Amdatu Foundation
+ *
+ * Licensed 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.amdatu.auth.example.oauth.twitter.service;
+
+import java.util.Map;
+
+import net.oauth.OAuthConsumer;
+import net.oauth.OAuthServiceProvider;
+
+import org.amdatu.auth.example.oauth.twitter.AmdatuTwitterClient;
+import org.amdatu.authentication.oauth.api.ConsumerAlreadyExistsException;
+import org.amdatu.authentication.oauth.api.ConsumerRegistryStorageException;
+import org.amdatu.authentication.oauth.api.OAuthServiceConsumerRegistry;
+import org.osgi.service.log.LogService;
+
+public class AmdatuTwitterClientImpl implements AmdatuTwitterClient {
+    // Logical name of our client
+    private static final String CONSUMER_NAME = "Amdatu Twitter Client";
+    
+    // The consumer key is provided by Twitter with the registration of this 
application.
+    // Note that the API key and Consumer key are one and the same
+    private static final String CONSUMER_KEY = "ZdODivCUkfHAHHargOB7g";
+    
+    // The consumer secret is provided by Twitter with the registration of 
this application
+    private static final String CONSUMER_SECRET = 
"s1pLl4jcRU9OF9Y8BcZuOa7gzpAUAnNmxWNenKh81g";
+    
+    // Callback URL for OAuth negotiation. This URL will invoked by Twitter 
when the user
+    // authorized the request token and so we are ready to exchange the 
request token for
+    // an access token.
+    private static final String OAUTH_CALLBACK_URL = 
"http://localhost:3337/rest/example/twitter/oauthcallback";;
+    
+    private volatile LogService m_logService;
+    private volatile OAuthServiceConsumerRegistry m_consumerRegistry;
+    
+    public void start() {
+        try {
+            m_consumerRegistry.addConsumer(this);
+        }
+        catch (ConsumerAlreadyExistsException e) {
+            // Do nothing
+        }
+        catch (ConsumerRegistryStorageException e) {
+            m_logService.log(LogService.LOG_ERROR,
+                "Could not register Amdatu Twitter Client as OAuth Service 
Consumer", e);
+            throw new RuntimeException("Could not register Amdatu Twitter 
Client as OAuth Service Consumer");
+        }
+        
+        m_logService.log(LogService.LOG_INFO, "Amdatu Twitter Client started");
+    }
+    
+    public String getName() {
+        return CONSUMER_NAME;
+    }
+
+    public String getConsumerKey() {
+        return CONSUMER_KEY;
+    }
+
+    public String getConsumerSecret() {
+        return CONSUMER_SECRET;
+    }
+
+    public String getCallbackUrl() {
+        return OAUTH_CALLBACK_URL;
+    }
+
+    public Map<String, String> getProperties() {
+        return null;
+    }
+    
+    public OAuthConsumer toOAuthConsumer(OAuthServiceProvider provider) {
+        // TODO Auto-generated method stub
+        return new OAuthConsumer(OAUTH_CALLBACK_URL, CONSUMER_KEY, 
CONSUMER_SECRET, provider);
+    }
+}

Added: 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/TweetGadgetImpl.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/TweetGadgetImpl.java
       Fri Jun 24 10:29:10 2011
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2010, 2011 The Amdatu Foundation
+ *
+ * Licensed 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.amdatu.auth.example.oauth.twitter.service;
+
+import java.net.URL;
+
+import org.amdatu.auth.example.oauth.twitter.osgi.Activator;
+import org.amdatu.opensocial.gadgetmanagement.GadgetCategory;
+import org.amdatu.opensocial.gadgetmanagement.GadgetDefinition;
+import org.amdatu.opensocial.gadgetmanagement.GadgetManagement;
+import org.amdatu.web.httpcontext.ResourceProvider;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.log.LogService;
+
+public class TweetGadgetImpl implements ResourceProvider {
+    // JSP for the tweet gadget
+    private static final String GADGET_JSP =  "/jsp/TweetGadget.jsp";
+    
+    //Default category for Amdatu example gadgets.
+    private static final GadgetCategory AMDATU_EXAMPLES = new 
GadgetCategory("amdatu_examples", "Amdatu Examples");
+    
+    // Service dependencies, injected by the Felix dependency manager
+    private volatile LogService m_logService;
+    private volatile BundleContext m_bundleContext;
+    private volatile GadgetManagement m_gadgetManagement;
+
+    /**
+     * The init() method is invoked by the Felix dependency manager.
+     */
+    public void start() {
+
+        // Register the gadget with the Gadget management service. Note that 
we can do this as
+        // many times as we want, since the gadget URL is the unique identifier
+        String gadgetSpecUrl = Activator.ALIAS + GADGET_JSP;
+        GadgetDefinition gadgetDef = new GadgetDefinition(gadgetSpecUrl, 
AMDATU_EXAMPLES, true);
+        gadgetDef.setRank(0);
+        m_gadgetManagement.addGadget(gadgetDef);
+        m_logService.log(LogService.LOG_INFO, "Tweet gadget registered on URL 
'" + gadgetSpecUrl + "'");
+
+        m_logService.log(LogService.LOG_INFO, getClass().getName() + " service 
started");
+    }
+
+    public URL getResource(final String name) {
+        final String pathPrefix = Activator.ALIAS + "/";
+        if (name != null && name.startsWith(pathPrefix)) {
+            return 
m_bundleContext.getBundle().getResource(name.substring(pathPrefix.length()));
+        }
+        return null;
+    }
+}

Added: 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/TweetServiceImpl.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/TweetServiceImpl.java
      Fri Jun 24 10:29:10 2011
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 2010, 2011 The Amdatu Foundation
+ *
+ * Licensed 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.amdatu.auth.example.oauth.twitter.service;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.OAuth;
+import net.oauth.OAuthAccessor;
+import net.oauth.OAuthException;
+import net.oauth.OAuthMessage;
+
+import org.amdatu.auth.example.oauth.twitter.AmdatuTwitterClient;
+import org.amdatu.auth.example.oauth.twitter.TweetService;
+import org.amdatu.auth.example.oauth.twitter.TwitterServiceProvider;
+import org.amdatu.authentication.oauth.client.OAuthServiceConsumerClient;
+import org.apache.http.HttpStatus;
+import org.json.JSONException;
+import org.osgi.service.log.LogService;
+
+/**
+ * @author ivol
+ */
+@Path("example/twitter")
+public class TweetServiceImpl implements TweetService {
+    private final static String TWEET_MSG =
+        "Check out this new cool open source cloud platform named #Amdatu on 
http://amdatu.org";;
+
+    private volatile LogService m_logService;
+    private volatile AmdatuTwitterClient m_serviceConsumer;
+    private volatile TwitterServiceProvider m_serviceProvider;
+
+    private OAuthServiceConsumerClient m_oauthClient;
+
+    // map for storing token secrets with the tokens
+    private Map<String, String> m_tokens = new HashMap<String, String>();
+
+    public void start() {
+        // Create an OAuthClient
+        m_oauthClient = new OAuthServiceConsumerClient(m_serviceProvider, 
m_serviceConsumer);
+
+        m_logService.log(LogService.LOG_INFO, "Tweet service started");
+    }
+
+    /**
+     * This method can be used to check the availability of the Tweet Service.
+     * 
+     * @return The text "Tweet service online"
+     */
+    @GET
+    @Path("status")
+    @Produces({MediaType.TEXT_PLAIN})
+    public String status() {
+        return "Tweet service online";
+    }
+
+    /**
+     * This method will tweet a message on the users behalf. So we use the 
OAuth protected Twitter API to do so.
+     */
+    @POST
+    @Path("tweet")
+    public Response tweet() {
+        try {
+            // Step 1. Get a request token and token secret from Twitter
+            m_logService.log(LogService.LOG_DEBUG, "Retrieving request token 
from Twitter");
+            OAuthAccessor accessor = createRequestToken();
+
+            // Step 2: Remember the token secret associated with this request 
token
+            m_tokens.put(accessor.requestToken, accessor.tokenSecret);
+
+            // Step 3: Let the user redirect to the authorize URL
+            // a. Append Auth request token and callback URL to the authorize 
URL
+            String authorizeURL = m_serviceProvider.getAuthorizeURL();
+            authorizeURL = OAuth.addParameters(authorizeURL, 
OAuth.OAUTH_TOKEN, accessor.requestToken);
+            authorizeURL = OAuth.addParameters(authorizeURL, 
OAuth.OAUTH_CALLBACK, m_serviceConsumer.getCallbackUrl());
+
+            // b. Send client-side redirect to the authorize URL
+            return 
Response.status(HttpStatus.SC_MOVED_TEMPORARILY).location(new 
URI(authorizeURL)).build();
+        }
+        catch (Exception e) {
+            return Response.serverError().entity(e.toString()).build();
+        }
+    }
+
+    @GET
+    @Path("oauthcallback")
+    @Produces({MediaType.TEXT_PLAIN})
+    public Response oAuthCallback(@Context final HttpServletRequest request) {
+        try {
+            String token = request.getParameter("oauth_token");
+            String verifier = request.getParameter("oauth_verifier");
+
+            // Create the accessor
+            OAuthAccessor accessor =
+                new 
OAuthAccessor(m_serviceConsumer.toOAuthConsumer(m_serviceProvider.toOAuthProvider()));
+            accessor.requestToken = token;
+            accessor.tokenSecret = m_tokens.get(token);
+            accessor.setProperty(OAuth.OAUTH_VERIFIER, verifier);
+
+            // Exchange request token for access token
+            OAuthMessage message = m_oauthClient.getAccessToken(accessor);
+            String accessToken = message.getToken();
+
+            String msg = "Exchanged request token for access token:\r\n";
+            msg += "  Access token = " + accessToken + "\r\n";
+            msg += "  Token secret = " + 
message.getParameter("oauth_token_secret") + "\r\n";
+            msg += "  User id = " + message.getParameter("user_id") + "\r\n";
+            msg += "  User name = " + message.getParameter("screen_name") + 
"\r\n";
+            m_logService.log(LogService.LOG_INFO, msg);
+
+            // Update the accessor
+            accessor.requestToken = null;
+            accessor.accessToken = accessToken;
+            accessor.tokenSecret = message.getParameter("oauth_token_secret");
+
+            m_logService.log(LogService.LOG_INFO, "Account Totals: " + 
getAccountTotals(accessor));
+            m_logService.log(LogService.LOG_INFO, "Account Verify Credentials: 
"
+                + getAccountVerifyCredentials(accessor));
+
+            m_logService.log(LogService.LOG_INFO, "Result: " + 
tweetMessage(accessor));
+
+            // Redirect to twitter such that we can see the Tweet
+            return Response.seeOther(new URI("http://twitter.com/";)).build();
+            
+  //          return Response.ok("OK").build();
+        }
+        catch (Exception e) {
+            return Response.serverError().entity(e.toString()).build();
+        }
+    }
+
+    private OAuthAccessor createRequestToken() throws IOException, 
OAuthException,
+        URISyntaxException {
+        OAuthAccessor accessor = m_oauthClient.generateRequestToken();
+        String requestToken = accessor.requestToken;
+        String tokenSecret = accessor.tokenSecret;
+        m_logService.log(LogService.LOG_INFO, "Request token received: " + 
requestToken + ", token secret="
+            + tokenSecret);
+        return accessor;
+    }
+
+    private String tweetMessage(OAuthAccessor accessor) throws Exception {
+        String url = "https://api.twitter.com/1/statuses/update.json";;
+        url += "?status=" + URLEncoder.encode(TWEET_MSG, "UTF-8");
+        OAuthMessage message = m_oauthClient.accessResource(accessor, url, 
"POST");
+        return convertStreamToString(message.getBodyAsStream());
+    }
+
+    private String getAccountTotals(OAuthAccessor accessor) throws 
IOException, URISyntaxException, OAuthException {
+        String url = "http://api.twitter.com/1/account/totals.json";;
+        OAuthMessage message = m_oauthClient.accessResource(accessor, url, 
"GET");
+        return convertStreamToString(message.getBodyAsStream());
+    }
+
+    private String getAccountSettings(OAuthAccessor accessor) throws 
IOException, URISyntaxException, OAuthException {
+        String url = "http://api.twitter.com/1/account/settings.json";;
+        OAuthMessage message = m_oauthClient.accessResource(accessor, url, 
"GET");
+        return convertStreamToString(message.getBodyAsStream());
+    }
+
+    private String getAccountVerifyCredentials(OAuthAccessor accessor) throws 
IOException, URISyntaxException,
+        OAuthException {
+        String url = 
"http://api.twitter.com/1/account/verify_credentials.json";;
+        OAuthMessage message = m_oauthClient.accessResource(accessor, url, 
"GET");
+        return convertStreamToString(message.getBodyAsStream());
+    }
+
+    private String updateProfile(OAuthAccessor accessor) throws IOException, 
URISyntaxException, OAuthException,
+        JSONException {
+        String url = "http://api.twitter.com/1/account/update_profile.json";;
+        url += "?location=Nijmegen";
+        OAuthMessage message = m_oauthClient.accessResource(accessor, url, 
"POST");
+        return convertStreamToString(message.getBodyAsStream());
+    }
+
+    public String convertStreamToString(InputStream is) throws IOException {
+        /*
+         * To convert the InputStream to String we use the
+         * Reader.read(char[] buffer) method. We iterate until the
+         * Reader return -1 which means there's no more data to
+         * read. We use the StringWriter class to produce the string.
+         */
+        if (is != null) {
+            Writer writer = new StringWriter();
+
+            char[] buffer = new char[1024];
+            try {
+                Reader reader = new BufferedReader(
+                    new InputStreamReader(is, "UTF-8"));
+                int n;
+                while ((n = reader.read(buffer)) != -1) {
+                    writer.write(buffer, 0, n);
+                }
+            }
+            finally {
+                is.close();
+            }
+            return writer.toString();
+        }
+        else {
+            return "";
+        }
+    }
+}
\ No newline at end of file

Added: 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/TwitterServiceProviderImpl.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/twitter-example/src/main/java/org/amdatu/auth/example/oauth/twitter/service/TwitterServiceProviderImpl.java
    Fri Jun 24 10:29:10 2011
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2010, 2011 The Amdatu Foundation
+ *
+ * Licensed 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.amdatu.auth.example.oauth.twitter.service;
+
+import net.oauth.OAuthServiceProvider;
+
+import org.amdatu.auth.example.oauth.twitter.TwitterServiceProvider;
+import org.osgi.service.log.LogService;
+
+public class TwitterServiceProviderImpl implements TwitterServiceProvider {
+    private volatile LogService m_logService;
+    
+    public void start() {   
+        m_logService.log(LogService.LOG_INFO, "Twitter Service Provider 
started");
+    }
+    
+    public String getRequestTokenURL() {
+        return "https://api.twitter.com/oauth/request_token";;
+    }
+
+    public String getAuthorizeTokenURL() {
+        return "https://api.twitter.com/oauth/authorize";;
+    }
+
+    public String getAccessTokenURL() {
+        return "https://api.twitter.com/oauth/access_token";;
+    }
+
+    public String getAuthorizeURL() {
+        return "https://api.twitter.com/oauth/authorize";;
+    }
+    
+    public OAuthServiceProvider toOAuthProvider() {
+        return new OAuthServiceProvider(getRequestTokenURL(), 
getAuthorizeTokenURL(), getAccessTokenURL());
+    }
+}

Added: sandbox/ivol/twitter-example/src/main/resources/jsp/TweetGadget.jsp
==============================================================================
--- (empty file)
+++ sandbox/ivol/twitter-example/src/main/resources/jsp/TweetGadget.jsp Fri Jun 
24 10:29:10 2011
@@ -0,0 +1,104 @@
+<%--
+  Copyright (c) 2010, 2011 The Amdatu Foundation
+
+  Licensed 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.verning permissions and limitations
+  under the License.
+--%>
+
+<%@ page language="java" session="false" buffer="none" %>
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"; %>
+
+<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
+<c:set var="tweetRestUrl" value="${contextPath}/rest/example/twitter/tweet"/>
+<c:set var="gadgetBaseUrl" value="${contextPath}/example/gadget/tweet"/>
+
+<?xml version="1.0" encoding="UTF-8" ?>
+<Module>
+  <ModulePrefs
+    title="Amdatu Tweet Gadget"
+    description="Provides an example Twitter client"
+    author="Ivo Ladage-van Doorn"
+    screenshot="${gadgetBaseUrl}/static/images/twitter.png"
+    icon="${gadgetBaseUrl}/static/images/twitter.png"
+    height="300">
+    <Require feature="osapi"/>
+    <Require feature="dynamic-height"/>
+    <OAuth>
+      <Service name="oauth-example">
+        <Request url="${contextPath}/oauth-server/requesttoken" />
+        <Access url="${contextPath}/oauth-server/accesstoken" />
+        <Authorization url="${contextPath}/oauth-server/authorizetoken" />
+      </Service>
+    </OAuth>
+  </ModulePrefs>
+  <Content type="html">
+    <![CDATA[
+    <link rel="stylesheet" 
href="${contextPath}/dashboard/static/css/dashboard.css">
+
+    <script type="text/javascript" 
src="${contextPath}/dashboard/static/js/lib/jquery-1.4.2.min.js"></script>
+    <script type="text/javascript" 
src="${contextPath}/dashboard/static/js/lib/jquery-ui-1.8.2.custom.min.js"></script>
+
+    <div align="right">
+      <p><img src="${gadgetBaseUrl}/static/images/twitter_small.png"/></p>
+    </div>
+    <div align="left">
+      <p><i>"Check out this new cool open source cloud platform named #Amdatu 
on http://amdatu.org";</i></p>
+    </div>
+    <div align="right">
+      <p>
+      <!--
+        <form action="${tweetRestUrl}" method="POST">
+          <input type="submit" value="Tweet (form) !"/>
+        </form>
+      -->
+      <a href="${tweetRestUrl}">Tweet!</a>
+        <input type="button" value="Tweet!" 
onClick="javascript:gadgetTweet();"/>
+      </p>
+    </div>
+
+    <script language="javascript">
+      function tweet() {
+        var url = "${tweetRestUrl}";
+        jQuery.ajax({
+          url: url,
+          type: "POST",
+          async:true,
+          complete: function (XMLHttpRequest, textStatus) {
+            alert(XMLHttpRequest);
+            alert(XMLHttpRequest.readyState);
+            alert(textStatus);
+          }
+        });
+      }
+
+
+
+
+      function gadgetTweet() {
+        var url = "${tweetRestUrl}";
+        var params = {};
+        params[gadgets.io.RequestParameters.CONTENT_TYPE] = 
gadgets.io.ContentType.TEXT;
+        params[gadgets.io.RequestParameters.METHOD] = 
gadgets.io.MethodType.POST;
+
+        gadgets.io.makeRequest(url, function (response) {
+          if (response.data) {
+            alert("data="+response.data);
+          } else {
+            alert(response);
+          }
+        }, params);
+      }
+    </script>
+    ]]>
+  </Content>
+</Module>

Added: sandbox/ivol/twitter-example/src/main/resources/jsp/TweetPage.jsp
==============================================================================
--- (empty file)
+++ sandbox/ivol/twitter-example/src/main/resources/jsp/TweetPage.jsp   Fri Jun 
24 10:29:10 2011
@@ -0,0 +1,43 @@
+<%--
+  Copyright (c) 2010, 2011 The Amdatu Foundation
+
+  Licensed 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.verning permissions and limitations
+  under the License.
+--%>
+
+<%@ page language="java" session="false" buffer="none" %>
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"; %>
+
+<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
+<c:set var="resourceBaseUrl" value="${contextPath}/example/twitter"/>
+<c:set var="restBaseUrl" value="${contextPath}/rest/example/twitter"/>
+
+<table width="50%">
+  <tr><td>
+    <div align="right">
+      <p><img src="${resourceBaseUrl}/static/images/twitter_small.png"/></p>
+    </div>
+    <div align="left">
+      <p><i>"Check out this new cool open source cloud platform named #Amdatu 
on http://amdatu.org";</i></p>
+      <hr/>
+
+    </div>
+    <div align="right">
+      <p>
+      <form action="${restBaseUrl}/tweet" method="POST">
+        <input type="submit" value="Tweet!"/>
+      </form>
+      </p>
+    </div>
+  </td></tr>
+</table>

Added: sandbox/ivol/twitter-example/src/main/resources/static/images/twitter.png
==============================================================================
Binary file. No diff available.

Added: 
sandbox/ivol/twitter-example/src/main/resources/static/images/twitter_small.png
==============================================================================
Binary file. No diff available.
_______________________________________________
Amdatu-commits mailing list
[email protected]
http://lists.amdatu.org/mailman/listinfo/amdatu-commits

Reply via email to