示例#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;
  }
示例#2
0
  /**
   * Insert new Google Drive files in the local database.
   *
   * @param driveFiles Collection of Google Drive files to insert.
   */
  private void insertNewDriveFiles(Collection<File> driveFiles) {
    Uri uri = getNotesUri(mAccount.name);

    Log.d(TAG, "Inserting new Drive files: " + driveFiles.size());

    for (File driveFile : driveFiles) {
      if (driveFile != null) {
        ContentValues values = new ContentValues();
        values.put(NotePad.Notes.COLUMN_NAME_ACCOUNT, mAccount.name);
        values.put(NotePad.Notes.COLUMN_NAME_FILE_ID, driveFile.getId());
        values.put(NotePad.Notes.COLUMN_NAME_TITLE, driveFile.getTitle());
        values.put(NotePad.Notes.COLUMN_NAME_NOTE, getFileContent(driveFile));
        values.put(NotePad.Notes.COLUMN_NAME_CREATE_DATE, driveFile.getCreatedDate().getValue());
        values.put(
            NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, driveFile.getModifiedDate().getValue());
        try {
          mProvider.insert(uri, values);
        } catch (RemoteException e) {
          e.printStackTrace();
        }
      }
    }

    mContext.getContentResolver().notifyChange(uri, null, false);
  }
示例#3
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;
  }
示例#4
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();
 }
示例#5
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;
    }
  }
  @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 InputStream downloadFile(String fileName) throws IOException {
    File file = DriveUtil.getFileByName(fileName);

    if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0)
      try {
        fileSize = file.getFileSize();
        return DriveUtil.service.files().get(file.getId()).executeMediaAsInputStream();
      } catch (IOException e) {
        e.printStackTrace();
        MAMUtil.writeLog(e);
        return null;
      }

    return null;
  }
示例#8
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();
    }
  }
  @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);
    }
  }
示例#10
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);
    }
  }
示例#12
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.");
    }
  }
示例#13
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;
  }
示例#14
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();
    }
  }
