PageRenderTime 2ms CodeModel.GetById 9ms app.highlight 7ms RepoModel.GetById 0ms app.codeStats 0ms

/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java

https://github.com/ddurnev/jclouds
Java | 169 lines | 121 code | 19 blank | 29 comment | 5 complexity | d47b8cd03cd0e136473a81ffc5dcdcde MD5 | raw file
  1/**
  2 * Licensed to jclouds, Inc. (jclouds) under one or more
  3 * contributor license agreements.  See the NOTICE file
  4 * distributed with this work for additional information
  5 * regarding copyright ownership.  jclouds licenses this file
  6 * to you under the Apache License, Version 2.0 (the
  7 * "License"); you may not use this file except in compliance
  8 * with the License.  You may obtain a copy of the License at
  9 *
 10 *   http://www.apache.org/licenses/LICENSE-2.0
 11 *
 12 * Unless required by applicable law or agreed to in writing,
 13 * software distributed under the License is distributed on an
 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 15 * KIND, either express or implied.  See the License for the
 16 * specific language governing permissions and limitations
 17 * under the License.
 18 */
 19package org.jclouds.demo.tweetstore.config;
 20
 21import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
 22import static com.google.common.base.Preconditions.checkNotNull;
 23import static com.google.common.base.Preconditions.checkState;
 24import static com.google.common.base.Predicates.in;
 25import static com.google.common.collect.ImmutableSet.copyOf;
 26import static com.google.common.collect.Sets.filter;
 27import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES;
 28import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER;
 29import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN;
 30import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET;
 31import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY;
 32import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET;
 33
 34import java.io.IOException;
 35import java.io.InputStream;
 36import java.util.Map;
 37import java.util.Properties;
 38import java.util.Set;
 39
 40import javax.servlet.ServletContextEvent;
 41
 42import org.jclouds.blobstore.BlobStoreContext;
 43import org.jclouds.blobstore.BlobStoreContextFactory;
 44import org.jclouds.demo.tweetstore.config.util.CredentialsCollector;
 45import org.jclouds.demo.tweetstore.controller.AddTweetsController;
 46import org.jclouds.demo.tweetstore.controller.StoreTweetsController;
 47import org.jclouds.gae.config.GoogleAppEngineConfigurationModule;
 48
 49import twitter4j.Twitter;
 50import twitter4j.TwitterFactory;
 51import twitter4j.conf.Configuration;
 52import twitter4j.conf.ConfigurationBuilder;
 53
 54import com.google.appengine.api.taskqueue.Queue;
 55import com.google.appengine.api.taskqueue.QueueFactory;
 56import com.google.appengine.api.taskqueue.TaskOptions.Method;
 57import com.google.appengine.repackaged.com.google.common.base.Splitter;
 58import com.google.common.collect.ImmutableSet;
 59import com.google.common.collect.Maps;
 60import com.google.common.io.Closeables;
 61import com.google.inject.Guice;
 62import com.google.inject.Injector;
 63import com.google.inject.Module;
 64import com.google.inject.TypeLiteral;
 65import com.google.inject.name.Names;
 66import com.google.inject.servlet.GuiceServletContextListener;
 67import com.google.inject.servlet.ServletModule;
 68
 69/**
 70 * Setup Logging and create Injector for use in testing S3.
 71 * 
 72 * @author Adrian Cole
 73 */
 74public class GuiceServletConfig extends GuiceServletContextListener {
 75   public static final String PROPERTY_BLOBSTORE_CONTEXTS = "blobstore.contexts";
 76
 77   private Map<String, BlobStoreContext> providerTypeToBlobStoreMap;
 78   private Twitter twitterClient;
 79   private String container;
 80   private Queue queue;
 81
 82   @Override
 83   public void contextInitialized(ServletContextEvent servletContextEvent) {
 84
 85      BlobStoreContextFactory blobStoreContextFactory = new BlobStoreContextFactory();
 86
 87      Properties props = loadJCloudsProperties(servletContextEvent);
 88
 89      Module googleModule = new GoogleAppEngineConfigurationModule();
 90      Set<Module> modules = ImmutableSet.<Module> of(googleModule);
 91      // shared across all blobstores and used to retrieve tweets
 92      try {
 93          Configuration twitterConf = new ConfigurationBuilder()
 94              .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY))
 95              .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET))
 96              .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN))
 97              .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET))
 98              .build();
 99          twitterClient = new TwitterFactory(twitterConf).getInstance();
100      } catch (IllegalArgumentException e) {
101          throw new IllegalArgumentException("properties for twitter not configured properly in " + props.toString(), e);
102      }
103      // common namespace for storing tweets
104      container = checkNotNull(props.getProperty(PROPERTY_TWEETSTORE_CONTAINER), PROPERTY_TWEETSTORE_CONTAINER);
105
106      // instantiate and store references to all blobstores by provider name
107      // instantiate and store references to all blobstores by provider name
108      providerTypeToBlobStoreMap = Maps.newHashMap();
109      for (String hint : getBlobstoreContexts(props)) {
110          providerTypeToBlobStoreMap.put(hint, blobStoreContextFactory.createContext(hint, modules, props));
111      }
112
113      // get a queue for submitting store tweet requests
114      queue = QueueFactory.getQueue("twitter");
115      // submit a job to store tweets for each configured blobstore
116      for (String name : providerTypeToBlobStoreMap.keySet()) {
117          queue.add(withUrl("/store/do").header("context", name).method(Method.GET));
118      }
119
120      super.contextInitialized(servletContextEvent);
121   }
122   
123   private static Iterable<String> getBlobstoreContexts(Properties props) {
124       Set<String> contexts = new CredentialsCollector().apply(props).keySet();
125       String explicitContexts = props.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES);
126       if (explicitContexts != null) {
127           contexts = filter(contexts, in(copyOf(Splitter.on(',').split(explicitContexts))));
128       }
129       checkState(!contexts.isEmpty(), "no credentials available for any requested  context");
130       return contexts;
131   }
132
133   private Properties loadJCloudsProperties(ServletContextEvent servletContextEvent) {
134      InputStream input = servletContextEvent.getServletContext().getResourceAsStream("/WEB-INF/jclouds.properties");
135      Properties props = new Properties();
136      try {
137         props.load(input);
138      } catch (IOException e) {
139         throw new RuntimeException(e);
140      } finally {
141         Closeables.closeQuietly(input);
142      }
143      return props;
144   }
145
146   @Override
147   protected Injector getInjector() {
148      return Guice.createInjector(new ServletModule() {
149         @Override
150         protected void configureServlets() {
151            bind(new TypeLiteral<Map<String, BlobStoreContext>>() {
152            }).toInstance(providerTypeToBlobStoreMap);
153            bind(Twitter.class).toInstance(twitterClient);
154            bindConstant().annotatedWith(Names.named(PROPERTY_TWEETSTORE_CONTAINER)).to(container);
155            serve("/store/*").with(StoreTweetsController.class);
156            serve("/tweets/*").with(AddTweetsController.class);
157         }
158      });
159   }
160
161   @Override
162   public void contextDestroyed(ServletContextEvent servletContextEvent) {
163      for (BlobStoreContext context : providerTypeToBlobStoreMap.values()) {
164         context.close();
165      }
166      queue.purge();
167      super.contextDestroyed(servletContextEvent);
168   }
169}