List of usage examples for com.google.api.client.googleapis.extensions.android.gms.auth GoogleAccountCredential getToken
public String getToken() throws IOException, GoogleAuthException
From source file:br.com.bioscada.apps.biotracks.io.sendtogoogle.SendToGoogleUtils.java
License:Apache License
/** * Gets the google account credential.//from w w w . j a v a2 s . c om * * @param context the context * @param accountName the account name * @param scope the scope */ public static GoogleAccountCredential getGoogleAccountCredential(Context context, String accountName, String scope) throws IOException, GoogleAuthException { GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, scope); credential.setSelectedAccountName(accountName); credential.getToken(); return credential; }
From source file:br.com.bioscada.apps.biotracks.io.sendtogoogle.SendToGoogleUtils.java
License:Apache License
/** * Gets the OAuth2 token.// w w w .j a va2s . co m * * @param context the context * @param accountName the account name * @param scope the scope */ public static String getToken(Context context, String accountName, String scope) throws IOException, GoogleAuthException { GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, scope); credential.setSelectedAccountName(accountName); return credential.getToken(); }
From source file:com.flowzr.budget.holo.export.flowzr.GoogleDrivePictureClient.java
License:Open Source License
public static Drive create(Context context) throws IOException, GoogleAuthException, ImportExportException { String googleDriveAccount = MyPreferences.getGoogleDriveAccount(context); if (googleDriveAccount == null) { throw new ImportExportException(R.string.google_drive_account_required); }//ww w .j a v a 2 s.co m try { List<String> scope = new ArrayList<String>(); scope.add(DriveScopes.DRIVE_FILE); if (MyPreferences.isGoogleDriveFullReadonly(context)) { scope.add(DriveScopes.DRIVE_READONLY); } GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, scope); credential.setSelectedAccountName(googleDriveAccount); credential.getToken(); return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build(); } catch (UserRecoverableAuthException e) { NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Intent authorizationIntent = e.getIntent(); authorizationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_FROM_BACKGROUND); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, authorizationIntent, 0); Notification notification = new NotificationCompat.Builder(context) .setSmallIcon(android.R.drawable.ic_dialog_alert) .setTicker(context.getString(R.string.google_drive_permission_requested)) .setContentTitle(context.getString(R.string.google_drive_permission_requested)) .setContentText(context.getString(R.string.google_drive_permission_requested_for_account, googleDriveAccount)) .setContentIntent(pendingIntent).setAutoCancel(true).build(); notificationManager.notify(0, notification); throw new ImportExportException(R.string.google_drive_permission_required); } }
From source file:com.flowzr.export.flowzr.GoogleDrivePictureClient.java
License:Open Source License
public static Drive create(Context context) throws IOException, ImportExportException, GoogleAuthException { String googleDriveAccount = MyPreferences.getGoogleDriveAccount(context); if (googleDriveAccount == null) { throw new ImportExportException(R.string.google_drive_account_required); }//w w w . j ava 2 s . com try { List<String> scope = new ArrayList<String>(); scope.add(DriveScopes.DRIVE_FILE); if (MyPreferences.isGoogleDriveFullReadonly(context)) { scope.add(DriveScopes.DRIVE_READONLY); } GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, scope); credential.setSelectedAccountName(googleDriveAccount); credential.getToken(); return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build(); } catch (UserRecoverableAuthException e) { NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Intent authorizationIntent = e.getIntent(); authorizationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_FROM_BACKGROUND); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, authorizationIntent, 0); Notification notification = new NotificationCompat.Builder(context) .setSmallIcon(android.R.drawable.ic_dialog_alert) .setTicker(context.getString(R.string.google_drive_permission_requested)) .setContentTitle(context.getString(R.string.google_drive_permission_requested)) .setContentText(context.getString(R.string.google_drive_permission_requested_for_account, googleDriveAccount)) .setContentIntent(pendingIntent).setAutoCancel(true).build(); notificationManager.notify(0, notification); throw new ImportExportException(R.string.google_drive_permission_required); } }
From source file:com.zns.comicdroid.service.GoogleDriveService.java
License:Open Source License
private synchronized void Backup(String account, String appId) { //Get Service Drive service = null;/* w w w . ja v a 2 s.c om*/ try { GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(Application.DRIVE_SCOPE_BACKUP)); credential.setSelectedAccountName(account); credential.getToken(); service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), credential) .build(); } catch (UserRecoverableAuthException e) { //We are not authenticated for some reason, notify user. NotifyAuthentication(); return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } catch (GoogleAuthException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } //Make sure the current backup is made from the same device try { com.google.api.services.drive.model.File f = DriveUtil.getFile(service, "appdata", BACKUP_META_FILENAME); if (f != null) { HttpResponse response = service.getRequestFactory() .buildGetRequest(new GenericUrl(f.getDownloadUrl())).execute(); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getContent())); String backupAppId = reader.readLine(); reader.close(); response.disconnect(); if (!backupAppId.equals(appId)) { mLogger.appendLog("Unable to backup to drive, appid does not match", Logger.TAG_BACKUP); return; } } } catch (Exception e) { e.printStackTrace(); } //------------------Upload current backup to google drive--------------------------- //Get file path String outPath = getApplicationContext().getExternalFilesDir(null).toString() + "/backup"; File fileData = new File(outPath, BACKUP_DATA_FILENAME); //Upload to google drive int timeStamp = (int) (System.currentTimeMillis() / 1000L); boolean uploadSuccess = true; try { //Get files to update/insert com.google.api.services.drive.model.File dataDriveFile = null; com.google.api.services.drive.model.File metaDriveFile = null; FileList list = service.files().list().setQ("'appdata' in parents").execute(); for (com.google.api.services.drive.model.File f : list.getItems()) { if (f.getTitle().toLowerCase(Locale.ENGLISH).equals(BACKUP_META_FILENAME)) { metaDriveFile = f; } else if (f.getTitle().toLowerCase(Locale.ENGLISH).equals(BACKUP_DATA_FILENAME)) { dataDriveFile = f; } } //Insert meta ByteArrayContent contentMeta = ByteArrayContent.fromString("text/plain", appId + "\n" + Integer.toString(timeStamp)); com.google.api.services.drive.model.File fMeta = new com.google.api.services.drive.model.File(); fMeta.setTitle(BACKUP_META_FILENAME); fMeta.setMimeType("text/plain"); fMeta.setParents(Arrays.asList(new ParentReference().setId("appdata"))); if (metaDriveFile == null) { service.files().insert(fMeta, contentMeta).execute(); } else { Update update = service.files().update(metaDriveFile.getId(), null, contentMeta); update.setNewRevision(false); update.execute(); } //Insert/Update data FileContent contentData = new FileContent("application/octet-stream", fileData); com.google.api.services.drive.model.File fData = new com.google.api.services.drive.model.File(); fData.setTitle(BACKUP_DATA_FILENAME); fData.setMimeType("application/octet-stream"); fData.setParents(Arrays.asList(new ParentReference().setId("appdata"))); if (dataDriveFile == null) { service.files().insert(fData, contentData).execute(); } else { Update update = service.files().update(dataDriveFile.getId(), null, contentData); update.setNewRevision(false); update.execute(); } } catch (Exception e) { uploadSuccess = false; e.printStackTrace(); } //Success? SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Editor edit = prefs.edit(); edit.putBoolean(Application.PREF_BACKUP_SUCCESS, uploadSuccess); if (uploadSuccess) { mLogger.appendLog("Backup to drive success", Logger.TAG_BACKUP); edit.putInt(Application.PREF_BACKUP_LAST, timeStamp); } else { mLogger.appendLog("Backup to drive failed", Logger.TAG_BACKUP); } edit.commit(); }
From source file:com.zns.comicdroid.service.GoogleDriveService.java
License:Open Source License
private synchronized void PublishComics(String account, String webFolderId, boolean force) { //Get Service Drive service = null;/* www . j ava 2 s . c o m*/ try { GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(Application.DRIVE_SCOPE_PUBLISH)); credential.setSelectedAccountName(account); credential.getToken(); service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), credential) .build(); } catch (UserRecoverableAuthException e) { //We are not authenticated for some reason, notify user. NotifyAuthentication(); return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } catch (GoogleAuthException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } //Make sure webfolder still exists try { com.google.api.services.drive.model.File webFolder = service.files().get(webFolderId).execute(); if (webFolder == null || webFolder.getExplicitlyTrashed() == Boolean.TRUE) { NotifyAuthentication(); return; } } catch (IOException e) { NotifyAuthentication(); return; } //Get some more stuff from context String outPath = getApplicationContext().getExternalFilesDir(null).toString() + "/html"; String imagePath = ((Application) getApplication()).getImagePath(true); //Let's get started File fileOut = new File(outPath); fileOut.mkdirs(); fileOut = new File(outPath, PUBLISH_INDEX_FILENAME); BufferedReader reader = null; BufferedWriter writer = null; Cursor cursor = null; try { cursor = mDb.getCursor( "SELECT _id, Title, Subtitle, Author, Image, ImageUrl, 1 AS ItemType, 0 AS BookCount, IsBorrowed, AddedDate " + "FROM tblBooks WHERE GroupId = 0 OR ifnull(GroupId, '') = '' " + "UNION " + "SELECT _id, Name AS Title, '' AS Subtitle, '' AS Author, (SELECT Image FROM tblBooks where GroupId = tblGroups._id) AS Image, ImageUrl, 2 AS ItemType, BookCount, 0 AS IsBorrowed, 0 AS PublishDate " + "FROM tblGroups " + "ORDER BY Title", null); int rowCount = cursor.getCount(); String line; //Read template StringBuilder sbTemplate = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.listtemplate))); while ((line = reader.readLine()) != null) { sbTemplate.append(line); } reader.close(); //Write HTML writer = new BufferedWriter(new FileWriter(fileOut)); reader = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.framework))); int i = 0; while ((line = reader.readLine()) != null) { if (line.trim().equals("#LISTCOMICS#")) { while (cursor.moveToNext()) { int id = cursor.getInt(0); String title = nullToEmpty(cursor.getString(1)); String subTitle = nullToEmpty(cursor.getString(2)); String author = nullToEmpty(cursor.getString(3)); String image = nullToEmpty(cursor.getString(4)); String imageUrl = nullToEmpty(cursor.getString(5)); int type = cursor.getInt(6); int date = cursor.getInt(9); StringBuilder sbChildren = new StringBuilder(); String comicLine = sbTemplate.toString(); comicLine = comicLine.replace("#TITLE#", title + (type == 1 && !subTitle.equals("") ? " - " + subTitle : "")); comicLine = comicLine.replace("#AUTHOR#", author); comicLine = comicLine.replace("#IMAGEURL#", getImageSrc(imageUrl, image, imagePath)); comicLine = comicLine.replace("#ISSUE#", ""); comicLine = comicLine.replace("#ISAGGREGATE#", type == 2 ? " Aggregate" : ""); comicLine = comicLine.replace("#MARK#", type == 2 ? "<div class=\"Mark\"></div>" : ""); comicLine = comicLine.replace("#DATE#", type == 1 ? Integer.toString(date) : ""); if (type == 2) { //Render group children List<Comic> comics = mDb.getComics(id); for (Comic comic : comics) { String childComic = sbTemplate.toString(); childComic = childComic.replace("#TITLE#", nullToEmpty(comic.getTitle()) + (!nullToEmpty(comic.getSubTitle()).equals("") ? " - " + comic.getSubTitle() : "")); childComic = childComic.replace("#AUTHOR#", nullToEmpty(comic.getAuthor())); childComic = childComic.replace("#IMAGEURL#", getImageSrc(nullToEmpty(comic.getImageUrl()), nullToEmpty(comic.getImage()), imagePath)); childComic = childComic.replace("#ISSUE#", comic.getIssue() > 0 ? Integer.toString(comic.getIssue()) : ""); childComic = childComic.replace("#DATE#", Integer.toString(comic.getAddedDateTimestamp())); childComic = childComic.replace("#ISAGGREGATE#", ""); childComic = childComic.replace("#MARK#", ""); childComic = childComic.replace("#CHILDREN#", ""); sbChildren.append(childComic); } comicLine = comicLine.replace("#CHILDREN#", sbChildren.toString()); } else { comicLine = comicLine.replace("#CHILDREN#", ""); } writer.write(comicLine); if (force) { Double part = (((double) i + 1) / (double) rowCount) * 100.0; EventBus.getDefault().post( new ProgressResult(part.intValue(), getString(R.string.progress_publish))); i++; } } } else { writer.write(line); } } } catch (Exception e) { //Gotta catch'em all! return; } finally { if (cursor != null) cursor.close(); try { if (writer != null) writer.close(); if (reader != null) reader.close(); } catch (IOException e) { } } //Upload to google drive if (force) { EventBus.getDefault().post(new ProgressResult(20, getString(R.string.progress_publishupload))); } try { //Get current index file com.google.api.services.drive.model.File fileIndex = DriveUtil.getFile(service, webFolderId, PUBLISH_INDEX_FILENAME); //Set content of file FileContent content = new FileContent("text/html", fileOut); //Insert / Update if (fileIndex == null) { com.google.api.services.drive.model.File driveFile = new com.google.api.services.drive.model.File(); driveFile.setTitle(PUBLISH_INDEX_FILENAME); driveFile.setMimeType("text/html"); driveFile.setParents(Arrays.asList(new ParentReference().setId(webFolderId))); service.files().insert(driveFile, content).execute(); } else { Update update = service.files().update(fileIndex.getId(), null, content); update.setNewRevision(false); update.execute(); } mLogger.appendLog("Published to google drive", Logger.TAG_BACKUP); } catch (Exception e) { mLogger.appendLog("Failed to publish to google drive", Logger.TAG_BACKUP); e.printStackTrace(); } if (force) { EventBus.getDefault().post(new ProgressResult(100, getString(R.string.progress_publishupload))); } }
From source file:com.zns.comicdroid.service.RestoreFromDriveService.java
License:Open Source License
@Override protected void onHandleIntent(Intent intent) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String account = prefs.getString(Application.PREF_DRIVE_ACCOUNT, null); com.google.api.services.drive.model.File gFileData = null; //Get Service Drive service = null;/*from ww w . j av a 2 s.c o m*/ try { GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(Application.DRIVE_SCOPE_BACKUP)); credential.setSelectedAccountName(account); credential.getToken(); service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), credential) .build(); gFileData = DriveUtil.getFile(service, "appdata", GoogleDriveService.BACKUP_DATA_FILENAME); } catch (Exception e) { //Failed to get data from google drive } //-------------------------Restore Data------------------------------------ if (gFileData != null && gFileData.getDownloadUrl() != null && gFileData.getDownloadUrl().length() > 0) { DBHelper db = DBHelper.getHelper(getApplicationContext()); String imagePath = ((Application) getApplication()).getImagePath(true); DataInputStream in = null; try { //Get http response for data file HttpResponse response = service.getRequestFactory() .buildGetRequest(new GenericUrl(gFileData.getDownloadUrl())).execute(); in = new DataInputStream(response.getContent()); //Restore data BackupUtil.RestoreDataFromStream(in, db, imagePath, getResources()); } catch (Exception e) { //Restore failed } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } else { EventBus.getDefault().post(new ProgressResult(100, "")); } stopSelf(); }
From source file:org.opensilk.music.plugin.drive.SessionFactory.java
License:Open Source License
public Session getSession(String accountName) throws IOException, GoogleAuthException { Session s = sSessions.get(accountName); if (s != null) { return s; }//ww w. j a v a2 s . c o m final GoogleAccountCredential credential = GoogleAccountCredential .usingOAuth2(context, Collections.singleton(DriveScopes.DRIVE_READONLY)) .setSelectedAccountName(accountName); final Drive drive = new Drive.Builder(AndroidHttp.newCompatibleTransport(), AndroidJsonFactory.getDefaultInstance(), credential).setApplicationName(APP_NAME).build(); final String token = credential.getToken(); final Session holder = new Session(credential, drive, token); sSessions.put(accountName, holder); return holder; }