Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleCredential GoogleCredential

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential GoogleCredential

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.auth.oauth2 GoogleCredential GoogleCredential.

Prototype

public GoogleCredential() 

Source Link

Document

Constructor with the ability to access protected resources, but not refresh tokens.

Usage

From source file:edu.umich.its.lti.google.GoogleLtiServlet.java

License:Educational Community License

private GoogleCredential getGoogleCredential(HttpServletRequest request) {
    GoogleCredential result = null;/*from   w  w w  .  j av  a2  s  . c  o m*/
    String accessToken = request.getParameter(PARAM_ACCESS_TOKEN);
    if (!getIsEmpty(accessToken)) {
        result = new GoogleCredential().setAccessToken(accessToken);
    }
    return result;
}

From source file:fi.viljami.confluence.gdoc.GdocGoogleOauth2.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    String[] error = req.getParameterValues(ERROR_URL_PARAM_NAME);
    if (error != null && error.length > 0) {
        res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: " + error[0]);
        return;/*w w w  .  ja v a 2  s .co m*/
    }

    String[] code = req.getParameterValues(CODE_URL_PARAM_NAME);
    if (code == null || code.length == 0) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "The code URL parameter is missing");
        return;
    }

    // Authentication OK.
    GoogleCredential googleCredential = null;
    try {
        GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(httpTransport, jsonFactory,
                OauthProperties.getClientId(), OauthProperties.getClientSecret(), code[0],
                OauthProperties.getRedirectUri()).execute();
        googleCredential = new GoogleCredential().setFromTokenResponse(response);
    } catch (IOException e) {
        new RuntimeException("An unknown problem occured while retrieving token");
    }

    Drive drive = new Drive.Builder(httpTransport, jsonFactory, googleCredential).build();
    List<File> files = retrieveAllFiles(drive);
    List<String> titles = getFileTitles(files);

    System.out.println(drive);
    System.out.println(files);
    System.out.println(titles);

    HttpSession session = req.getSession();
    session.setAttribute("files", titles);

    res.sendRedirect("/confluence");
}

From source file:gnomezgrave.gsyncj.auth.Authorization.java

public static synchronized Drive getDrive(String key) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE)).setAccessType("online")
                    .setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
    System.out.println(url);/*from  w  w w  .j  a  v  a 2 s .  c o  m*/

    GoogleTokenResponse response = flow.newTokenRequest(key).setRedirectUri(REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

    //Create a new authorized API client
    return new Drive.Builder(httpTransport, jsonFactory, credential).build();
}

From source file:GoogleDrive.GoogleDrive.java

private void buildService(String codeValidation) {
    try {/*  w  w  w.ja  v a  2s  . c om*/
        GoogleTokenResponse response = this.flow.newTokenRequest(codeValidation).setRedirectUri(REDIRECT_URI)
                .execute();
        GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
        this.service = new Drive.Builder(this.httpTransport, this.jsonFactory, credential).build();
        //return service;
    } catch (IOException ex) {
        ex.printStackTrace();
        //return null;
    }
}

From source file:javamailclient.GmailAPI.java

public static void initialize(String code) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));

    // Allow user to authorize via url.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            clientSecrets, Arrays.asList(SCOPE)).setAccessType("online").setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build();
    //System.out.println("Please open the following URL in your browser then type"+" the authorization code:\n" + url);

    // Read code entered by user.
    //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    //String code = br.readLine();

    // Generate Credential using retrieved code.
    GoogleTokenResponse response = flow.newTokenRequest(code)
            .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

    // Create a new authorized Gmail API client
    service = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName(APP_NAME).build();

    Profile profile = service.users().getProfile(USER).execute();
    USER_EMAIL = profile.getEmailAddress();
    System.out.println(USER_EMAIL);
    /*ListThreadsResponse threadsResponse = service.users().threads().list(USER).execute();
    List<Thread> threads = threadsResponse.getThreads();
            /*from  w  w w.j a v a  2 s .c  om*/
    // Print ID of each Thread.
    for (Thread thread : threads) {
      System.out.println("Thread ID: " + thread.getId());
    }*/
}

From source file:net.grappendorf.doitlater.TaskManagerImpl.java

License:Apache License

