Ejemplo n.º 1
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;
  }
Ejemplo n.º 2
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();
    }
  }
Ejemplo n.º 3
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);
  }
Ejemplo n.º 4
0
  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);
    }
  }
Ejemplo n.º 6
0
  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;
    }
  }
Ejemplo n.º 7
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();
 }
 private File createDirectory(File f) {
   try {
     return service.files().insert(f).execute();
   } catch (IOException e) {
     this.error = e;
     return f;
   }
 }
  @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);
    }
  }
Ejemplo n.º 10
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.");
    }
  }
  @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);
    }
  }
Ejemplo n.º 12
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();
    }
  }
  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);
    }
  }
  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;
  }
Ejemplo n.º 15
0
  @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);
    }
  }
Ejemplo n.º 17
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;
  }
  @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);
    }
  }
Ejemplo n.º 19
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;
  }
  private void syncNotes(final String syncAccountName, final String accessToken) {
    final Drive drive = getDriveService(syncAccountName, accessToken);
    ContentResolver cr = getContentResolver();
    try {
      // loop over saved files and add any new notes to drive
      Cursor savedNotes =
          cr.query(NotesProvider.CONTENT_URI, NotesSyncQuery.PROJECTION, null, null, null);
      if (savedNotes.moveToFirst()) {
        do {
          final String driveId = savedNotes.getString(NotesSyncQuery.DRIVE_ID);
          if (TextUtils.isEmpty(driveId)) {
            // exists locally but not in drive Ð upload it
            File newNote = new File();
            newNote.setTitle(savedNotes.getString(NotesSyncQuery.TITLE));
            newNote.setMimeType(NOTE_MIME_TYPE);

            File inserted =
                drive
                    .files()
                    .insert(
                        newNote,
                        ByteArrayContent.fromString(
                            NOTE_MIME_TYPE, savedNotes.getString(NotesSyncQuery.BODY)))
                    .execute();

            // save the drive id to the db
            ContentValues cv = new ContentValues();
            cv.put(NotesProvider.KEY_DRIVE_ID, inserted.getId());
            Uri noteUri =
                ContentUris.withAppendedId(
                    NotesProvider.CONTENT_URI, savedNotes.getLong(NotesSyncQuery.ID));
            cr.update(noteUri, cv, null, null);
          } else {
            // TODO compare timestamps etc.
          }
        } while (savedNotes.moveToNext());
      }

      // loop over all files in drive and see if any need to be
      // synced locally
      FileList driveFilesList = drive.files().list().execute();
      for (File remote : driveFilesList.getItems()) {
        if (remote.getLabels().getTrashed()) {
          // skip deleted files
          continue;
        }
        final String where = NotesProvider.KEY_DRIVE_ID + "=?";
        final String[] arguments = new String[] {remote.getId()};
        Cursor c =
            cr.query(
                NotesProvider.CONTENT_URI, NotesDownloadQuery.PROJECTION, where, arguments, null);
        if (c.getCount() == 0) {
          // exists in drive but not locally Ð download it
          final String title = remote.getTitle();
          final String body = getFileContents(drive, remote.getDownloadUrl());
          final ContentValues cv = new ContentValues();
          cv.put(NotesProvider.KEY_TITLE, title);
          cv.put(NotesProvider.KEY_BODY, body);
          cv.put(NotesProvider.KEY_DRIVE_ID, remote.getId());
          cv.put(NotesProvider.KEY_LAST_MODIFIED, remote.getModifiedDate().getValue());
          cr.insert(NotesProvider.CONTENT_URI, cv);
        } else {
          // TODO compare timestamps etc.
        }
      }

    } catch (IOException e) {
      // FIXME error handling
      Log.e(getClass().getSimpleName(), "Drive esplode", e);
    }
  }
