com.aalmeida.lightning.external.auth.GoogleAuthorizationImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.aalmeida.lightning.external.auth.GoogleAuthorizationImpl.java

Source

/*
 * Copyright (c) 2015 Alexandre Almeida.
 *
 * 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 com.aalmeida.lightning.external.auth;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.aalmeida.lightning.external.AbstractComponent;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.calendar.Calendar;

public class GoogleAuthorizationImpl extends AbstractComponent implements Authorization {
    //private static final String AUTH_PATH = ".store/BillsManagement";
    private static String appName;
    private static boolean isAuthorized;
    private static FileDataStoreFactory dataStoreFactory;
    private static JsonFactory jsonFactory;
    private static HttpTransport httpTransport;
    private static Credential credential;

    /**
     * Instantiates a new google authorization impl.
     *
     * @param pUrl
     *            the url
     * @param pAppName
     *            the app name
     * @param pLog
     *            the log
     */
    public GoogleAuthorizationImpl(String pUrl, String pAppName, Logger pLog) {
        super(null, pLog);
        appName = pAppName;
        try {
            jsonFactory = JacksonFactory.getDefaultInstance();

            httpTransport = GoogleNetHttpTransport.newTrustedTransport();

            dataStoreFactory = new FileDataStoreFactory(new File(".store/BillsManagement"));
            if (credential == null) {
                credential = authorize(pUrl);
            }
            isAuthorized = true;
        } catch (Exception e) {
            isAuthorized = false;
            this.log.error(e);
        }
    }

    /**
     * Authorize.
     *
     * @param pUrl
     *            the url
     * @return the credential
     * @throws Exception
     *             the exception
     */
    private static Credential authorize(String pUrl) throws Exception {
        URL url = new URL(pUrl);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, in);
        String clientId = clientSecrets.getDetails().getClientId();
        String clientSecret = clientSecrets.getDetails().getClientSecret();
        if ((clientId == null) || (clientId.isEmpty()) || (clientSecret == null) || (clientSecret.isEmpty())) {
            throw new Exception("Empty Google credencials");
        }
        GoogleClientSecrets.Details details = new GoogleClientSecrets.Details();
        details.setClientId(clientId);
        details.setClientSecret(clientSecret);
        clientSecrets.setInstalled(details);

        List<String> permissions = new ArrayList<String>();
        permissions.add("https://www.googleapis.com/auth/calendar");
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
                clientSecrets, permissions).setAccessType("offline").setApprovalPrompt("force")
                        .setDataStoreFactory(dataStoreFactory).build();

        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

    /* (non-Javadoc)
     * @see com.aalmeida.lightning.external.auth.Authorization#check()
     */
    public boolean check() {
        return isAuthorized;
    }

    /* (non-Javadoc)
     * @see com.aalmeida.lightning.external.auth.Authorization#getCalendarClientAuthorization()
     */
    public Object getCalendarClientAuthorization() {
        Calendar client = new Calendar.Builder(httpTransport, jsonFactory, credential).setApplicationName(appName)
                .build();

        return client;
    }
}