List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential setAccessToken
@Override
public GoogleCredential setAccessToken(String accessToken)
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; }/*from 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; files.removeAll(files);/*from ww w .j a v a 2s . co m*/ 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.alow.servlet.ConnectServlet.java
License:Open Source License
/** * Exposed as `POST /api/connect`./* w w w . j a v a2 s . co m*/ * * Takes the following payload in the request body. The payload represents * all of the parameters that are required to authorize and connect the user * to the app. * { * "state":"", * "access_token":"", * "token_type":"", * "expires_in":"", * "code":"", * "id_token":"", * "authuser":"", * "session_state":"", * "prompt":"", * "client_id":"", * "scope":"", * "g_user_cookie_policy":"", * "cookie_policy":"", * "issued_at":"", * "expires_at":"", * "g-oauth-window":"" * } * * Returns the following JSON response representing the User that was * connected: * { * "id":0, * "googleUserId":"", * "googleDisplayName":"", * "googlePublicProfileUrl":"", * "googlePublicProfilePhotoUrl":"", * "googleExpiresAt":0 * } * * Issues the following errors along with corresponding HTTP response codes: * 401: The error from the Google token verification end point. * 500: "Failed to upgrade the authorization code." This can happen during * OAuth v2 code exchange flows. * 500: "Failed to read token data from Google." * This response also sends the error from the token verification * response concatenated to the error message. * 500: "Failed to query the Google+ API: " * This error also includes the error from the client library * concatenated to the error response. * 500: "IOException occurred." The IOException could happen when any * IO-related errors occur such as network connectivity loss or local * file-related errors. * * @see javax.servlet.http.HttpServlet#doPost( * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { TokenData accessToken = null; try { // read the token accessToken = Jsonifiable.fromJson(req.getReader(), TokenData.class); } catch (IOException e) { sendError(resp, 400, "Unable to read auth result from request body"); } // Create a credential object. GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY) .setTransport(TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build(); try { if (accessToken.code != null) { // exchange the code for a token (Web Frontend) GoogleTokenResponse tokenFromExchange = exchangeCode(accessToken); credential.setFromTokenResponse(tokenFromExchange); } else { if (accessToken.access_token == null) { sendError(resp, 400, "Missing access token in request."); } // use the token received from the client credential.setAccessToken(accessToken.access_token).setRefreshToken(accessToken.refresh_token) .setExpiresInSeconds(accessToken.expires_in) .setExpirationTimeMilliseconds(accessToken.expires_at); } // ensure that we consider logged in the user that owns the access token String tokenGoogleUserId = verifyToken(credential); User user = saveTokenForUser(tokenGoogleUserId, credential); // save the user in the session HttpSession session = req.getSession(); session.setAttribute(CURRENT_USER_SESSION_KEY, user.id); generateFriends(user, credential); sendResponse(req, resp, user); } catch (TokenVerificationException e) { sendError(resp, 401, e.getMessage()); } catch (TokenResponseException e) { sendError(resp, 500, "Failed to upgrade the authorization code."); } catch (TokenDataException e) { sendError(resp, 500, "Failed to read token data from Google. " + e.getMessage()); } catch (IOException e) { sendError(resp, 500, e.getMessage()); } catch (GoogleApiException e) { sendError(resp, 500, "Failed to query the Google+ API: " + e.getMessage()); } catch (DaoException e) { sendError(resp, 500, "Failed to access database: " + e.getMessage()); } catch (EntityExistsException e) { sendError(resp, 500, "Entity already exists: " + e.getMessage()); } }
From source file:com.binomed.gdg.form.GdgFormActivity.java
License:Open Source License
/** * @param accessToken//from w ww. j ava 2 s . c om * @return */ private HttpRequestInitializer getCredentialGoogle(final String accessToken) { GoogleCredential credential = new GoogleCredential(); credential.setAccessToken(accessToken); return credential; }
From source file:com.framework.common.GoogleSheets.java
public GoogleSheets(GoogleSheetConnectionDetails requiredSheet) { this.sheetName = requiredSheet.getSpreadSheetName(); this.workSheetName = requiredSheet.getWorkSheetName(); this.CLIENT_ID = requiredSheet.getClient_id(); this.CLIENT_SECRET = requiredSheet.getClient_secret(); this.refreshToken = requiredSheet.getRefreshToken(); this.accessToken = requiredSheet.getAccessToken(); List<String> scopes = Arrays.asList("https://www.googleapis.com/auth/drive"); try {// w w w.ja va 2 s . com GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT) .setJsonFactory(JSON_FACTORY).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build(); credential.setRefreshToken(refreshToken); credential.setAccessToken(accessToken); SpreadsheetService service = new SpreadsheetService("Aplication-name"); this.requiredservice = service; service.setOAuth2Credentials(credential); URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full"); // Make a request to the API and get all spreadsheets. SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class); List<com.google.gdata.data.spreadsheet.SpreadsheetEntry> spreadsheets = feed.getEntries(); boolean spreadsheetfound = false; int sheetCounter = 0; for (com.google.gdata.data.spreadsheet.SpreadsheetEntry spreadsheet : spreadsheets) { if (spreadsheets.isEmpty()) { System.out.println(" No spread sheets found."); throw new IllegalArgumentException(); } // System.out.println(spreadsheet.getTitle().getPlainText()); if (spreadsheet.getTitle().getPlainText().equalsIgnoreCase(this.sheetName)) { // System.out.println("Found it"); this.requiredSpreadsheet = spreadsheet; spreadsheetfound = true; } } if (!spreadsheetfound) { System.out.println("Spreadsheet not found, please check the name"); throw new IllegalArgumentException("Spreadsheet not found, please check the name"); } WorksheetFeed worksheetFeed = service.getFeed(requiredSpreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class); List<WorksheetEntry> worksheets = worksheetFeed.getEntries(); boolean worksheetfound = false; for (WorksheetEntry worksheet : worksheets) { // System.out.println(worksheet.getTitle().getPlainText()); if (worksheet.getTitle().getPlainText().equalsIgnoreCase(workSheetName)) { // System.out.println("Found It"); this.requiredWorkSheet = worksheet; worksheetfound = true; } sheetCounter++; } if (!worksheetfound) { System.out.println("Worksheet was not found, please check the name"); throw new IllegalArgumentException("Worksheet was not found, please check the name"); } this.totalSheets = sheetCounter; } catch (Exception e) { e.printStackTrace(); } }
From source file:com.google.plus.samples.photohunt.ConnectServlet.java
License:Open Source License
/** * Exposed as `POST /api/connect`.//from w ww.j av a2 s .c o m * <p> * Takes the following payload in the request body. Payload represents all * parameters required to authorize and/or connect. * { * "state":"", * "access_token":"", * "token_type":"", * "expires_in":"", * "code":"", * "id_token":"", * "authuser":"", * "session_state":"", * "prompt":"", * "client_id":"", * "scope":"", * "g_user_cookie_policy":"", * "cookie_policy":"", * "issued_at":"", * "expires_at":"", * "g-oauth-window":"" * } * <p> * Returns the following JSON response representing the User that was * connected: * { * "id":0, * "googleUserId":"", * "googleDisplayName":"", * "googlePublicProfileUrl":"", * "googlePublicProfilePhotoUrl":"", * "googleExpiresAt":0 * } * <p> * Issues the following errors along with corresponding HTTP response codes: * 401: error from token verification end-point. * 500: "Failed to upgrade the authorization code." (for code exchange flows) * 500: "Failed to read token data from Google." * + error from reading token verification response. * 500: "Failed to query the Google+ API: " + error from client library. * 500: IOException occurred (several ways this could happen). * * @see javax.servlet.http.HttpServlet#doPost( *javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { TokenData accessToken = null; try { // read the token accessToken = Jsonifiable.fromJson(req.getReader(), TokenData.class); } catch (IOException e) { sendError(resp, 400, "Unable to read auth result from request body"); } // Create a credential object. GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY) .setTransport(TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build(); try { if (accessToken.code != null) { // exchange the code for a token (Web Frontend) GoogleTokenResponse tokenFromExchange = exchangeCode(accessToken); credential.setFromTokenResponse(tokenFromExchange); } else { // use the token received from the client credential.setAccessToken(accessToken.access_token).setRefreshToken(accessToken.refresh_token) .setExpiresInSeconds(accessToken.expires_in) .setExpirationTimeMilliseconds(accessToken.expires_at); } // ensure that we consider logged in the user that owns the access token String tokenGoogleUserId = verifyToken(credential); User user = saveTokenForUser(tokenGoogleUserId, credential); // save the user in the session HttpSession session = req.getSession(); session.setAttribute(CURRENT_USER_SESSION_KEY, user.id); generateFriends(user, credential); sendResponse(req, resp, user); } catch (TokenVerificationException e) { sendError(resp, 401, e.getMessage()); } catch (TokenResponseException e) { sendError(resp, 500, "Failed to upgrade the authorization code."); } catch (TokenDataException e) { sendError(resp, 500, "Failed to read token data from Google. " + e.getMessage()); } catch (IOException e) { sendError(resp, 500, e.getMessage()); } catch (GoogleApiException e) { sendError(resp, 500, "Failed to query the Google+ API: " + e.getMessage()); } }
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/* ww w . java 2 s. 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// www . j a v a2s.c o 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 w w .j ava 2s.co 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); }
From source file:com.google.ytdl.UploadService.java
License:Apache License
@Override protected void onHandleIntent(Intent intent) { mFileUri = intent.getData();//from w ww .j a va 2 s. c om mToken = intent.getStringExtra("token"); mFileSize = intent.getLongExtra("length", 0); GoogleCredential credential = new GoogleCredential(); credential.setAccessToken(mToken); HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); YouTube youtube = new YouTube.Builder(httpTransport, jsonFactory, credential) .setApplicationName(Constants.APP_NAME).build(); InputStream fileInputStream = null; try { mFileSize = getContentResolver().openFileDescriptor(mFileUri, "r").getStatSize(); fileInputStream = getContentResolver().openInputStream(mFileUri); } catch (FileNotFoundException e) { Log.e(getApplicationContext().toString(), e.getMessage()); } ResumableUpload.upload(youtube, fileInputStream, mFileSize, getApplicationContext()); }