@Override
  public List<ExtRepositoryFileVersion> getExtRepositoryFileVersions(
      ExtRepositoryFileEntry extRepositoryFileEntry) throws PortalException {

    try {
      Drive drive = getDrive();

      Drive.Revisions driveRevisions = drive.revisions();

      Drive.Revisions.List driveRevisionsList =
          driveRevisions.list(extRepositoryFileEntry.getExtRepositoryModelKey());

      RevisionList revisionList = driveRevisionsList.execute();

      List<Revision> revisions = revisionList.getItems();

      List<ExtRepositoryFileVersion> extRepositoryFileVersions = new ArrayList<>(revisions.size());

      for (int i = 0; i < revisions.size(); i++) {
        Revision revision = revisions.get(i);

        extRepositoryFileVersions.add(
            new GoogleDriveFileVersion(
                revision, extRepositoryFileEntry.getExtRepositoryModelKey(), i + 1));
      }

      Collections.reverse(extRepositoryFileVersions);

      return extRepositoryFileVersions;
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
  @Override
  public ExtRepositoryFileVersion getExtRepositoryFileVersion(
      ExtRepositoryFileEntry extRepositoryFileEntry, String version) throws PortalException {

    try {
      Drive drive = getDrive();

      Drive.Revisions driveRevisions = drive.revisions();

      Drive.Revisions.List driveRevisionsList =
          driveRevisions.list(extRepositoryFileEntry.getExtRepositoryModelKey());

      RevisionList revisionList = driveRevisionsList.execute();

      List<Revision> revisions = revisionList.getItems();

      int[] versionParts = StringUtil.split(version, StringPool.PERIOD, 0);

      Revision revision = revisions.get(versionParts[0]);

      return new GoogleDriveFileVersion(
          revision, extRepositoryFileEntry.getExtRepositoryModelKey(), versionParts[0]);
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
  private static String folderContains(String filename, String folderID) {

    // Returns the ID of a specified filename in a folder or null if it does not exist

    File child = null;
    ChildList children = null;
    try {
      children = service.children().list(folderID).execute();
      for (ChildReference element : children.getItems()) {
        child = service.files().get(element.getId()).execute();
        if (child.getTitle().equals(filename)) {
          break;
        }
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      // System.out.println("children: "+children.toPrettyString());
      // System.out.println("child: "+child.toPrettyString());
    }

    if (child != null && child.getTitle().equals(filename)) {
      return child.getId();
    }

    return null;
  }
  @Override
  public ExtRepositoryFileEntry updateExtRepositoryFileEntry(
      String extRepositoryFileEntryKey, String mimeType, InputStream inputStream)
      throws PortalException {

    try {
      Drive drive = getDrive();

      Drive.Files driveFiles = drive.files();

      File file = getFile(drive, extRepositoryFileEntryKey);

      InputStreamContent inputStreamContent = new InputStreamContent(mimeType, inputStream);

      Drive.Files.Update driveFilesUpdate =
          driveFiles.update(extRepositoryFileEntryKey, file, inputStreamContent);

      file = driveFilesUpdate.execute();

      return new GoogleDriveFileEntry(file);
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
  public static String uploadDriveFile(
      String title,
      String description,
      String parentId,
      String mimeType,
      String filename,
      String path,
      String shareTo) {

    // File's metadata.
    File body = new File();
    body.setTitle(title);
    body.setDescription(description);
    body.setMimeType(mimeType);

    body.setParents(Arrays.asList(new ParentReference().setId(parentId)));
    // File's content.
    java.io.File fileContent = new java.io.File(path);
    FileContent mediaContent = new FileContent(mimeType, fileContent);
    try {
      File file = service.files().insert(body, mediaContent).execute();
      service.permissions().insert(file.getId(), perm).execute();

      // Uncomment the following line to print the File ID.
      // System.out.println("File ID: " + file.getId());

      return file.getId();
    } catch (IOException e) {
      System.out.println("An error occured: " + e);
      return null;
    }
  }
Beispiel #6
0
  /**
   * Delete spreadsheet which name is title.
   *
   * @param title the name of spreadsheet
   * @param activity to get context
   * @param accountName the name of Google account
   * @return true means delete successfully
   */
  public static boolean deleteSpreadsheetByTitle(
      String title, Activity activity, String accountName) {
    try {
      GoogleAccountCredential driveCredential =
          SendToGoogleUtils.getGoogleAccountCredential(
              activity.getApplicationContext(), accountName, SendToGoogleUtils.DRIVE_SCOPE);
      if (driveCredential == null) {
        return false;
      }

      Drive drive = SyncUtils.getDriveService(driveCredential);
      com.google.api.services.drive.Drive.Files.List list =
          drive
              .files()
              .list()
              .setQ(
                  String.format(Locale.US, SendSpreadsheetsAsyncTask.GET_SPREADSHEET_QUERY, title));
      List<File> files = list.execute().getItems();
      for (Iterator<File> iterator = files.iterator(); iterator.hasNext(); ) {
        File file = (File) iterator.next();
        drive.files().delete(file.getId()).execute();
      }
      return true;
    } catch (Exception e) {
      Log.e(EndToEndTestUtils.LOG_TAG, "Search spreadsheet failed.");
    }
    return false;
  }
  @Override
  public <T extends ExtRepositoryObject> T getExtRepositoryObject(
      ExtRepositoryObjectType<T> extRepositoryObjectType,
      String extRepositoryFolderKey,
      String title)
      throws PortalException {

    try {
      StringBundler sb = new StringBundler();

      sb.append("'");
      sb.append(extRepositoryFolderKey);
      sb.append("' in parents and title contains '");
      sb.append(title);
      sb.append(" and mimeType ");

      if (extRepositoryObjectType.equals(ExtRepositoryObjectType.FOLDER)) {

        sb.append("= ");
      } else {
        sb.append("!= ");
      }

      sb.append(_FOLDER_MIME_TYPE);

      Drive drive = getDrive();

      Drive.Files driveFiles = drive.files();

      Drive.Files.List driveFilesList = driveFiles.list();

      driveFilesList.setQ(sb.toString());

      FileList fileList = driveFilesList.execute();

      List<File> files = fileList.getItems();

      if (files.isEmpty()) {
        if (extRepositoryObjectType == ExtRepositoryObjectType.FOLDER) {
          throw new NoSuchFolderException(title);
        }

        throw new NoSuchFileEntryException(title);
      }

      if (extRepositoryObjectType.equals(ExtRepositoryObjectType.FOLDER)) {

        return (T) new GoogleDriveFolder(files.get(0), getRootFolderKey());
      }

      return (T) new GoogleDriveFileEntry(files.get(0));
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
Beispiel #8
0
  /** Insert all new local files in Google Drive. */
  private void insertNewLocalFiles() {
    Uri uri = getNotesUri(mAccount.name);
    try {
      Cursor cursor =
          mProvider.query(
              uri, PROJECTION, NotePad.Notes.COLUMN_NAME_FILE_ID + " is NULL", null, null);

      Log.d(TAG, "Inserting new local files: " + cursor.getCount());

      if (cursor.moveToFirst()) {
        do {
          Uri localFileUri = getNoteUri(mAccount.name, cursor.getString(COLUMN_INDEX_ID));

          if (cursor.getShort(COLUMN_INDEX_DELETED) != 0) {
            mProvider.delete(localFileUri, null, null);
          } else {
            File newFile = new File();

            newFile.setTitle(cursor.getString(COLUMN_INDEX_TITLE));
            newFile.setMimeType(TEXT_PLAIN);
            String content = cursor.getString(COLUMN_INDEX_NOTE);

            try {
              File insertedFile = null;

              if (content != null && content.length() > 0) {
                insertedFile =
                    mService
                        .files()
                        .insert(newFile, ByteArrayContent.fromString(TEXT_PLAIN, content))
                        .execute();
              } else {
                insertedFile = mService.files().insert(newFile).execute();
              }

              // Update the local file to add the file ID.
              ContentValues values = new ContentValues();
              values.put(
                  NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE,
                  insertedFile.getModifiedDate().getValue());
              values.put(
                  NotePad.Notes.COLUMN_NAME_CREATE_DATE, insertedFile.getCreatedDate().getValue());
              values.put(NotePad.Notes.COLUMN_NAME_FILE_ID, insertedFile.getId());

              mProvider.update(localFileUri, values, null, null);
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        } while (cursor.moveToNext());
      }
    } catch (RemoteException e) {
      e.printStackTrace();
    }
  }
 @ApiMethod(name = "user.verify.installation", httpMethod = HttpMethod.GET)
 public VerificationResult verifyInstallation(User user) {
   try {
     Drive service = Utils.createDriveFromUser(user);
     About execute = service.about().get().execute();
     return PASS;
   } catch (Exception e) {
     log.log(Level.WARNING, "Error verifying user", e);
     return FAIL;
   }
 }
  protected GoogleDriveSession buildGoogleDriveSession() throws IOException, PortalException {

    long userId = PrincipalThreadLocal.getUserId();

    User user = UserLocalServiceUtil.getUser(userId);

    if (user.isDefaultUser()) {
      throw new PrincipalException("User is not authenticated");
    }

    GoogleCredential.Builder builder = new GoogleCredential.Builder();

    String googleClientId = PrefsPropsUtil.getString(user.getCompanyId(), "google-client-id");
    String googleClientSecret =
        PrefsPropsUtil.getString(user.getCompanyId(), "google-client-secret");

    builder.setClientSecrets(googleClientId, googleClientSecret);

    JacksonFactory jsonFactory = new JacksonFactory();

    builder.setJsonFactory(jsonFactory);

    HttpTransport httpTransport = new NetHttpTransport();

    builder.setTransport(httpTransport);

    GoogleCredential googleCredential = builder.build();

    ExpandoBridge expandoBridge = user.getExpandoBridge();

    String googleAccessToken =
        GetterUtil.getString(expandoBridge.getAttribute("googleAccessToken", false));

    googleCredential.setAccessToken(googleAccessToken);

    String googleRefreshToken =
        GetterUtil.getString(expandoBridge.getAttribute("googleRefreshToken", false));

    googleCredential.setRefreshToken(googleRefreshToken);

    Drive.Builder driveBuilder = new Drive.Builder(httpTransport, jsonFactory, googleCredential);

    Drive drive = driveBuilder.build();

    Drive.About driveAbout = drive.about();

    Drive.About.Get driveAboutGet = driveAbout.get();

    About about = driveAboutGet.execute();

    return new GoogleDriveSession(drive, about.getRootFolderId());
  }
  @Override
  public List<ExtRepositorySearchResult<?>> search(
      SearchContext searchContext, Query query, ExtRepositoryQueryMapper extRepositoryQueryMapper)
      throws PortalException {

    try {
      Drive drive = getDrive();

      Drive.Files driveFiles = drive.files();

      Drive.Files.List driveFilesList = driveFiles.list();

      String searchQuery =
          getSearchQuery(
              searchContext.getKeywords(), searchContext.getFolderIds(), extRepositoryQueryMapper);

      driveFilesList.setQ(searchQuery);

      FileList fileList = driveFilesList.execute();

      List<File> files = fileList.getItems();

      List<ExtRepositorySearchResult<?>> extRepositorySearchResults = new ArrayList<>(files.size());

      for (File file : files) {
        if (_FOLDER_MIME_TYPE.equals(file.getMimeType())) {
          GoogleDriveFolder googleDriveFolder = new GoogleDriveFolder(file, getRootFolderKey());

          ExtRepositorySearchResult<GoogleDriveFolder> extRepositorySearchResult =
              new ExtRepositorySearchResult<>(googleDriveFolder, 1.0f, StringPool.BLANK);

          extRepositorySearchResults.add(extRepositorySearchResult);
        } else {
          GoogleDriveFileEntry googleDriveFileEntry = new GoogleDriveFileEntry(file);

          ExtRepositorySearchResult<GoogleDriveFileEntry> extRepositorySearchResult =
              new ExtRepositorySearchResult<>(googleDriveFileEntry, 1.0f, StringPool.BLANK);

          extRepositorySearchResults.add(extRepositorySearchResult);
        }
      }

      return extRepositorySearchResults;
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
  private String getFileContents(Drive drive, String downloadUrl) {
    if (!TextUtils.isEmpty(downloadUrl)) {
      try {
        HttpResponse resp =
            drive.getRequestFactory().buildGetRequest(new GenericUrl(downloadUrl)).execute();

        final char[] buffer = new char[1024];
        final StringBuilder out = new StringBuilder();
        Reader in = null;
        try {
          in = new InputStreamReader(resp.getContent(), "UTF-8");
          for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0) break;
            out.append(buffer, 0, rsz);
          }
        } finally {
          in.close();
        }
        return out.toString();
      } catch (IOException e) {
        Log.e(getClass().getSimpleName(), "Error downloading file contenst", e);
      }
    }
    return null;
  }
Beispiel #13
0
  /**
   * Retrieve a collection of files that have changed since the provided {@code changeId}.
   *
   * @param changeId Change ID to retrieve changed files from.
   * @return Map of changed files key'ed by their file ID.
   */
  private Map<String, File> getChangedFiles(long changeId) {
    Map<String, File> result = new HashMap<String, File>();

    try {
      Changes.List request = mService.changes().list().setStartChangeId(changeId);
      do {
        ChangeList changes = request.execute();
        long largestChangeId = changes.getLargestChangeId().longValue();

        for (Change change : changes.getItems()) {
          if (change.getDeleted()) {
            result.put(change.getFileId(), null);
          } else if (TEXT_PLAIN.equals(change.getFile().getMimeType())) {
            result.put(change.getFileId(), change.getFile());
          }
        }

        if (largestChangeId > mLargestChangeId) {
          mLargestChangeId = largestChangeId;
        }
        request.setPageToken(changes.getNextPageToken());
      } while (request.getPageToken() != null && request.getPageToken().length() > 0);
    } catch (IOException e) {
      e.printStackTrace();
    }

    Log.d(TAG, "Got changed Drive files: " + result.size() + " - " + mLargestChangeId);
    return result;
  }
Beispiel #14
0
  /** Perform a synchronization for the current account. */
  public void performSync() {
    if (mService == null) {
      return;
    }

    Log.d(TAG, "Performing sync for " + mAccount.name);
    if (mLargestChangeId == -1) {
      // First time the sync adapter is run for the provided account.
      performFullSync();
    } else {
      Map<String, File> files = getChangedFiles(mLargestChangeId);
      Uri uri = getNotesUri(mAccount.name);

      try {
        Cursor cursor =
            mProvider.query(
                uri, PROJECTION, NotePad.Notes.COLUMN_NAME_FILE_ID + " IS NOT NULL", null, null);

        Log.d(TAG, "Got local files: " + cursor.getCount());
        for (boolean more = cursor.moveToFirst(); more; more = cursor.moveToNext()) {

          // Merge.
          String fileId = cursor.getString(COLUMN_INDEX_FILE_ID);
          Uri localFileUri = getFileUri(mAccount.name, fileId);

          Log.d(TAG, "Processing local file with drive ID: " + fileId);
          if (files.containsKey(fileId)) {
            File driveFile = files.get(fileId);
            if (driveFile != null) {
              // Merge the files.
              mergeFiles(localFileUri, cursor, driveFile);
            } else {
              Log.d(TAG, "  > Deleting local file: " + fileId);
              // The file does not exist in Drive anymore, delete it.
              mProvider.delete(localFileUri, null, null);
            }
            files.remove(fileId);
          } else {
            // The file has not been updated on Drive, eventually update the Drive file.
            File driveFile = mService.files().get(fileId).execute();
            mergeFiles(localFileUri, cursor, driveFile);
          }
          mContext.getContentResolver().notifyChange(localFileUri, null, false);
        }

        // Any remaining files in the map are files that do not exist in the local database.
        insertNewDriveFiles(files.values());
        storeLargestChangeId(mLargestChangeId + 1);
      } catch (IOException e) {
        e.printStackTrace();
      } catch (RemoteException e) {
        e.printStackTrace();
      }
    }

    // Insert new local files.
    insertNewLocalFiles();

    Log.d(TAG, "Done performing sync for " + mAccount.name);
  }
 private File createDirectory(File f) {
   try {
     return service.files().insert(f).execute();
   } catch (IOException e) {
     this.error = e;
     return f;
   }
 }
Beispiel #16
0
 @Override
 public File call() throws IOException {
   File copiedFile = new File();
   copiedFile.setTitle(targetName);
   copiedFile.setParents(Arrays.asList(new ParentReference().setId(targetParentId)));
   new OriginMD5ChecksumAccessor(copiedFile).set(getOriginMD5Checksum());
   return drive.files().copy(originFile.getId(), copiedFile).execute();
 }
  protected File addFile(
      String extRepositoryParentFolderKey,
      String mimeType,
      String title,
      String description,
      InputStream inputStream)
      throws PortalException {

    try {
      File file = new File();

      file.setDescription(description);
      file.setMimeType(mimeType);

      Drive drive = getDrive();

      Drive.Files driveFiles = drive.files();

      File extRepositoryParentFolderFile = getFile(drive, extRepositoryParentFolderKey);

      ParentReference parentReference = new ParentReference();

      parentReference.setId(extRepositoryParentFolderFile.getId());

      file.setParents(Arrays.asList(parentReference));

      file.setTitle(title);

      if (inputStream != null) {
        InputStreamContent inputStreamContent = new InputStreamContent(mimeType, inputStream);

        Drive.Files.Insert driveFilesInsert = driveFiles.insert(file, inputStreamContent);

        return driveFilesInsert.execute();
      } else {
        Drive.Files.Insert driveFilesInsert = driveFiles.insert(file);

        return driveFilesInsert.execute();
      }
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
  @Override
  public <T extends ExtRepositoryObject> T moveExtRepositoryObject(
      ExtRepositoryObjectType<T> extRepositoryObjectType,
      String extRepositoryObjectKey,
      String newExtRepositoryFolderKey,
      String newTitle)
      throws PortalException {

    try {
      Drive drive = getDrive();

      File file = getFile(drive, extRepositoryObjectKey);

      Drive.Parents driveParents = drive.parents();

      List<ParentReference> parentReferences = file.getParents();

      for (ParentReference parentReference : parentReferences) {
        Drive.Parents.Delete driveParentsDelete =
            driveParents.delete(file.getId(), parentReference.getId());

        driveParentsDelete.execute();
      }

      ParentReference parentReference = new ParentReference();

      parentReference.setId(newExtRepositoryFolderKey);

      Drive.Parents.Insert driveParentsInsert = driveParents.insert(file.getId(), parentReference);

      driveParentsInsert.execute();

      if (extRepositoryObjectType.equals(ExtRepositoryObjectType.FILE)) {
        return (T) new GoogleDriveFileEntry(file);
      }

      return (T) new GoogleDriveFolder(file, getRootFolderKey());
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
  @Test
  public void test() throws IOException {

    HttpTransport transport = injector.getInstance(HttpTransport.class);
    JsonFactory jsonFactory = injector.getInstance(JsonFactory.class);

    DriveManager drive =
        new DriveManager(
            transport, jsonFactory, GoogleOAuth2.getGlobalCredential(transport, jsonFactory));
    Drive service = drive.getClient();
    File file = service.files().get("1HyyFJfqms_ZII3kNHr9smIXFadMYNRQvXsOhLOsUhLg").execute();
    //		IOUtils.toString(downloadFile(service, file));
    String downloadUrl = file.getExportLinks().get("text/html");
    System.out.println(downloadUrl);

    HttpRequestFactory factory = transport.createRequestFactory();
    HttpRequest request = factory.buildGetRequest(new GenericUrl(downloadUrl));
    HttpResponse response = request.execute();
    System.out.println(IOUtils.toString(response.getContent()));
  }
  @Override
  public <T extends ExtRepositoryObject> T copyExtRepositoryObject(
      ExtRepositoryObjectType<T> extRepositoryObjectType,
      String extRepositoryFileEntryKey,
      String newExtRepositoryFolderKey,
      String newTitle)
      throws PortalException {

    try {
      Drive drive = getDrive();

      Drive.Files driveFiles = drive.files();

      File newFile = new File();

      ParentReference parentReference = new ParentReference();

      parentReference.setId(newExtRepositoryFolderKey);

      newFile.setParents(Arrays.asList(parentReference));

      Drive.Files.Copy driveFilesCopy = driveFiles.copy(extRepositoryFileEntryKey, newFile);

      driveFilesCopy.execute();

      T extRepositoryObject = null;

      if (extRepositoryObjectType.equals(ExtRepositoryObjectType.FOLDER)) {

        extRepositoryObject = (T) new GoogleDriveFolder(newFile, getRootFolderKey());
      } else {
        extRepositoryObject = (T) new GoogleDriveFileEntry(newFile);
      }

      return extRepositoryObject;
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
Beispiel #21
0
  /**
   * Removes old tracks created by MyTracks test.
   *
   * @param activity
   * @param accountName
   */
  public static void deleteTestTracksOnGoogleDrive(Activity activity, String accountName) {
    try {
      GoogleAccountCredential driveCredential =
          SendToGoogleUtils.getGoogleAccountCredential(
              activity.getApplicationContext(), accountName, SendToGoogleUtils.DRIVE_SCOPE);
      if (driveCredential == null) {
        return;
      }

      Drive drive = SyncUtils.getDriveService(driveCredential);
      com.google.api.services.drive.Drive.Files.List list =
          drive.files().list().setQ(TEST_TRACKS_QUERY);
      List<File> files = list.execute().getItems();
      for (Iterator<File> iterator = files.iterator(); iterator.hasNext(); ) {
        File file = (File) iterator.next();
        drive.files().delete(file.getId()).execute();
      }
    } catch (Exception e) {
      Log.e(EndToEndTestUtils.LOG_TAG, "Delete test tracks failed.");
    }
  }
Beispiel #22
0
 /** Performs a full sync, usually occurs the first time a sync occurs for the account. */
 private void performFullSync() {
   Log.d(TAG, "Performing first sync");
   Long largestChangeId = (long) -1;
   try {
     // Get the largest change Id first to avoid race conditions.
     About about = mService.about().get().setFields(ABOUT_GET_FIELDS).execute();
     largestChangeId = about.getLargestChangeId();
   } catch (IOException e) {
     e.printStackTrace();
   }
   storeAllDriveFiles();
   storeLargestChangeId(largestChangeId);
   Log.d(TAG, "Done performing first sync: " + largestChangeId);
 }
Beispiel #23
0
  private static Permission insertPermission(
      Drive service, String fileId, String value, String type, String role) {

    Permission newPermission = new Permission();

    newPermission.setValue(value);
    newPermission.setType(type);
    newPermission.setRole(role);
    try {
      return service.permissions().insert(fileId, newPermission).execute();
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
    }
    return null;
  }
  protected InputStream getContentStream(String downloadURL) throws PortalException {

    if (Validator.isNull(downloadURL)) {
      return null;
    }

    Drive drive = getDrive();

    HttpRequestFactory httpRequestFactory = drive.getRequestFactory();

    GenericUrl genericUrl = new GenericUrl(downloadURL);

    try {
      HttpRequest httpRequest = httpRequestFactory.buildGetRequest(genericUrl);

      HttpResponse httpResponse = httpRequest.execute();

      return httpResponse.getContent();
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
  @Override
  public void deleteExtRepositoryObject(
      ExtRepositoryObjectType<? extends ExtRepositoryObject> extRepositoryObjectType,
      String extRepositoryObjectKey)
      throws PortalException {

    try {
      Drive drive = getDrive();

      Drive.Files driveFiles = drive.files();

      Drive.Files.Delete driveFilesDelete = driveFiles.delete(extRepositoryObjectKey);

      driveFilesDelete.execute();

      GoogleDriveCache googleDriveCache = GoogleDriveCache.getInstance();

      googleDriveCache.remove(extRepositoryObjectKey);
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
Beispiel #26
0
  /**
   * Searches docs in user's Google Documents.
   *
   * @param title the title of doc
   * @param activity to get context
   * @param accountName the name of Google account
   * @return the file list of the document, null means can not find the spreadsheets
   */
  public static List<File> searchAllSpreadsheetByTitle(
      String title, Activity activity, String accountName) {
    try {
      GoogleAccountCredential driveCredential =
          SendToGoogleUtils.getGoogleAccountCredential(
              activity.getApplicationContext(), accountName, SendToGoogleUtils.DRIVE_SCOPE);
      if (driveCredential == null) {
        return null;
      }

      Drive drive = SyncUtils.getDriveService(driveCredential);
      com.google.api.services.drive.Drive.Files.List list =
          drive
              .files()
              .list()
              .setQ(
                  String.format(Locale.US, SendSpreadsheetsAsyncTask.GET_SPREADSHEET_QUERY, title));
      FileList result = list.execute();
      return result.getItems();
    } catch (Exception e) {
      Log.e(EndToEndTestUtils.LOG_TAG, "Search spreadsheet failed.");
    }
    return null;
  }
Beispiel #27
0
  /**
   * Store all text/plain files from Drive that the app has access to. This is called the first time
   * the app synchronize the database with Google Drive for the current user.
   */
  private void storeAllDriveFiles() {
    try {
      Files.List request = mService.files().list().setQ("mimeType = '" + TEXT_PLAIN + "'");
      Map<String, File> textFiles = new HashMap<String, File>();

      do {
        try {
          FileList files = request.execute();

          for (File file : files.getItems()) {
            textFiles.put(file.getId(), file);
          }
          request.setPageToken(files.getNextPageToken());
        } catch (IOException e) {
          System.out.println("An error occurred: " + e);
          request.setPageToken(null);
        }
      } while (request.getPageToken() != null && request.getPageToken().length() > 0);

      // Merge with files that are already in the database.
      try {
        Uri uri = getNotesUri(mAccount.name);
        Cursor cursor =
            mProvider.query(
                uri, PROJECTION, NotePad.Notes.COLUMN_NAME_FILE_ID + " IS NOT NULL", null, null);

        if (cursor.moveToFirst()) {
          do {
            String fileId = cursor.getString(COLUMN_INDEX_FILE_ID);

            if (textFiles.containsKey(fileId)) {
              Uri localFileUri = getNoteUri(mAccount.name, cursor.getString(COLUMN_INDEX_ID));
              mergeFiles(localFileUri, cursor, textFiles.get(fileId));
              textFiles.remove(fileId);
            }
          } while (cursor.moveToNext());
        }
      } catch (RemoteException e) {
        e.printStackTrace();
      }

      insertNewDriveFiles(textFiles.values());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Returns a list of changes to a file
   *
   * @param service Drive API service instance.
   * @param params HashMap containing parameters for the request
   * @return <strong>List</strong> of changes
   */
  private ChangeList getChangeList(Drive service, HashMap<String, String> params)
      throws IOException {

    Changes.List request = service.changes().list();
    String temporaryResult = params.get(GoogleDriveUtils.StringConstants.INCLUDE_DELETED);

    if (!EMPTY_STRING.equals(temporaryResult)) {

      request.setIncludeDeleted(Boolean.valueOf(temporaryResult));
    }

    temporaryResult = EMPTY_STRING;
    temporaryResult = params.get(GoogleDriveUtils.StringConstants.INCLUDE_SUBSCRIBED);

    if (!EMPTY_STRING.equals(temporaryResult)) {

      request.setIncludeSubscribed(Boolean.valueOf(temporaryResult));
    }

    temporaryResult = EMPTY_STRING;
    temporaryResult = params.get(GoogleDriveUtils.StringConstants.MAX_RESULTS);

    if (!EMPTY_STRING.equals(temporaryResult)) {

      request.setMaxResults(Integer.valueOf(temporaryResult));
    }

    temporaryResult = EMPTY_STRING;
    temporaryResult = params.get(GoogleDriveUtils.StringConstants.PAGE_TOKEN);

    if (!EMPTY_STRING.equals(temporaryResult)) {

      request.setPageToken(temporaryResult);
    }

    temporaryResult = EMPTY_STRING;
    temporaryResult = params.get(GoogleDriveUtils.StringConstants.START_CHANGE_ID);

    if (!EMPTY_STRING.equals(temporaryResult)) {

      request.setStartChangeId(Long.valueOf(temporaryResult));
    }

    return request.execute();
  }
  protected File getFile(Drive drive, String extRepositoryObjectKey) throws IOException {

    GoogleDriveCache googleDriveCache = GoogleDriveCache.getInstance();

    File file = googleDriveCache.get(extRepositoryObjectKey);

    if (file == null) {
      Drive.Files driveFiles = drive.files();

      Drive.Files.Get driveFilesGet = driveFiles.get(extRepositoryObjectKey);

      file = driveFilesGet.execute();

      googleDriveCache.put(file);
    }

    return file;
  }
Beispiel #30
0
  private static String createFolderWithParentAndTitle(String parentID, String title) {
    String folderMIME = "application/vnd.google-apps.folder";

    File newFolder =
        new File()
            .setTitle(title)
            .setParents(Arrays.asList(new ParentReference().setId(parentID)))
            .setMimeType(folderMIME);

    File returned = null;
    try {
      returned = service.files().insert(newFolder).execute();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    if (returned != null) return returned.getId();

    return null;
  }