Ejemplo n.º 21
0
  private static String determineParent(String email, String workflow) {
    String root = "0B7Jfx3RRVE5YenZEY1N5cE5pRms";
    String parentFolder = null;

    String level = root;
    String parent = root;
    boolean lowest = false;

    // Checks for user
    level = folderContains(email, level);
    if (level != null) {

      DateFormat today = new SimpleDateFormat("E, MM/dd/yyyy");
      Date now = new Date();
      String nowStr = today.format(now);

      // Checks for today's date
      parent = level;
      level = folderContains(nowStr, level);
      if (level != null) {

        // Checks for a workflowID folder
        parent = level;
        level = folderContains(workflow, level);
        // System.out.println("level: "+level);
        if (level != null) {

          // Finds the highest folder number; add 1 and creates it.
          try {
            File child = null;
            int lastRun = 0;
            int tmp = lastRun;
            ChildList children = service.children().list(level).execute();
            for (ChildReference element : children.getItems()) {
              child = service.files().get(element.getId()).execute();
              try {
                tmp = Integer.parseInt(child.getTitle());
                if (tmp > lastRun) {
                  lastRun = tmp;
                }
              } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
            }
            lastRun += 1;
            String next = new Integer(lastRun).toString();
            // System.out.println("level: "+level);
            // System.out.println("next: "+next);
            parentFolder = createFolderWithParentAndTitle(level, next);

          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

          } finally {
            lowest = true;
          }

        } else {
          parentFolder = createFolderWithParentAndTitle(parent, workflow);
        }
      } else {
        parentFolder = createFolderWithParentAndTitle(parent, nowStr);
      }
    } else {
      parentFolder = createFolderWithParentAndTitle(parent, email);
    }

    try {
      File file = service.files().get(parentFolder).execute();
      service.permissions().insert(file.getId(), perm).execute();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if (!lowest) parentFolder = determineParent(email, workflow);

    return parentFolder;
  }
Ejemplo n.º 22
0
  /**
   * Merge a local file with a Google Drive File.
   *
   * <p>The last modification is used to check which file to sync from. Then, the md5 checksum of
   * the file is used to check whether or not the file's content should be sync'ed.
   *
   * @param localFileUri Local file URI to save local changes against.
   * @param localFile Local file cursor to retrieve data from.
   * @param driveFile Google Drive file.
   */
  private void mergeFiles(Uri localFileUri, Cursor localFile, File driveFile) {
    long localFileModificationDate = localFile.getLong(COLUMN_INDEX_MODIFICATION_DATE);

    Log.d(
        TAG,
        "Modification dates: "
            + localFileModificationDate
            + " - "
            + driveFile.getModifiedDate().getValue());
    if (localFileModificationDate > driveFile.getModifiedDate().getValue()) {
      try {
        if (localFile.getShort(COLUMN_INDEX_DELETED) != 0) {
          Log.d(TAG, "  > Deleting Drive file.");
          mService.files().delete(driveFile.getId()).execute();
          mProvider.delete(localFileUri, null, null);
        } else {
          String localNote = localFile.getString(COLUMN_INDEX_NOTE);
          File updatedFile = null;

          // Update drive file.
          Log.d(TAG, "  > Updating Drive file.");
          driveFile.setTitle(localFile.getString(COLUMN_INDEX_TITLE));

          if (md5(localNote) != driveFile.getMd5Checksum()) {
            // Update both content and metadata.
            ByteArrayContent content = ByteArrayContent.fromString(TEXT_PLAIN, localNote);
            updatedFile = mService.files().update(driveFile.getId(), driveFile, content).execute();
          } else {
            // Only update the metadata.
            updatedFile = mService.files().update(driveFile.getId(), driveFile).execute();
          }

          ContentValues values = new ContentValues();
          values.put(
              NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE,
              updatedFile.getModifiedDate().getValue());
          mProvider.update(localFileUri, values, null, null);
        }
      } catch (IOException e) {
        e.printStackTrace();
      } catch (RemoteException e) {
        e.printStackTrace();
      }
    } else if (localFileModificationDate < driveFile.getModifiedDate().getValue()) {
      // Update local file.
      Log.d(TAG, "  > Updating local file.");
      ContentValues values = new ContentValues();
      values.put(NotePad.Notes.COLUMN_NAME_TITLE, driveFile.getTitle());
      values.put(
          NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, driveFile.getModifiedDate().getValue());
      // Only download the content if it has changed.
      if (md5(localFile.getString(COLUMN_INDEX_NOTE)) != driveFile.getMd5Checksum()) {
        values.put(NotePad.Notes.COLUMN_NAME_NOTE, getFileContent(driveFile));
      }
      try {
        mProvider.update(localFileUri, values, null, null);
      } catch (RemoteException e) {
        e.printStackTrace();
      }
    }
  }
  @Override
  public <T extends ExtRepositoryObject> List<T> getExtRepositoryObjects(
      ExtRepositoryObjectType<T> extRepositoryObjectType, String extRepositoryFolderKey)
      throws PortalException {

    try {
      Drive drive = getDrive();

      Drive.Files driveFiles = drive.files();

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

      StringBundler sb = new StringBundler();

      if (extRepositoryFolderKey != null) {
        sb.append("'");
        sb.append(extRepositoryFolderKey);
        sb.append("' in parents and ");
      }

      if (!extRepositoryObjectType.equals(ExtRepositoryObjectType.OBJECT)) {

        sb.append("mimeType");

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

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

        sb.append(_FOLDER_MIME_TYPE);
        sb.append("' and ");
      }

      sb.append("trashed = false");

      driveFilesList.setQ(sb.toString());

      FileList fileList = driveFilesList.execute();

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

      List<T> extRepositoryObjects = new ArrayList<>();

      GoogleDriveCache googleDriveCache = GoogleDriveCache.getInstance();

      for (File file : files) {
        if (_FOLDER_MIME_TYPE.equals(file.getMimeType())) {
          extRepositoryObjects.add((T) new GoogleDriveFolder(file, getRootFolderKey()));
        } else {
          extRepositoryObjects.add((T) new GoogleDriveFileEntry(file));
        }

        googleDriveCache.put(file);
      }

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

      throw new SystemException(ioe);
    }
  }