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:calendarevent.CalendarEvent.java

/**
 * @param args the command line arguments
 *///  w ww  . j a va2  s . co  m
public static void main(String[] args) {
    // TODO code application logic here

    /*       
                
        This has to be replaced with the json data coming from the getJsonData() method
        Expecting the Json will be in the format from the above methid.
                
    */
    String jsonString = "{\n" + " \"kind\": \"calendar#events\",\n"
            + " \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/QElT1PHkP9d3G5VSndpdEMlSzKE\\\"\",\n"
            + " \"summary\": \"PushEvents\",\n" + " \"description\": \"Hackathon\",\n"
            + " \"updated\": \"2014-03-29T22:35:18.495Z\",\n" + " \"timeZone\": \"Asia/Calcutta\",\n"
            + " \"accessRole\": \"reader\",\n" + " \"items\": [\n" + "  {\n"
            + "   \"kind\": \"calendar#event\",\n"
            + "   \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/MTM5NjEyNTQwNzcxMTAwMA\\\"\",\n"
            + "   \"id\": \"q28lprjb8ad3m17955lf1p9d48\",\n" + "   \"status\": \"confirmed\",\n"
            + "   \"htmlLink\": \"https://www.google.com/calendar/event?eid=cTI4bHByamI4YWQzbTE3OTU1bGYxcDlkNDggM3RvcjdvamZxaWhlamNqNjduOWw0dDhnMmNAZw\",\n"
            + "   \"created\": \"2014-03-29T20:36:47.000Z\",\n"
            + "   \"updated\": \"2014-03-29T20:36:47.711Z\",\n" + "   \"summary\": \"Test API\",\n"
            + "   \"creator\": {\n" + "    \"email\": \"vrohitrao@gmail.com\",\n"
            + "    \"displayName\": \"Rohith Vallu\"\n" + "   },\n" + "   \"organizer\": {\n"
            + "    \"email\": \"3tor7ojfqihejcj67n9l4t8g2c@group.calendar.google.com\",\n"
            + "    \"displayName\": \"PushEvents\",\n" + "    \"self\": true\n" + "   },\n"
            + "   \"start\": {\n" + "    \"dateTime\": \"2014-03-30T02:30:00+05:30\"\n" + "   },\n"
            + "   \"end\": {\n" + "    \"dateTime\": \"2014-03-30T03:30:00+05:30\"\n" + "   },\n"
            + "   \"iCalUID\": \"q28lprjb8ad3m17955lf1p9d48@google.com\",\n" + "   \"sequence\": 0\n" + "  },\n"
            + "  {\n" + "   \"kind\": \"calendar#event\",\n"
            + "   \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/MTM5NjEzMjUzMjQxNzAwMA\\\"\",\n"
            + "   \"id\": \"jgpue3stuo3js5qlsodob84voo\",\n" + "   \"status\": \"confirmed\",\n"
            + "   \"htmlLink\": \"https://www.google.com/calendar/event?eid=amdwdWUzc3R1bzNqczVxbHNvZG9iODR2b28gM3RvcjdvamZxaWhlamNqNjduOWw0dDhnMmNAZw\",\n"
            + "   \"created\": \"2014-03-29T22:35:32.000Z\",\n"
            + "   \"updated\": \"2014-03-29T22:35:32.417Z\",\n" + "   \"summary\": \"Test Events\",\n"
            + "   \"description\": \"Hack!!\",\n"
            + "   \"location\": \"Northeastern University, Huntington Avenue, Boston, MA, United States\",\n"
            + "   \"creator\": {\n" + "    \"email\": \"vrohitrao@gmail.com\",\n"
            + "    \"displayName\": \"Rohith Vallu\"\n" + "   },\n" + "   \"organizer\": {\n"
            + "    \"email\": \"3tor7ojfqihejcj67n9l4t8g2c@group.calendar.google.com\",\n"
            + "    \"displayName\": \"PushEvents\",\n" + "    \"self\": true\n" + "   },\n"
            + "   \"start\": {\n" + "    \"dateTime\": \"2014-03-30T04:30:00+05:30\"\n" + "   },\n"
            + "   \"end\": {\n" + "    \"dateTime\": \"2014-03-30T19:30:00+05:30\"\n" + "   },\n"
            + "   \"visibility\": \"public\",\n"
            + "   \"iCalUID\": \"jgpue3stuo3js5qlsodob84voo@google.com\",\n" + "   \"sequence\": 0\n" + "  }\n"
            + " ]\n" + "}";

    Gson gson = new Gson();
    try {
        JSONObject jsonData = new JSONObject(jsonString);
        JSONArray jsonArray = jsonData.getJSONArray("items");
        JSONObject eventData;
        Event event = new Event();
        for (int i = 0; i < jsonArray.length(); i++) {

            System.out.println(jsonArray.get(i).toString());
            Items item = gson.fromJson(jsonArray.get(i).toString(), Items.class);

            event.setSummary(item.getSummary());
            event.setLocation(item.getLocation());

            /* Will be adding the attendees here
             ArrayList<EventAttendee> attendees = new ArrayList<EventAttendee>();
             attendees.add(new EventAttendee().setEmail("attendeeEmail"));
             // ...
             event.setAttendees(attendees);
             */
            Date startDate = new Date();
            Date endDate = new Date(startDate.getTime() + 3600000);
            DateTime start = new DateTime(startDate, TimeZone.getDefault().getDefault().getTimeZone("UTC"));
            event.setStart(new EventDateTime().setDateTime(start));
            DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
            event.setEnd(new EventDateTime().setDateTime(end));
            HttpTransport transport = new NetHttpTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            Calendar.Builder builder = new Calendar.Builder(transport, jsonFactory, null);
            String clientID = "937140966210.apps.googleusercontent.com";
            String redirectURL = "urn:ietf:wg:oauth:2.0:oob";
            String clientSecret = "qMFSb_cadYDG7uh3IDXWiMQY";
            ArrayList<String> scope = new ArrayList<String>();
            scope.add("https://www.googleapis.com/auth/calendar");

            String url = new GoogleAuthorizationCodeRequestUrl(clientID, redirectURL, scope).build();

            System.out.println("Go to the following link in your browser:");
            System.out.println(url);

            // Read the authorization code from the standard input stream.
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("What is the authorization code?");
            String code = in.readLine();

            GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory,
                    clientID, clientSecret, redirectURL, code, redirectURL).execute();

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

            Calendar service = new Calendar.Builder(transport, jsonFactory, credential).build();

            Event createdEvent = service.events().insert(item.getSummary(), event).execute();

            System.out.println(createdEvent.getId());

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cd.education.data.collector.android.tasks.GoogleMapsEngineAbstractUploader.java

License:Apache License

private boolean uploadOneSubmission(String id, String instanceFilePath, String jrFormId, String token,
        HashMap<String, String> gmeFormValues, String md5, String formFilePath) {
    // if the token is null fail immediately
    if (token == null) {
        mResults.put(id, oauth_fail + Collect.getInstance().getString(R.string.invalid_oauth));
        return false;
    }// w  w  w . ja  v  a 2 s.co m

    HashMap<String, String> answersToUpload = new HashMap<String, String>();
    HashMap<String, String> photosToUpload = new HashMap<String, String>();
    HashMap<String, PhotoEntry> uploadedPhotos = new HashMap<String, PhotoEntry>();

    HttpTransport h = AndroidHttp.newCompatibleTransport();
    GoogleCredential gc = new GoogleCredential();
    gc.setAccessToken(token);

    PicasaClient client = new PicasaClient(h.createRequestFactory(gc));
    String gmeTableId = null;

    // get instance file
    File instanceFile = new File(instanceFilePath);

    // parses the instance file and populates the answers and photos
    // hashmaps. Also extracts the projectid and draftaccess list if
    // defined
    try {
        processXMLFile(instanceFile, answersToUpload, photosToUpload, gmeFormValues);
    } catch (XmlPullParserException e) {
        e.printStackTrace();
        mResults.put(id, form_fail + e.getMessage());
        return false;
    } catch (FormException e) {
        mResults.put(id, form_fail + Collect.getInstance().getString(R.string.gme_repeat_error));
        return false;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        mResults.put(id, form_fail + e.getMessage());
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        mResults.put(id, form_fail + e.getMessage());
        return false;
    }

    // at this point, we should have a projectid either from
    // the settings or the form
    // if not, fail
    if (gmeFormValues.get(PROJECT_ID) == null) {
        mResults.put(id, form_fail + Collect.getInstance().getString(R.string.gme_project_id_error));
        return false;
    }

    // check to see if a table already exists in GME that
    // matches the given md5
    try {
        gmeTableId = getGmeTableID(gmeFormValues.get(PROJECT_ID), jrFormId, token, md5);
    } catch (IOException e2) {
        e2.printStackTrace();
        mResults.put(id, form_fail + e2.getMessage());
        return false;
    }

    // GME limit is 1/s, so sleep for 1 second after each GME query
    try {
        Thread.sleep(GME_SLEEP_TIME);
    } catch (InterruptedException e3) {
        e3.printStackTrace();
    }

    // didn't exist, so try to create it
    boolean newTable = false;
    if (gmeTableId == null) {
        try {
            gmeTableId = createTable(jrFormId, gmeFormValues.get(PROJECT_ID), md5, token, formFilePath);
            newTable = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mResults.put(id, form_fail + e.getMessage());
            return false;
        } catch (XmlPullParserException e) {
            e.printStackTrace();
            mResults.put(id, form_fail + e.getMessage());
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            mResults.put(id, form_fail + e.getMessage());
            return false;
        } catch (FormException e) {
            e.printStackTrace();
            mResults.put(id, form_fail + e.getMessage());
            return false;
        }
    }

    // GME has 1q/s limit
    // but needs a few extra seconds after a create table
    try {
        int sleepTime = GME_SLEEP_TIME;
        if (newTable) {
            sleepTime += GME_CREATE_TABLE_DELAY;
        }
        Thread.sleep(sleepTime);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // at this point, we should have a valid gme table id to
    // submit this instance to
    if (gmeTableId == null) {
        mResults.put(id, form_fail + Collect.getInstance().getString(R.string.gme_table_error));
        return false;
    }

    // if we have any photos to upload,
    // get the picasa album or create a new one
    // then upload the photos
    if (photosToUpload.size() > 0) {
        // First set up a picasa album to upload to:
        // maybe we should move this, because if we don't have any
        // photos we don't care...
        AlbumEntry albumToUse = null;
        try {
            albumToUse = getOrCreatePicasaAlbum(client, jrFormId);
        } catch (IOException e) {
            e.printStackTrace();
            GoogleAuthUtil.invalidateToken(Collect.getInstance(), token);
            mResults.put(id, picasa_fail + e.getMessage());
            return false;
        }

        try {
            uploadPhotosToPicasa(photosToUpload, uploadedPhotos, client, albumToUse, instanceFile);
        } catch (IOException e1) {
            e1.printStackTrace();
            mResults.put(id, picasa_fail + e1.getMessage());
            return false;
        }
    }

    // All photos have been sent to picasa (if there were any)
    // now upload data to GME

    String jsonSubmission = null;
    try {
        jsonSubmission = buildJSONSubmission(answersToUpload, uploadedPhotos);
    } catch (GeoPointNotFoundException e2) {
        e2.printStackTrace();
        mResults.put(id, form_fail + e2.getMessage());
        return false;
    }

    URL gmeuri = null;
    try {
        gmeuri = new URL(
                "https://www.googleapis.com/mapsengine/v1/tables/" + gmeTableId + "/features/batchInsert");
    } catch (MalformedURLException e) {
        mResults.put(id, gme_fail + e.getMessage());
        return false;
    }

    // try to upload the submission
    // if not successful, in case of error results will already be
    // populated
    return uploadSubmission(gmeuri, token, jsonSubmission, gmeTableId, id, newTable);
}

From source file:cloudnet.user.UserGoogleDrive.java

public void printFilesInFolder(String userType, String folderId, String token) {
    //        if(!files.isEmpty())
    //            parentFolderId = files.get(0).getParents().get(0).getId();
    GoogleCredential credential;//from   ww w. j  ava  2s.co m
    files.removeAll(files);

    try {
        GoogleTokenResponse response;
        if (userType.equals(CloudNet.NEW_USER)) {
            response = flow.newTokenRequest(token).setRedirectUri(REDIRECT_URI).execute();

            addTokenToDatabase(response.getRefreshToken());
            User.setGoogleToken(String.valueOf(response.getRefreshToken()));

            credential = new GoogleCredential().setAccessToken(response.getAccessToken());
        } else {
            GoogleCredential.Builder b = new GoogleCredential.Builder();
            b.setJsonFactory(jsonFactory);
            b.setTransport(httpTransport);
            b.setClientSecrets(CLIENT_ID, CLIENT_SECRET);
            credential = b.build();
            credential.setRefreshToken(token);
            credential.refreshToken();
            credential.setAccessToken(credential.getAccessToken());
        }

        //Create a new authorized API client
        service = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName("CloudNet")
                .build();
        filesRequest = service.files().list().setQ("trashed = false and '" + folderId + "' in parents");

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    do {
        try {
            FileList filesList = filesRequest.execute();

            for (File file : filesList.getItems()) {
                files.add(file);
                System.out.println(file.getTitle());
            }
            //parentFolderId = files.get(0).getParents().get(0).getId();

            filesRequest.setPageToken(filesList.getNextPageToken());
        } catch (IOException e) {
            System.out.println("An error occurred: " + e);
            filesRequest.setPageToken(null);
        }
    } while (filesRequest.getPageToken() != null && filesRequest.getPageToken().length() > 0);

    addMenu();
    CloudNet.noAccounts.setListItems(files, GOOGLE_CLOUD);
}

From source file:com.binomed.gdg.form.GdgFormActivity.java

License:Open Source License

/**
 * @param accessToken//from  ww  w  . ja  v  a 2 s. co  m
 * @return
 */
private HttpRequestInitializer getCredentialGoogle(final String accessToken) {
    GoogleCredential credential = new GoogleCredential();
    credential.setAccessToken(accessToken);
    return credential;
}

From source file:com.dhara.googlecalendartrial.MainActivity.java

private void setUp(final String userAccount) {
    try {//  w  w  w.ja  v a 2s . co m
        String clientId = "424045474279-tdm2pud0f32vovicoajj3hul5ot349r7.apps.googleusercontent.com";
        String clientSecret = "pjCbZO9lwGudNtk9CMKQ7GGx";

        // Or your redirect URL for web based applications.
        String redirectUrl = "https://localhost/oauth2callback"; //"urn:ietf:wg:oauth:2.0:oob";
        String scope = "https://www.googleapis.com/auth/calendar";
        java.util.List<String> listOfScope = new ArrayList<String>();
        listOfScope.add(scope);

        Collection<String> scopes = listOfScope;

        HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();

        // Step 1: Authorize -->
        String authorizationUrl = new GoogleAuthorizationCodeRequestUrl(clientId, redirectUrl, scopes).build();

        // Point or redirect your user to the authorizationUrl.
        System.out.println("Go to the following link in your browser:");
        System.out.println(authorizationUrl);

        // Read the authorization code from the standard input stream.
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is the authorization code?");
        String code = in.readLine();

        // End of Step 1 <--

        // Step 2: Exchange -->
        final GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(httpTransport, jsonFactory,
                clientId, clientSecret, code, redirectUrl).execute();
        // End of Step 2 <--

        /*GoogleAccessProtectedResource accessProtectedResource = new Google(
            response.getAccessToken(), httpTransport, jsonFactory, clientId, clientSecret,
            response.getRefreshToken());*/

        credential = new GoogleCredential().setAccessToken(response.getAccessToken());
        Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName("GoogleCalendarTrial").setHttpRequestInitializer(credential)
                .setCalendarRequestInitializer(new CalendarRequestInitializer() {
                    @Override
                    protected void initializeCalendarRequest(CalendarRequest<?> calendarRequest)
                            throws IOException {
                        super.initializeCalendarRequest(calendarRequest);
                        ArrayMap<String, Object> customKeys = new ArrayMap<String, Object>();
                        customKeys.put("xoauth_requestor_id", userAccount);
                        calendarRequest.setUnknownKeys(customKeys);
                        calendarRequest.setOauthToken(response.getAccessToken());
                        calendarRequest.setKey(apiKey);
                    }
                }).build();

        List find = service.events().list("primary");
        Events events = find.execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.dhara.googlecalendartrial.MainActivity.java

private void useCalendarAPI(final String accessToken, final String userAccount) {
    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    Log.e("tag", "accessToken : " + accessToken);
    credential = new GoogleCredential().setAccessToken(accessToken);
    try {// w  w  w .  j a v  a2s  .com
        //String path = "data/data/com.dhara.googlecalendartrial" + "/private_key";
        //String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/private_key/" + "3ceb5f543e0a13a3bd1028c5a32a89dab9397dbb-privatekey.p12";
        //java.io.File licenseFile = new java.io.File(path);
        //licenseFile.mkdir();
        //licenseFile.mkdirs();

        //if(!licenseFile.mkdirs()) {
        //licenseFile.mkdirs();
        //licenseFile.mkdir();
        //}

        //licenseFile = new File(path,"3ceb5f543e0a13a3bd1028c5a32a89dab9397dbb-privatekey.p12");

        /*credential = new GoogleCredential.Builder()
             .setServiceAccountId("424045474279-dv03cnl1aslne6mpec6tlap5mg4uuei2.apps.googleusercontent.com")
             .setTransport(transport)
             .setJsonFactory(jsonFactory)
             .setServiceAccountPrivateKeyFromP12File(new File(path))
             .setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR))
             .build();*/

        credential.setAccessToken(accessToken);

        //.setServiceAccountPrivateKeyFromP12File( new java.io.File(path))

        /*credential =
         GoogleCredential.usingOAuth2(this, Collections.singleton(CalendarScopes.CALENDAR));*/

        /*mGoogleApiClient = new GoogleApiClient.Builder(this)
           .addApi(com.google.android.gms.common.api..API)
           .addScope(Drive.SCOPE_FILE)
           .addConnectionCallbacks(this)
           .addOnConnectionFailedListener(this)
           .build();*/

        service = new Calendar.Builder(transport, jsonFactory, credential)
                .setApplicationName("GoogleCalendarTrial").setHttpRequestInitializer(credential)
                .setCalendarRequestInitializer(new CalendarRequestInitializer() {
                    @Override
                    protected void initializeCalendarRequest(CalendarRequest<?> calendarRequest)
                            throws IOException {
                        super.initializeCalendarRequest(calendarRequest);
                        ArrayMap<String, Object> customKeys = new ArrayMap<String, Object>();
                        customKeys.put("xoauth_requestor_id", userAccount);
                        calendarRequest.setUnknownKeys(customKeys);
                        calendarRequest.setOauthToken(accessToken);
                        calendarRequest.setKey(apiKey);
                    }
                }).build();

        mUserAccount = userAccount;

        CalendarList.List calendarList = service.calendarList().list();

        Log.e("tag", "calendarList: " + calendarList.size());
        java.util.List<CalendarListEntry> calendarListEntry = calendarList.execute().getItems();

        Log.e("tag", "calendarListEntry: " + calendarListEntry.size());

        /*for(int i=0;i<calendarListEntry.size();i++) {
           CalendarListEntry entry = calendarListEntry.get(i);
           Log.e("tag","calendar entry : " + entry.getDescription());
        }
                
        List find = service.events().list(userAccount).setCalendarId(calendarListEntry.get(2).getId());*/
        List find = service.events().list(userAccount);
        Events events = find.execute();
        mEventList = events.getItems();
        setAdapter();
    } catch (IOException e) {
        t.send(new HitBuilders.ExceptionBuilder()
                .setDescription(new StandardExceptionParser(MainActivity.this, null)
                        .getDescription(Thread.currentThread().getName(), e))
                .setFatal(false).build());

        e.printStackTrace();
        accountManager.invalidateAuthToken(account.type, accessToken);
    } /*catch (GeneralSecurityException e) {
        e.printStackTrace();
      }*/

    // Setting up the Tasks API Service
    /*
    HttpRequestInitializer requestInitializer = new HttpRequestInitializer() {
       public void initialize(HttpRequest request) throws IOException {
    request.getHeaders().setAuthorization(HttpHeaders..getGoogleLoginValue(accessToken));
       }
    };*/

    /*service = com.google.api.services.tasks.Tasks.builder(transport, jsonFactory)
      .setApplicationName("Google-TasksAndroidSample/1.0")
      .setHttpRequestInitializer(credential)
      .setJsonHttpRequestInitializer(new GoogleKeyInitializer(ClientCredentials.KEY))
      .build();*/

    /*service.accessKey = "AIzaSyAw1Ys2vLh152sKyfmbXUEK-aDKyhkwCFQ";
    service.setApplicationName("GoogleCalendarTrial");*/
}

From source file:com.dotosoft.dotoquiz.tools.thirdparty.GoogleOAuth.java

License:Apache License

private static Credential getRefreshedCredentials(String refreshCode, Settings setting)
        throws IOException, GeneralSecurityException {
    // HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    log.info("Getting access token for refresh token..");

    try {/*from  w w w.j ava  2 s  . c om*/
        if (setting.getApi().getClientSecret().getClientId().startsWith("Enter")
                || setting.getApi().getClientSecret().getClientSecret().startsWith("Enter ")) {
            System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/ "
                    + "into oauth2-cmdline-sample/src/main/resources/client_secrets.json");
            System.exit(1);
        }

        GoogleTokenResponse response = new GoogleRefreshTokenRequest(httpTransport, JSON_FACTORY, refreshCode,
                setting.getApi().getClientSecret().getClientId(),
                setting.getApi().getClientSecret().getClientSecret()).execute();

        return new GoogleCredential().setAccessToken(response.getAccessToken());

    } catch (UnknownHostException ex) {
        log.error("Unknown host. No web access?");
        throw ex;
    } catch (IOException e) {
        log.error("Exception getting refreshed auth: ", e);
    }
    return null;
}

From source file:com.example.taphan.core1.languageProcessing.AccessTokenLoader.java

License:Open Source License

@Override
public String loadInBackground() {

    final SharedPreferences prefs = getContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
    String currentToken = prefs.getString(PREF_ACCESS_TOKEN, null);

    // Check if the current token is still valid for a while
    if (currentToken != null) {
        final GoogleCredential credential = new GoogleCredential().setAccessToken(currentToken)
                .createScoped(CloudNaturalLanguageAPIScopes.all());
        final Long seconds = credential.getExpiresInSeconds();
        if (seconds != null && seconds > 3600) {
            return currentToken;
        }/*  w w  w  .java  2 s  . c om*/
    }

    final InputStream stream = getContext().getResources().openRawResource(R.raw.credential);
    try {
        final GoogleCredential credential = GoogleCredential.fromStream(stream)
                .createScoped(CloudNaturalLanguageAPIScopes.all());
        credential.refreshToken();
        final String accessToken = credential.getAccessToken();
        prefs.edit().putString(PREF_ACCESS_TOKEN, accessToken).apply();
        return accessToken;
    } catch (IOException e) {
        Log.e(TAG, "Failed to obtain access token.", e);
    }
    return null;
}

From source file:com.example.taphan.core1.languageProcessing.ApiFragment.java

License:Open Source License

public void setAccessToken(String token) {
    mCredential = new GoogleCredential().setAccessToken(token)
            .createScoped(CloudNaturalLanguageAPIScopes.all());
    startWorkerThread();/*from   ww w  .jav  a2s  .  c o m*/
}

From source file:com.gdgdevfest.android.apps.devfestbcn.sync.SyncHelper.java

License:Apache License

private Googledevelopers getConferenceAPIClient() {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new GsonFactory();
    GoogleCredential credential = new GoogleCredential().setAccessToken(AccountUtils.getAuthToken(mContext));
    // Note: The Googledevelopers API is unique, in that it requires an API key in addition to the client
    //       ID normally embedded an an OAuth token. Most apps will use one or the other.
    return new Googledevelopers.Builder(httpTransport, jsonFactory, null)
            .setApplicationName(NetUtils.getUserAgent(mContext))
            .setGoogleClientRequestInitializer(new CommonGoogleClientRequestInitializer(Config.API_KEY))
            .setHttpRequestInitializer(credential).build();
}