示例#15
0
  /**
   * Retrieve a Google Drive file's content.
   *
   * @param driveFile Google Drive file to retrieve content from.
   * @return Google Drive file's content if successful, {@code null} otherwise.
   */
  public String getFileContent(File driveFile) {
    String result = "";

    if (driveFile.getDownloadUrl() != null && driveFile.getDownloadUrl().length() > 0) {
      try {
        GenericUrl downloadUrl = new GenericUrl(driveFile.getDownloadUrl());

        HttpResponse resp = mService.getRequestFactory().buildGetRequest(downloadUrl).execute();
        InputStream inputStream = null;

        try {
          inputStream = resp.getContent();
          BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
          StringBuilder content = new StringBuilder();
          char[] buffer = new char[1024];
          int num;

          while ((num = reader.read(buffer)) > 0) {
            content.append(buffer, 0, num);
          }
          result = content.toString();
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
        }
      } catch (IOException e) {
        // An error occurred.
        e.printStackTrace();
        return null;
      }
    } else {
      // The file doesn't have any content stored on Drive.
      return null;
    }

    return result;
  }
  @Override
  public ExtRepositoryFolder getExtRepositoryParentFolder(ExtRepositoryObject extRepositoryObject)
      throws PortalException {

    try {
      Drive drive = getDrive();

      File file = getFile(drive, extRepositoryObject.getExtRepositoryModelKey());

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

      if (!parentReferences.isEmpty()) {
        ParentReference parentReference = parentReferences.get(0);

        File parentFile = getFile(drive, parentReference.getId());

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

    return null;
  }
  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);
    }
  }
  private void synchronize(ChangeRecord record) throws IOException {
    try {
      switch (record.getOperation()) {
        case LOCAL_INSERT:
          {
            // Get remote id for the parent folder
            File local = DriveUtils.absolutePath(record.getLocalFile());
            String remoteParent =
                stub.storage().localToRemote().get(DriveUtils.relativePath(local.getParentFile()));
            if (!StringUtils.isEmpty(remoteParent)
                && !stub.storage().localToRemote().containsKey(record.getLocalFile())) {
              // Ignore insert request that doesn't have a parent or
              // already have a mapping.
              // The insert operation will be accomplished by the topmost
              // folder
              String remoteId = stub.transmit().upload(remoteParent, local);
              record.setRemoteFileId(remoteId);
            }
            break;
          }
        case LOCAL_DELETE:
          {
            if (!StringUtils.isEmpty(record.getRemoteFileId())) {
              stub.transmit().delete(record.getRemoteFileId());
            } else {
              logger.warn(
                  "Local deletion has no remote reference, make sure the storage is correct.");
            }
            break;
          }
        case LOCAL_CHANGE:
          {
            if (!StringUtils.isEmpty(record.getRemoteFileId())) {
              File local = DriveUtils.absolutePath(record.getLocalFile());
              stub.transmit().update(record.getRemoteFileId(), local);
            } else {
              logger.warn(
                  "Local change has no remote reference, make sure the storage is correct.");
              logger.warn("Trying to insert the new record");
              // Modify it to a local insert
              record.setOperation(Operation.LOCAL_INSERT);
              synchronize(record);
            }
            break;
          }
        case LOCAL_RENAME:
          {
            if (!StringUtils.isEmpty(record.getRemoteFileId())) {
              stub.transmit().rename(record.getRemoteFileId(), (String) record.getContext()[0]);
            } else {
              logger.warn(
                  "Local rename has no remote reference, make sure the storage is correct.");
              logger.warn("Trying to insert the new record");
              // Modify it to be a local insert
              record.setOperation(Operation.LOCAL_INSERT);
              synchronize(record);
            }
            break;
          }
        case REMOTE_INSERT:
          {
            if (stub.storage().remoteToLocal().containsKey(record.getRemoteFileId())) {
              // This file/folder already had been created
              break;
            }
            com.google.api.services.drive.model.File file = record.getContext(0);

            // Depth search of parent that has a local root
            List<ParentReference> path = new ArrayList<ParentReference>();
            File local = pathToLocal(record.getRemoteFileId(), path);
            if (null == local) {
              // Check whether this file is trashed
              if (file.getLabels().getTrashed()) {
                return;
              }
              if (file.getShared()) {
                return;
              } else {
                throw new IllegalArgumentException("Non-trash file has no known parent");
              }
            }
            File parent = local;
            for (ParentReference node : path) {
              stub.transmit().download(node.getId(), parent);
              parent = DriveUtils.absolutePath(stub.storage().remoteToLocal().get(node.getId()));
            }
            stub.transmit().download(record.getRemoteFileId(), parent);
            record.setLocalFile(stub.storage().remoteToLocal().get(record.getRemoteFileId()));
            if (StringUtils.isEmpty(record.getLocalFile())) {
              break;
            }
            break;
          }
        case REMOTE_DELETE:
          {
            if (StringUtils.isEmpty(record.getLocalFile())) {
              // No local file, remote file should be a trashed one.
              if (logger.isDebugEnabled()) {
                logger.debug(
                    "No corresponding local file for deletion. Remote file may be trashed");
              }
              break;
            }
            File localFile = DriveUtils.absolutePath(record.getLocalFile());
            String localParent = DriveUtils.relativePath(localFile.getParentFile());
            // Preserve the original context
            record.setContext(new Object[] {record.getContext(0), localParent});
            deleteLocalFile(localFile);
            if (localFile.exists()) {
              if (logger.isDebugEnabled()) {
                logger.debug(
                    MessageFormat.format(
                        "Failed to delete file {0}. File may have been deleted.",
                        record.getLocalFile()));
              }
            }
            stub.storage().localToRemote().remove(record.getLocalFile());
            stub.storage().remoteToLocal().remove(record.getRemoteFileId());
            break;
          }
        case REMOTE_CHANGE:
          {
            File local = DriveUtils.absolutePath(record.getLocalFile());
            File localParent = local.getParentFile();
            com.google.api.services.drive.model.File remote = record.getContext(0);

            if (!remote.getTitle().equals(local.getName())) {
              local.delete();
              stub.storage().localToRemote().remove(record.getLocalFile());
              stub.storage().remoteToLocal().remove(record.getRemoteFileId());
            }
            stub.transmit().download(record.getRemoteFileId(), localParent);
            break;
          }
        case REMOTE_RENAME:
          {
            File local = DriveUtils.absolutePath(record.getLocalFile());
            com.google.api.services.drive.model.File remote = record.getContext(0);
            String remoteName = remote.getTitle();
            File newName =
                new File(local.getParentFile().getAbsolutePath() + File.separator + remoteName);
            String relNewName = DriveUtils.relativePath(newName);
            record.setContext(new Object[] {record.getContext()[0], relNewName});
            local.renameTo(newName);
            stub.storage()
                .remoteToLocal()
                .put(record.getRemoteFileId(), DriveUtils.relativePath(newName));
            stub.storage().localToRemote().remove(DriveUtils.relativePath(local));
            stub.storage()
                .localToRemote()
                .put(DriveUtils.relativePath(newName), record.getRemoteFileId());
            break;
          }
      }
    } catch (Exception e) {
      logger.warn(MessageFormat.format("Exception on Change {0}. Retry later", record), e);
      FailedRecord fr = new FailedRecord(record);
      if (e instanceof GoogleJsonResponseException) {
        GoogleJsonResponseException gjre = (GoogleJsonResponseException) e;
        fr.setError(String.valueOf(gjre.getDetails().getCode()));
      } else {
        fr.setError(e.getMessage());
      }
      stub.storage().failedLog().add(fr);
    }
  }
  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);
    }
  }
