List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential GoogleCredential
public GoogleCredential()
From source file:com.github.jdavisonc.camel.gdrive.GDriveEndpoint.java
License:Apache License
private Drive createGDriveClient(String accessToken) { GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken); return new Drive.Builder(httpTransport, jsonFactory, credential).build(); }
From source file:com.github.tempora.oauth.CurrentUser.java
License:Apache License
public Optional<GoogleCredential> getCredential() { if (googleCredential == null && accessToken != null) { googleCredential = new GoogleCredential().setAccessToken(accessToken); }//from w w w .java 2s . c o m return Optional.ofNullable(googleCredential); }
From source file:com.google.appinventor.components.runtime.FusiontablesControl.java
License:Open Source License
/** * Executes a Fusiontable query with an OAuth 2.0 authenticated * request. Requests are authenticated by attaching an * Authentication header to the Http request. The header * takes the form 'Authentication Oauth <access_token>'. * * Requests take the form of SQL strings, using an Sql * object from the Google API Client library. Apparently * the Sql object handles the decision of whether the request * should be a GET or a POST. Queries such as 'show tables' * and 'select' are supposed to be GETs and queries such as * 'insert' are supposed to be POSTS./*from w w w . j a v a 2s .c o m*/ * * See <a href="https://developers.google.com/fusiontables/docs/v1/using">https://developers.google.com/fusiontables/docs/v1/using</a> * * @param query the raw SQL string used by App Inventor * @param authToken the OAuth 2.0 access token * @return the HttpResponse if the request succeeded, or null */ public com.google.api.client.http.HttpResponse sendQuery(String query, String authToken) { errorMessage = standardErrorMessage; // In case we get an error without a message Log.i(LOG_TAG, "executing " + query); com.google.api.client.http.HttpResponse response = null; // Create a Fusiontables service object (from Google API client lib) Fusiontables service = new Fusiontables.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), new GoogleCredential()).setApplicationName("App Inventor Fusiontables/v1.0") .setJsonHttpRequestInitializer(new GoogleKeyInitializer(ApiKey())).build(); try { // Construct the SQL query and get a CSV result Sql sql = ((Fusiontables) service).query().sql(query); sql.put("alt", "csv"); // Add the authToken to authentication header sql.setOauthToken(authToken); response = sql.executeUnparsed(); } catch (GoogleJsonResponseException e) { e.printStackTrace(); errorMessage = e.getMessage(); Log.e(LOG_TAG, "JsonResponseException"); Log.e(LOG_TAG, "e.getMessage() is " + e.getMessage()); Log.e(LOG_TAG, "response is " + response); } catch (IOException e) { e.printStackTrace(); errorMessage = e.getMessage(); Log.e(LOG_TAG, "IOException"); Log.e(LOG_TAG, "e.getMessage() is " + e.getMessage()); Log.e(LOG_TAG, "response is " + response); } return response; }
From source file:com.google.cloud.android.language.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(CloudNaturalLanguageScopes.all()); final Long seconds = credential.getExpiresInSeconds(); if (seconds != null && seconds > 3600) { return currentToken; }//from w ww. j a va2s . c o m } // ***** WARNING ***** // In this sample, we load the credential from a JSON file stored in a raw resource folder // of this client app. You should never do this in your app. Instead, store the file in your // server and obtain an access token from there. // ******************* final InputStream stream = getContext().getResources().openRawResource(R.raw.credential); try { final GoogleCredential credential = GoogleCredential.fromStream(stream) .createScoped(CloudNaturalLanguageScopes.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.google.cloud.android.language.ApiFragment.java
License:Open Source License
public void setAccessToken(String token) { mCredential = new GoogleCredential().setAccessToken(token).createScoped(CloudNaturalLanguageScopes.all()); startWorkerThread(); }
From source file:com.google.plus.samples.verifytoken.Verify.java
License:Open Source License
/** * Register all endpoints that we'll handle in our server. * @param args Command-line arguments.// w w w .java 2s. com */ public static void main(String[] args) { // Initialize a session for the current user, and render index.html. get(new Route("/") { @Override public Object handle(Request request, Response response) { response.type("text/html"); try { // Fancy way to read index.html into memory, and set the client ID // in the HTML before serving it. return new Scanner(new File("index.html"), "UTF-8").useDelimiter("\\A").next() .replaceAll("[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID) .replaceAll("[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APPLICATION_NAME); } catch (FileNotFoundException e) { // When running the sample, there was some path issue in finding // index.html. Double check the guide. e.printStackTrace(); return e.toString(); } } }); // "Verify an ID Token or an Access Token. // Tokens should be passed in the URL parameters of a POST request. post(new Route("/verify") { @Override public Object handle(Request request, Response response) { response.type("application/json"); String idToken = request.queryParams("id_token"); String accessToken = request.queryParams("access_token"); TokenStatus idStatus = new TokenStatus(); if (idToken != null) { // Check that the ID Token is valid. Checker checker = new Checker(new String[] { CLIENT_ID }, CLIENT_ID); GoogleIdToken.Payload jwt = checker.check(idToken); if (jwt == null) { // This is not a valid token. idStatus.setValid(false); idStatus.setId(""); idStatus.setMessage("Invalid ID Token."); } else { idStatus.setValid(true); String gplusId = (String) jwt.get("sub"); idStatus.setId(gplusId); idStatus.setMessage("ID Token is valid."); } } else { idStatus.setMessage("ID Token not provided"); } TokenStatus accessStatus = new TokenStatus(); if (accessToken != null) { // Check that the Access Token is valid. try { GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken); Oauth2 oauth2 = new Oauth2.Builder(TRANSPORT, JSON_FACTORY, credential).build(); Tokeninfo tokenInfo = oauth2.tokeninfo().setAccessToken(accessToken).execute(); if (tokenInfo.containsKey("error")) { // This is not a valid token. accessStatus.setValid(false); accessStatus.setId(""); accessStatus.setMessage("Invalid Access Token."); } else if (!tokenInfo.getIssuedTo().equals(CLIENT_ID)) { // This is not meant for this app. It is VERY important to check // the client ID in order to prevent man-in-the-middle attacks. accessStatus.setValid(false); accessStatus.setId(""); accessStatus.setMessage("Access Token not meant for this app."); } else { accessStatus.setValid(true); accessStatus.setId(tokenInfo.getUserId()); accessStatus.setMessage("Access Token is valid."); } } catch (IOException e) { accessStatus.setValid(false); accessStatus.setId(""); accessStatus.setMessage("Invalid Access Token."); } } else { accessStatus.setMessage("Access Token not provided"); } VerificationResponse tokenStatus = new VerificationResponse(idStatus, accessStatus); return GSON.toJson(tokenStatus); } }); }
From source file:com.google.refine.extension.gdata.GDataExtension.java
License:Open Source License
static public Drive getDriveService(String token) { GoogleCredential credential = new GoogleCredential().setAccessToken(token); return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(SERVICE_APP_NAME) .build();//w w w . j a va 2s. c om }
From source file:com.google.ytdl.DirectFragment.java
License:Apache License
public void directLite(final VideoData video, final String token) { video.addTag(Constants.DEFAULT_KEYWORD); video.addTag(Upload.generateKeywordFromPlaylistId(Constants.UPLOAD_PLAYLIST)); new AsyncTask<Void, Void, Void>() { @Override/*from ww w.j a va2s . co m*/ protected Void doInBackground(Void... voids) { GoogleCredential credential = new GoogleCredential(); credential.setAccessToken(token); HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); YouTube youtube = new YouTube.Builder(httpTransport, jsonFactory, credential) .setApplicationName(Constants.APP_NAME).build(); try { youtube.videos().update("snippet", video.getVideo()).execute(); } catch (IOException e) { Log.e(this.getClass().toString(), e.getMessage()); } return null; } }.execute((Void) null); }
From source file:com.google.ytdl.MainActivity.java
License:Apache License
private void loadProfile() { new AsyncTask<Void, Void, Person>() { @Override/*from ww w .j a va 2 s .co m*/ protected Person doInBackground(Void... voids) { GoogleCredential credential = new GoogleCredential(); credential.setAccessToken(mToken); HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); Plus plus = new Plus.Builder(httpTransport, jsonFactory, credential) .setApplicationName(Constants.APP_NAME).build(); try { return plus.people().get("me").execute(); } catch (final GoogleJsonResponseException e) { if (401 == e.getDetails().getCode()) { Log.e(this.getClass().getSimpleName(), e.getMessage()); GoogleAuthUtil.invalidateToken(MainActivity.this, mToken); mHandler.postDelayed(new Runnable() { @Override public void run() { tryAuthenticate(); } }, mCurrentBackoff * 1000); mCurrentBackoff *= 2; if (mCurrentBackoff == 0) { mCurrentBackoff = 1; } } } catch (final IOException e) { Log.e(this.getClass().getSimpleName(), e.getMessage()); } return null; } @Override protected void onPostExecute(Person me) { mUploadsListFragment.setProfileInfo(me); } }.execute((Void) null); }
From source file:com.google.ytdl.MainActivity.java
License:Apache License
private void loadUploadedVideos() { if (mToken == null) { return;/*from w ww. j av a 2s .c o m*/ } setProgressBarIndeterminateVisibility(true); new AsyncTask<Void, Void, List<VideoData>>() { @Override protected List<VideoData> doInBackground(Void... voids) { GoogleCredential credential = new GoogleCredential(); credential.setAccessToken(mToken); HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); YouTube yt = new YouTube.Builder(httpTransport, jsonFactory, credential) .setApplicationName(Constants.APP_NAME).build(); try { ChannelListResponse clr = yt.channels().list("contentDetails").setMine(true).execute(); String uploadsPlaylistId = clr.getItems().get(0).getContentDetails().getRelatedPlaylists() .getUploads(); List<VideoData> videos = new ArrayList<VideoData>(); PlaylistItemListResponse pilr = yt.playlistItems().list("id,contentDetails") .setPlaylistId(uploadsPlaylistId).setMaxResults(20l).execute(); List<String> videoIds = new ArrayList<String>(); for (PlaylistItem item : pilr.getItems()) { videoIds.add(item.getContentDetails().getVideoId()); } VideoListResponse vlr = yt.videos().list(TextUtils.join(",", videoIds), "id,snippet,status") .execute(); for (Video video : vlr.getItems()) { if ("public".equals(video.getStatus().getPrivacyStatus())) { VideoData videoData = new VideoData(); videoData.setVideo(video); videos.add(videoData); } } Collections.sort(videos, new Comparator<VideoData>() { @Override public int compare(VideoData videoData, VideoData videoData2) { return videoData.getTitle().compareTo(videoData2.getTitle()); } }); mCurrentBackoff = 0; return videos; } catch (final GoogleJsonResponseException e) { if (401 == e.getDetails().getCode()) { Log.e(this.getClass().getSimpleName(), e.getMessage()); GoogleAuthUtil.invalidateToken(MainActivity.this, mToken); mHandler.postDelayed(new Runnable() { @Override public void run() { tryAuthenticate(); } }, mCurrentBackoff * 1000); mCurrentBackoff *= 2; if (mCurrentBackoff == 0) { mCurrentBackoff = 1; } } } catch (final IOException e) { Log.e(this.getClass().getSimpleName(), e.getMessage()); } return null; } @Override protected void onPostExecute(List<VideoData> videos) { setProgressBarIndeterminateVisibility(false); if (videos == null) { return; } mUploadsListFragment.setVideos(videos); } }.execute((Void) null); }