public TaskManagerImpl(Context context) {
    SharedPreferences globalPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    String apiKey = globalPrefs.getString("api_key", "");
    this.credential = new GoogleCredential();
    this.accountManager = new GoogleAccountManager(context);
    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = new GsonFactory();
    this.tasksService = new Tasks.Builder(transport, jsonFactory, credential)
            .setApplicationName(DoItLaterApplication.NAME)
            .setJsonHttpRequestInitializer(new GoogleKeyInitializer(apiKey)).build();
    asyncTaskByActivity = new HashMap<Activity, AsyncTask<Void, Void, ?>>();
    preferences = context.getSharedPreferences(PREF_NAME, Activity.MODE_PRIVATE);
    credential.setAccessToken(preferences.getString(PREF_AUTH_TOKEN, null));
    accountName = preferences.getString(PREF_ACCOUNT_NAME, null);
    received401 = false;/* w w w  .  j  a  va 2  s .  c om*/
}

From source file:net.xisberto.phonetodesktop.GoogleTasksActivity.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Configure a background thread
    HandlerThread thread = new HandlerThread("PhoneToDesktopThread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();//from  w w  w. j ava  2 s. c o  m
    looper = thread.getLooper();
    handler = new Handler(looper);

    // Configure app's preferences
    settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    accountManager = new GoogleAccountManager(getApplicationContext());

    // Configure GoogleCredential. loadAuthToken can return null
    credential = new GoogleCredential();
    log("Current saved token: " + loadAuthToken());

    // Configure and build the Tasks object
    tasksService = new Tasks.Builder(transport, jsonFactory, credential).setApplicationName("PhoneToDesktop")
            .setJsonHttpRequestInitializer(new GoogleKeyInitializer(my_credentials.getAPIKey())).build();

    if (getIntent().getAction().equals(ACTION_AUTHENTICATE)) {
        broadcastUpdatingStatus(ACTION_AUTHENTICATE, true);
        authorize();
    } else if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
        addTask(loadWhatToSend(), getIntent().getStringExtra(Intent.EXTRA_TEXT));
    } else if (getIntent().getAction().equals(ACTION_LIST_TASKS)) {
        broadcastUpdatingStatus(ACTION_LIST_TASKS, true);
        getTaskList();
    } else if (getIntent().getAction().equals(ACTION_REMOVE_TASKS)) {
        removeTask(getIntent().getStringExtra("task_id"));
    }

}

From source file:nl.welteninstituut.tel.la.bigquery.Common.java

License:Open Source License

private static HttpRequestInitializer getRequestInitializer() {
    if (System.getProperty("OAUTH_ACCESS_TOKEN") != null) {
        return new GoogleCredential().setAccessToken(System.getProperty("OAUTH_ACCESS_TOKEN"));
    }//from w  w w. j a  v  a2  s . c  o m
    return new AppIdentityCredential(Arrays.asList(new String[] { SCOPE }));
}

From source file:org.caboclo.clients.GoogleDriveClient.java

License:Open Source License

public GoogleDriveClient(String bearerToken) {
    this();//  www.j  av a 2  s .c  o  m

    GoogleCredential credential = new GoogleCredential().setAccessToken(bearerToken);
    // Create a new authorized API client
    service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
    files = service.files();

    this.token = bearerToken;

    authenticated = true;
}

From source file:org.caboclo.clients.GoogleDriveClient.java

License:Open Source License

@Override
public boolean authenticate(String token) {
    try {/*from w  w w.  ja v a 2 s.c o m*/

        GoogleTokenResponse response = flow.newTokenRequest(token).setRedirectUri(REDIRECT_URI).execute();

        GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

        // Create a new authorized API client
        service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
        files = service.files();

        Credentials cred = new Credentials();

        //Remove old credentials, if they exist
        cred.removeCredentials(Credentials.GOOGLE);

        //Save new credentials
        cred.saveCredentials(Credentials.GOOGLE, credential.getAccessToken());

        this.token = credential.getAccessToken();

        authenticated = true;

        return true;

    } catch (Exception ex) {
        Logger.getLogger(GoogleDriveClient.class.getName()).log(Level.SEVERE, null, ex);
    }

    return false;

}