示例#20
0
 @Override
 public int compare(File o1, File o2) {
   String i1 = o1.getId();
   String i2 = o2.getId();
   return i1.compareToIgnoreCase(i2);
 }
示例#21
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);
    }
  }
示例#23
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;
  }
  private void addToSnapshot(Snapshot root, ChangeRecord remoteChange) {
    switch (remoteChange.getOperation()) {
      case REMOTE_INSERT:
        String localName = stub.storage().remoteToLocal().get(remoteChange.getRemoteFileId());
        if (StringUtils.isEmpty(localName)) {
          // Insert failed
          return;
        }
        File localFile = DriveUtils.absolutePath(localName);
        String parent = DriveUtils.relativePath(localFile.getParentFile());
        if (root.getName().equals(parent)) {
          for (Snapshot sn : root.getChildren()) {
            if (sn.getName().equals(localName)) return;
          }
          Snapshot sn = stub.snapshot().make(localFile);
          root.addChild(sn);
        } else {
          for (Snapshot sn : root.getChildren()) {
            if (parent.startsWith(sn.getName())) {
              addToSnapshot(sn, remoteChange);
              return;
            }
          }
          // TODO the operations are not in sequence.
          // Didn't find?
          logger.warn(
              MessageFormat.format("Remote insert cannot find local parent {0}", remoteChange));
          // throw new IllegalArgumentException();
        }
        break;
      case REMOTE_CHANGE:
        {
          String fileName = remoteChange.getLocalFile();
          if (fileName.equals(root.getName())) {
            com.google.api.services.drive.model.File remoteFile = remoteChange.getContext(0);
            root.setMd5Checksum(remoteFile.getMd5Checksum());
          } else {
            for (Snapshot sn : root.getChildren()) {
              if (fileName.startsWith(sn.getName())) {
                addToSnapshot(sn, remoteChange);
                return;
              }
            }
            // Didn't find?
            logger.error(
                MessageFormat.format(
                    "Local root doesn't contain this file {0}. Should be an error.", remoteChange));
            // throw new IllegalArgumentException();
          }
          break;
        }
      case REMOTE_RENAME:
        {
          String fileName = remoteChange.getLocalFile();

          if (root.getName().startsWith(fileName)) {
            String newName = remoteChange.getContext(1);
            root.setName(root.getName().replaceFirst(fileName, newName));
            for (Snapshot sn : root.getChildren()) {
              addToSnapshot(sn, remoteChange);
            }
          } else {
            for (Snapshot sn : root.getChildren()) {
              if (fileName.startsWith(sn.getName())) {
                addToSnapshot(sn, remoteChange);
                return;
              }
            }
            // Didn't find?
            logger.error(
                MessageFormat.format(
                    "Remote rename cannot find local corresponding {0}, should be an error",
                    remoteChange));
            // throw new IllegalArgumentException();
          }
          break;
        }
      case REMOTE_DELETE:
        String fileName = remoteChange.getLocalFile();
        if (StringUtils.isEmpty(fileName)) {
          return;
        }
        for (int i = 0; i < root.getChildren().size(); i++) {
          Snapshot sn = root.getChildren().get(i);
          if (fileName.equals(sn.getName())) {
            root.getChildren().remove(sn);
            return;
          }
          if (fileName.startsWith(sn.getName())) {
            addToSnapshot(sn, remoteChange);
            return;
          }
        }
        // Didn't find?
        logger.warn(
            MessageFormat.format(
                "Remote change cannot find local corresponding {0}, possibly caused by deleting of parent folder",
                remoteChange));
        // This means the remote change is out of date
        break;
      default:
        throw new IllegalArgumentException();
    }
  }