Home | History | Annotate | Download | only in hello-java
      1 /*
      2  * Copyright (c) 2012 The Chromium Authors. All rights reserved.
      3  * Use of this source code is governed by a BSD-style license that can be
      4  * found in the LICENSE file.
      5  *
      6  * The "Hello world!" of the Chrome Web Store Licensing API, in Java. This
      7  * program logs the user in with OpenID, fetches their license state with OAuth,
      8  * and prints one of these greetings as appropriate:
      9  *
     10  *   1. Hello *no* license!
     11  *   2. Hello *free trial* license!
     12  *   3. Hello *full* license!
     13  *
     14  * Brian Kennish <bkennish (at) chromium.org>
     15  */
     16 package com.example;
     17 
     18 import java.io.*;
     19 import java.net.*;
     20 import java.util.HashSet;
     21 import javax.servlet.http.*;
     22 import com.google.appengine.api.users.*;
     23 import com.google.appengine.repackaged.org.json.JSONObject;
     24 import oauth.signpost.OAuthConsumer;
     25 import oauth.signpost.basic.DefaultOAuthConsumer;
     26 
     27 /* A Google App Engine servlet. */
     28 @SuppressWarnings("serial")
     29 public class HelloLicenseServlet extends HttpServlet {
     30   /* TODO: The app ID from the Chrome Developer Dashboard. */
     31   public static final String APP_ID = "[INSERT APP ID HERE]";
     32 
     33   /* TODO: The token from the Chrome Developer Dashboard. */
     34   private static final String TOKEN = "[INSERT TOKEN HERE]";
     35 
     36   /* TODO: The token secret from the Chrome Developer Dashboard. */
     37   private static final String TOKEN_SECRET = "[INSERT TOKEN SECRET HERE]";
     38 
     39   /*
     40    * The license server URL, where %s are placeholders for app and
     41    * user IDs
     42    */
     43   public static final String SERVER_URL =
     44       "https://www.googleapis.com/chromewebstore/v1/licenses/%s/%s";
     45 
     46   /* The consumer key. */
     47   public static final String CONSUMER_KEY = "anonymous";
     48 
     49   /* The consumer secret. */
     50   public static final String CONSUMER_SECRET = CONSUMER_KEY;
     51 
     52   /* Handles "GET" requests. */
     53   public void doGet(HttpServletRequest request, HttpServletResponse response)
     54       throws IOException {
     55     response.setContentType("text/html; charset=UTF-8");
     56     UserService userService = UserServiceFactory.getUserService();
     57     PrintWriter output = response.getWriter();
     58     String url = request.getRequestURI();
     59 
     60     if (userService.isUserLoggedIn()) {
     61       // Provide a logout path.
     62       User user = userService.getCurrentUser();
     63       output.printf(
     64         "<strong>%s</strong> | <a href=\"%s\">Sign out</a><br><br>",
     65         user.getEmail(),
     66         userService.createLogoutURL(url)
     67       );
     68 
     69       try {
     70         // Send a signed request for the user's license state.
     71         OAuthConsumer oauth =
     72             new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
     73         oauth.setTokenWithSecret(TOKEN, TOKEN_SECRET);
     74         URLConnection http =
     75             new URL(
     76               String.format(
     77                 SERVER_URL,
     78                 APP_ID,
     79                 URLEncoder.encode(user.getFederatedIdentity(), "UTF-8")
     80               )
     81             ).openConnection();
     82         oauth.sign(http);
     83         http.connect();
     84 
     85         // Convert the response from the license server to a string.
     86         BufferedReader input =
     87             new BufferedReader(new InputStreamReader(http.getInputStream()));
     88         String file = "";
     89         for (String line; (line = input.readLine()) != null; file += line);
     90         input.close();
     91 
     92         // Parse the string as JSON and display the license state.
     93         JSONObject json = new JSONObject(file);
     94         output.printf(
     95           "Hello <strong>%s</strong> license!",
     96           "YES".equals(json.get("result")) ?
     97               "FULL".equals(json.get("accessLevel")) ? "full" : "free trial" :
     98               "no"
     99         );
    100       } catch (Exception exception) {
    101         // Dump any error.
    102         output.printf("Oops! <strong>%s</strong>", exception.getMessage());
    103       }
    104     } else { // The user isn't logged in.
    105       // Prompt for login.
    106       output.printf(
    107         "<a href=\"%s\">Sign in</a>",
    108         userService.createLoginURL(
    109           url,
    110           null,
    111           "https://www.google.com/accounts/o8/id",
    112           new HashSet<String>()
    113         )
    114       );
    115     }
    116   }
    117 }
    118