org.insomne.blackbush.ConnectServlet.java Source code

Java tutorial

Introduction

Here is the source code for org.insomne.blackbush.ConnectServlet.java

Source

/*
 *
 * Copyright 2014 Google Inc.
 *
 * 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.insomne.blackbush;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import com.google.api.client.auth.oauth2.TokenResponseException;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author Andres Leonardo Martinez Ortiz a.k.a almo
 *
 */
@SuppressWarnings("serial")
public class ConnectServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        GoogleClientSecrets clientSecrets = (GoogleClientSecrets) getServletContext().getAttribute("clientSecrets");
        String CLIENT_ID = clientSecrets.getWeb().getClientId();
        String CLIENT_SECRET = clientSecrets.getWeb().getClientSecret();

        HttpTransport TRANSPORT = (HttpTransport) getServletContext().getAttribute("TRANSPORT");
        JacksonFactory JSON_FACTORY = (JacksonFactory) getServletContext().getAttribute("JSON_FACTORY");

        // Only connect a user that is not already connected
        String tokenData = (String) req.getSession().getAttribute("token");
        if (tokenData != null) {
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().print("Current user is already connected.");
            return;
        }

        ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
        getContent(req.getInputStream(), resultStream);

        String code = new String(resultStream.toByteArray(), "UTF-8");
        try {
            // Upgrade the authorization code into an access and refresh token.
            GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY,
                    CLIENT_ID, CLIENT_SECRET, code, "postmessage").execute();

            // Store the token in the session for later use.
            req.getSession().setAttribute("token", tokenResponse.toString());
            resp.setStatus(HttpServletResponse.SC_OK);

        } catch (TokenResponseException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    static void getContent(InputStream inputStream, ByteArrayOutputStream outputStream) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        int readChar;
        while ((readChar = reader.read()) != -1) {
            outputStream.write(readChar);
        }
        reader.close();
    }
}