com.google.api.services.drive.model.FileList Java Examples

The following examples show how to use com.google.api.services.drive.model.FileList. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 7 votes vote down vote up
@Override
public String getRemoteExperimentLibraryFileId() throws IOException {
  FileList fileList =
      driveApi
          .files()
          .list()
          .setSpaces(APP_DATA_FOLDER)
          .setQ(EXPERIMENT_LIBRARY_QUERY)
          .execute();
  if (!fileList.getItems().isEmpty()) {
    File firstFile = fileList.getItems().get(0);
    if (firstFile != null) {
      return firstFile.getId();
    }
  }
  return null;
}
 
Example #2
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public List<File> listChildren(String parentId) {
	List<File> resultList = new LinkedList<File>();
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		Drive.Files.List request = drive.files().list().setFields("nextPageToken, files");
		request.setQ("trashed = false and '" + parentId + "' in parents");
		request.setPageSize(1000);
		LOGGER.log(Level.FINE, "Listing children of folder " + parentId + ".");
		do {
			FileList fileList = executeWithRetry(options, () -> request.execute());
			List<File> items = fileList.getFiles();
			resultList.addAll(items);
			request.setPageToken(fileList.getNextPageToken());
		} while (request.getPageToken() != null && request.getPageToken().length() > 0);
		if (LOGGER.isLoggable(Level.FINE)) {
			for (File file : resultList) {
				LOGGER.log(Level.FINE, "Child of " + parentId + ": " + file.getId() + ";" + file.getName() + ";" + file.getMimeType());
			}
		}
		removeDuplicates(resultList);
		return resultList;
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to execute list request: " + e.getMessage(), e);
	}
}
 
Example #3
Source File: GoogleDriveTestBaseRuntime.java    From components with Apache License 2.0 6 votes vote down vote up
protected FileList createFolderFileList(String folderId, boolean createDuplicate) {
    FileList fileList = new FileList();
    java.util.List<com.google.api.services.drive.model.File> files = new ArrayList<>();
    com.google.api.services.drive.model.File file = new com.google.api.services.drive.model.File();
    file.setId(folderId);
    files.add(file);
    //
    if (createDuplicate) {
        com.google.api.services.drive.model.File fileDup = new com.google.api.services.drive.model.File();
        fileDup.setId(folderId);
        files.add(fileDup);
    }
    fileList.setFiles(files);

    return fileList;
}
 
Example #4
Source File: GoogleDriveCreateRuntimeTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test(expected = ComponentException.class)
public void testManyResourcesMatching() throws Exception {
    FileList flA = new FileList();
    List<File> fs = new ArrayList<>();
    File fA = new File();
    fA.setId("A");
    fs.add(fA);
    File fAp = new File();
    fAp.setId("A");
    fs.add(fAp);
    flA.setFiles(fs);
    when(drive.files().list().setQ(eq(qA)).execute()).thenReturn(flA);

    properties.parentFolder.setValue("/A");
    testRuntime.initialize(container, properties);
    testRuntime.runAtDriver(container);
    fail("Should not be here");
}
 
Example #5
Source File: GoogleDriveUtils.java    From components with Apache License 2.0 6 votes vote down vote up
/**
 * @param sourceFolderId source folder ID
 * @param destinationFolderId folder ID where to copy the sourceFolderId's content
 * @param newName folder name to assign
 * @return created folder ID
 * @throws IOException when operation fails
 */
public String copyFolder(String sourceFolderId, String destinationFolderId, String newName) throws IOException {
    LOG.debug("[copyFolder] sourceFolderId: {}; destinationFolderId: {}; newName: {}", sourceFolderId, destinationFolderId,
            newName);
    // create a new folder
    String newFolderId = createFolder(destinationFolderId, newName);
    // Make a recursive copy of all files/folders inside the source folder
    String query = format(Q_IN_PARENTS, sourceFolderId) + Q_AND + Q_NOT_TRASHED;
    FileList originals = drive.files().list().setQ(query).execute();
    LOG.debug("[copyFolder] Searching for copy {}", query);
    for (File file : originals.getFiles()) {
        if (file.getMimeType().equals(MIME_TYPE_FOLDER)) {
            copyFolder(file.getId(), newFolderId, file.getName());
        } else {
            copyFile(file.getId(), newFolderId, file.getName(), false);
        }
    }

    return newFolderId;
}
 
Example #6
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public List<File> listChildren(String parentId) {
	List<File> resultList = new LinkedList<File>();
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		Drive.Files.List request = drive.files().list().setFields("nextPageToken, files");
		request.setQ("trashed = false and '" + parentId + "' in parents");
		request.setPageSize(1000);
		LOGGER.log(Level.FINE, "Listing children of folder " + parentId + ".");
		do {
			FileList fileList = executeWithRetry(options, () -> request.execute());
			List<File> items = fileList.getFiles();
			resultList.addAll(items);
			request.setPageToken(fileList.getNextPageToken());
		} while (request.getPageToken() != null && request.getPageToken().length() > 0);
		if (LOGGER.isLoggable(Level.FINE)) {
			for (File file : resultList) {
				LOGGER.log(Level.FINE, "Child of " + parentId + ": " + file.getId() + ";" + file.getName() + ";" + file.getMimeType());
			}
		}
		removeDuplicates(resultList);
		return resultList;
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to execute list request: " + e.getMessage(), e);
	}
}
 
Example #7
Source File: SyncAdapter.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all the files from a request.
 * 
 * @param request the request
 * @param excludeSharedWithMe true to exclude shared with me files
 * @return a map of file id to file
 */
private Map<String, File> getFiles(Files.List request, boolean excludeSharedWithMe)
    throws IOException {
  Map<String, File> idToFileMap = new HashMap<String, File>();
  do {
    FileList files = request.execute();

    for (File file : files.getItems()) {
      if (excludeSharedWithMe && file.getSharedWithMeDate() != null) {
        continue;
      }
      idToFileMap.put(file.getId(), file);
    }
    request.setPageToken(files.getNextPageToken());
  } while (request.getPageToken() != null && request.getPageToken().length() > 0);
  return idToFileMap;
}
 
Example #8
Source File: GoogleDriveGetRuntimeTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test(expected = ComponentException.class)
public void testManyFiles() throws Exception {
    FileList files = new FileList();
    List<File> fl = new ArrayList<>();
    File f1 = new File();
    fl.add(f1);
    File f2 = new File();
    fl.add(f2);
    files.setFiles(fl);
    String q1 = "name='A' and 'root' in parents and mimeType='application/vnd.google-apps.folder'";
    when(drive.files().list().setQ(q1).execute()).thenReturn(files);
    when(drive.files().list().setQ(any()).execute()).thenReturn(files);
    //
    properties.file.setValue("/A");
    testRuntime.initialize(container, properties);
    testRuntime.runAtDriver(container);
    fail("Should not be here");
}
 
Example #9
Source File: GoogleDriveTestBaseRuntime.java    From components with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    container = new DefaultComponentRuntimeContainerImpl() {

        @Override
        public String getCurrentComponentId() {
            return TEST_CONTAINER;
        }
    };
    //
    DATA_STORE_DIR = new File(getClass().getClassLoader().getResource("./").toURI().getPath());
    HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    //
    drive = mock(Drive.class, RETURNS_DEEP_STUBS);
    sourceOrSink = spy(GoogleDriveSourceOrSink.class);
    source = spy(GoogleDriveSource.class);
    sink = spy(GoogleDriveSink.class);
    doReturn(drive).when(sourceOrSink).getDriveService();
    doReturn(drive).when(source).getDriveService();
    doReturn(drive).when(sink).getDriveService();
    //
    emptyFileList = new FileList();
    emptyFileList.setFiles(new ArrayList<com.google.api.services.drive.model.File>());
}
 
Example #10
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@Override
public int getPackageVersion(String packageId) throws IOException {
  FileList files =
      driveApi
          .files()
          .list()
          .setQ("title = '" + VERSION_PROTO_FILE + "' and '" + packageId + "' in parents")
          .execute();
  if (!files.getItems().isEmpty()) {
    String fileId = files.getItems().get(0).getId();
    try {
      FileVersion version = downloadVersionProtoFile(fileId);
      return version.getVersion();
    } catch (IOException ioe) {
      // IO Exception. Don't sync this right now. We can try again in the future with no
      // consequences.
      return Integer.MAX_VALUE;
    }
  } else {
    // If there's no version info at all, it must have been uploaded before this CL. So it's
    // Version 1.
    return 1;
  }
}
 
Example #11
Source File: GoogleDrivePutRuntimeTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunAtDriverTooManyFiles() throws Exception {
    FileList hasfilelist = new FileList();
    List<File> hfiles = new ArrayList<>();
    File hfile = new File();
    hfile.setId(FILE_PUT_NAME);
    hfiles.add(hfile);
    hfiles.add(new File());
    hasfilelist.setFiles(hfiles);
    when(drive.files().list().setQ(anyString()).execute()).thenReturn(hasfilelist);
    properties.overwrite.setValue(true);
    testRuntime.initialize(container, properties);
    try {
        testRuntime.runAtDriver(container);
        fail("Should not be here");
    } catch (Exception e) {
    }
}
 
Example #12
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Long> getAllDriveExperimentVersions() throws IOException {
  FileList files =
      driveApi
          .files()
          .list()
          .setQ("title = '" + EXPERIMENT_PROTO_FILE + "'")
          .setFields("items(version,parents)")
          .execute();
  HashMap<String, Long> versionMap = new HashMap<>();
  if (!files.getItems().isEmpty()) {
    for (File f : files.getItems()) {
      versionMap.put(f.getParents().get(0).getId(), f.getVersion());
    }
  }
  return versionMap;
}
 
Example #13
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@Override
public java.io.File downloadExperimentAsset(
    String packageId, java.io.File experimentDirectory, String fileName) throws IOException {
  java.io.File outputFile = new java.io.File(experimentDirectory, fileName);
  outputFile.getParentFile().mkdirs();
  FileList files = getFileFromPackage(packageId, outputFile.getName());
  if (!files.getItems().isEmpty()) {
    if (files.getItems().size() > 1 && Log.isLoggable(TAG, Log.ERROR)) {
      Log.e(TAG, "More than one file found " + outputFile.getName());
    }
    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
      driveApi
          .files()
          .get(files.getItems().get(0).getId())
          .executeMediaAndDownloadTo(fos);
      fos.flush();
    }
  }
  return outputFile;
}
 
Example #14
Source File: BookmarkService.java    From drivemarks with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves or creates the folder with the given
 * name on the root level.
 * @param title
 * @return Retrieved or inserted folder.
 * @throws IOException
 */
public File createOrGetFolder(String title) throws IOException {
  Drive driveService = getDriveService();
  FileList list =
      driveService.files().list().setQ(QUERY_DRIVEMARKS_FOLDER).execute();
  File drivemarksDir = null;
  if (list == null || list.getItems().size() == 0) {
    // create directory
    File newDir = new File();
    newDir.setTitle(title);
    newDir.setMimeType(MIMETYPE_FOLDER);
    newDir.setParents(Arrays.asList(new ParentReference().setId("root")));
    drivemarksDir = driveService.files().insert(newDir).execute();
  } else {
    drivemarksDir = list.getItems().get(0);
  }
  return drivemarksDir;
}
 
Example #15
Source File: GpgsClient.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
/**
 * Blocking version of {@link #fetchGameStatesSync()}
 *
 * @return game states
 * @throws IOException
 */
public Array<String> fetchGameStatesSync() throws IOException {

    if (!driveApiEnabled)
        throw new UnsupportedOperationException();

    Array<String> games = new Array<String>();

    FileList l = GApiGateway.drive.files().list()
            .setSpaces("appDataFolder")
            .setFields("files(name)")
            .execute();

    for (File f : l.getFiles()) {
        games.add(f.getName());
    }

    return games;
}
 
Example #16
Source File: GoogleDrivePutRuntimeTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunAtDriverOverwrite() throws Exception {
    FileList hasfilelist = new FileList();
    List<File> hfiles = new ArrayList<>();
    File hfile = new File();
    hfile.setId(FILE_PUT_NAME);
    hfiles.add(hfile);
    hasfilelist.setFiles(hfiles);
    when(drive.files().list().setQ(anyString()).execute()).thenReturn(hasfilelist);
    properties.overwrite.setValue(true);
    testRuntime.initialize(container, properties);
    testRuntime.runAtDriver(container);
    assertNull(container.getComponentData(TEST_CONTAINER, getStudioName(GoogleDrivePutDefinition.RETURN_CONTENT)));
    assertEquals(PUT_FILE_ID,
            container.getComponentData(TEST_CONTAINER, getStudioName(GoogleDrivePutDefinition.RETURN_FILE_ID)));
    assertEquals(PUT_FILE_PARENT_ID,
            container.getComponentData(TEST_CONTAINER, getStudioName(GoogleDrivePutDefinition.RETURN_PARENT_FOLDER_ID)));
}
 
Example #17
Source File: GoogleDrivePutRuntimeTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunAtDriverOverwriteError() throws Exception {
    FileList hasfilelist = new FileList();
    List<File> hfiles = new ArrayList<>();
    File hfile = new File();
    hfile.setId(FILE_PUT_NAME);
    hfiles.add(hfile);
    hasfilelist.setFiles(hfiles);
    when(drive.files().list().setQ(anyString()).execute()).thenReturn(hasfilelist);
    properties.overwrite.setValue(false);
    testRuntime.initialize(container, properties);
    try {
        testRuntime.runAtDriver(container);
        fail("Should not be here");
    } catch (Exception e) {
    }
}
 
Example #18
Source File: GoogleDriveCopyReaderTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    super.setUp();

    properties = new GoogleDriveCopyProperties("test");
    properties.setupProperties();
    properties = (GoogleDriveCopyProperties) setupConnectionWithInstalledApplicationWithIdAndSecret(properties);
    //
    properties.copyMode.setValue(CopyMode.File);
    properties.source.setValue(FILE_COPY_NAME);
    properties.destinationFolder.setValue("/A");
    properties.newName.setValue("newName");
    // source fileName/folder
    File dest = new File();
    dest.setId(SOURCE_ID);
    FileList list = new FileList();
    List<File> files = new ArrayList<>();
    files.add(dest);
    list.setFiles(files);
    final String q1 = "name='A' and 'root' in parents and mimeType='application/vnd.google-apps.folder'";
    final String q2 = "name='" + FILE_COPY_NAME + "' and mimeType!='application/vnd.google-apps.folder'";

    when(drive.files().list().setQ(eq(q1)).execute()).thenReturn(list);
    when(drive.files().list().setQ(eq(q2)).execute()).thenReturn(list);

    // destination/copied
    File copiedFile = new File();
    copiedFile.setId(DESTINATION_ID);
    copiedFile.setParents(Collections.singletonList(SOURCE_ID));
    when(drive.files().copy(anyString(), any(File.class)).setFields(anyString()).execute()).thenReturn(copiedFile);

    File destFolder = new File();
    destFolder.setId(DESTINATION_ID);
    destFolder.setParents(Collections.singletonList(SOURCE_ID));
    when(drive.files().create(any(File.class)).setFields(anyString()).execute()).thenReturn(destFolder);
}
 
Example #19
Source File: GoogleDriveCreateRuntimeTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    super.setUp();

    properties = new GoogleDriveCreateProperties("test");
    properties.setupProperties();
    properties = (GoogleDriveCreateProperties) setupConnectionWithInstalledApplicationWithIdAndSecret(properties);
    //
    properties.parentFolder.setValue(FOLDER_ROOT);
    properties.newFolder.setValue(FOLDER_CREATE);

    testRuntime = spy(GoogleDriveCreateRuntime.class);
    doReturn(drive).when(testRuntime).getDriveService();
    File fc = new File();
    fc.setId(FOLDER_CREATE_ID);
    when(drive.files().create(any(File.class)).setFields(eq("id")).execute()).thenReturn(fc);
    //

    FileList flA = new FileList();
    List<File> fs = new ArrayList<>();
    File fA = new File();
    fA.setId("A");
    fs.add(fA);
    flA.setFiles(fs);
    when(drive.files().list().setQ(qA).execute()).thenReturn(flA);
    FileList flB = new FileList();
    List<File> fsA = new ArrayList<>();
    File fB = new File();
    fB.setId("B");
    fsA.add(fB);
    flB.setFiles(fsA);
    when(drive.files().list().setQ(qB).execute()).thenReturn(flB);
    FileList flC = new FileList();
    List<File> fsC = new ArrayList<>();
    File fC = new File();
    fC.setId("C");
    fsC.add(fC);
    flC.setFiles(fsC);
    when(drive.files().list().setQ(qC).execute()).thenReturn(flC);
}
 
Example #20
Source File: GoogleDriveFileObject.java    From hop with Apache License 2.0 5 votes vote down vote up
private File searchFile( String fileName, String parentId ) throws Exception {
  File file = null;
  StringBuffer fileQuery = new StringBuffer();
  fileQuery.append( "name = '" + fileName + "'" );
  if ( parentId != null ) {
    fileQuery.append( " and '" + parentId + "' in parents and trashed=false" );
  }
  FileList fileList = driveService.files().list().setQ( fileQuery.toString() ).execute();
  if ( !fileList.getFiles().isEmpty() ) {
    file = fileList.getFiles().get( 0 );
  }
  return file;
}
 
Example #21
Source File: GoogleDriveFsHelperTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public void testPagination() throws IOException, FileBasedHelperException {
  State state = new State();
  state.appendToSetProp(GoogleDriveFileSystem.PAGE_SIZE, Integer.toString(1));

  GoogleDriveFsHelper fsHelper = new GoogleDriveFsHelper(state, client, Closer.create());
  List listRequest = mock(List.class);
  when(files.list()).thenReturn(listRequest);
  when(listRequest.setPageSize(anyInt())).thenReturn(listRequest);
  when(listRequest.setFields(anyString())).thenReturn(listRequest);
  when(listRequest.setQ(anyString())).thenReturn(listRequest);
  when(listRequest.setPageToken(anyString())).thenReturn(listRequest);

  int paginatedCalls = 5;
  final MutableInt i = new MutableInt(paginatedCalls);
  final File file = new File();
  file.setId("testId");
  file.setModifiedTime(new DateTime(System.currentTimeMillis()));

  when(listRequest.execute()).thenAnswer(new Answer<FileList>() {

    @Override
    public FileList answer(InvocationOnMock invocation) throws Throwable {
      FileList fileList = new FileList();
      fileList.setFiles(ImmutableList.of(file));
      if (i.intValue() > 0) {
        fileList.setNextPageToken("token");
        i.decrement();
      }
      return fileList;
    }
  });

  fsHelper.ls("test");

  int expectedCalls = 1 + paginatedCalls;
  verify(listRequest, times(expectedCalls)).execute();
}
 
Example #22
Source File: GoogleDriveFileObject.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
protected String[] doListChildren() throws Exception {
  String[] children = null;
  if ( isFolder() ) {
    id = id == null ? "root" : id;
    String fileQuery = "'" + id + "' in parents and trashed=false";
    FileList files = driveService.files().list().setQ( fileQuery ).execute();
    List<String> fileNames = new ArrayList<String>();
    for ( File file : files.getFiles() ) {
      fileNames.add( file.getName() );
    }
    children = fileNames.toArray( new String[0] );
  }
  return children;
}
 
Example #23
Source File: GoogleDriveFileObject.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private File searchFile( String fileName, String parentId ) throws Exception {
  File file = null;
  StringBuffer fileQuery = new StringBuffer();
  fileQuery.append( "name = '" + fileName + "'" );
  if ( parentId != null ) {
    fileQuery.append( " and '" + parentId + "' in parents and trashed=false" );
  }
  FileList fileList = driveService.files().list().setQ( fileQuery.toString() ).execute();
  if ( !fileList.getFiles().isEmpty() ) {
    file = fileList.getFiles().get( 0 );
  }
  return file;
}
 
Example #24
Source File: GoogleDriveListReaderTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdvance() throws Exception {
    FileList fileList = new FileList();
    for (int i = 0; i < 5; i++) {
        File f = new File();
        f.setName("sd" + i);
        f.setMimeType("text/text");
        f.setId("id-" + i);
        f.setModifiedTime(com.google.api.client.util.DateTime.parseRfc3339("2017-09-29T10:00:00"));
        f.setSize(100L);
        f.setKind("drive#fileName");
        f.setTrashed(false);
        f.setParents(Collections.singletonList(FOLDER_ROOT));
        f.setWebViewLink("https://toto.com");
        fileList.setFiles(Arrays.asList(f));
    }
    when(mockList.execute()).thenReturn(fileList);
    //
    properties.folder.setValue("A");
    source.initialize(container, properties);
    GoogleDriveListReader reader = ((GoogleDriveListReader) source.createReader(container));
    assertTrue(reader.start());
    while (reader.advance()) {
        assertNotNull(reader.getCurrent());
    }
    reader.close();
}
 
Example #25
Source File: GoogleDriveListReaderTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartOnly() throws Exception {
    FileList fileList = new FileList();
    File f = new File();
    f.setName("sd");
    f.setMimeType("text/text");
    f.setId("id-1");
    f.setModifiedTime(com.google.api.client.util.DateTime.parseRfc3339("2017-09-29T10:00:00"));
    f.setSize(100L);
    f.setKind("drive#fileName");
    f.setTrashed(false);
    f.setParents(Collections.singletonList(FOLDER_ROOT));
    f.setWebViewLink("https://toto.com");
    fileList.setFiles(Arrays.asList(f));

    when(mockList.execute()).thenReturn(fileList);
    //
    source.initialize(container, properties);
    GoogleDriveListReader reader = ((GoogleDriveListReader) source.createReader(container));
    assertTrue(reader.start());
    IndexedRecord record = (IndexedRecord) reader.getCurrent();
    assertNotNull(record);
    assertEquals(9, record.getSchema().getFields().size());
    assertEquals("id-1", record.get(0));
    assertEquals("sd", record.get(1));
    assertFalse(reader.advance());
    reader.close();
}
 
Example #26
Source File: GoogleDriveAbstractListReader.java    From components with Apache License 2.0 5 votes vote down vote up
private boolean processFolder() throws IOException {
    if (folderId == null && !subFolders.isEmpty()) {
        folderId = subFolders.get(0);
        subFolders.remove(0);
        request.setQ(format(query, folderId));
        LOG.debug("query = {} {}.", query, folderId);
    }
    searchResults.clear();
    FileList files = request.execute();
    for (File file : files.getFiles()) {
        if (canAddSubFolder(file.getMimeType())) {
            subFolders.add(file.getId());
        }
        if (canAddFile(file.getMimeType())) {
            searchResults.add(file);
            result.totalCount++;
        }
    }
    request.setPageToken(files.getNextPageToken());
    searchCount = searchResults.size();
    // finished for folderId
    if (StringUtils.isEmpty(request.getPageToken()) || searchCount == 0) {
        folderId = null;
    }

    return searchCount > 0;
}
 
Example #27
Source File: GoogleDriveUtils.java    From components with Apache License 2.0 5 votes vote down vote up
public File putResource(GoogleDrivePutParameters parameters) throws IOException {
    String folderId = parameters.getDestinationFolderId();
    File putFile = new File();
    putFile.setParents(Collections.singletonList(folderId));
    Files.List fileRequest = drive.files().list()
            .setQ(format(QUERY_NOTTRASHED_NAME_NOTMIME_INPARENTS, parameters.getResourceName(), MIME_TYPE_FOLDER, folderId));
    LOG.debug("[putResource] `{}` Exists in `{}` ? with `{}`.", parameters.getResourceName(),
            parameters.getDestinationFolderId(), fileRequest.getQ());
    FileList existingFiles = fileRequest.execute();
    if (existingFiles.getFiles().size() > 1) {
        throw new IOException(messages.getMessage("error.file.more.than.one", parameters.getResourceName()));
    }
    if (existingFiles.getFiles().size() == 1) {
        if (!parameters.isOverwriteIfExist()) {
            throw new IOException(messages.getMessage("error.file.already.exist", parameters.getResourceName()));
        }
        LOG.debug("[putResource] {} will be overwritten...", parameters.getResourceName());
        drive.files().delete(existingFiles.getFiles().get(0).getId()).execute();
    }
    putFile.setName(parameters.getResourceName());
    String metadata = "id,parents,name";
    if (!StringUtils.isEmpty(parameters.getFromLocalFilePath())) {
        // Reading content from local fileName
        FileContent fContent = new FileContent(null, new java.io.File(parameters.getFromLocalFilePath()));
        putFile = drive.files().create(putFile, fContent).setFields(metadata).execute();
        //

    } else if (parameters.getFromBytes() != null) {
        AbstractInputStreamContent content = new ByteArrayContent(null, parameters.getFromBytes());
        putFile = drive.files().create(putFile, content).setFields(metadata).execute();
    }
    return putFile;
}
 
Example #28
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Override
public int countSJExperiments() throws IOException {
  FileList files =
      driveApi
          .files()
          .list()
          .setQ("title = '" + EXPERIMENT_PROTO_FILE + "'")
          .execute();
  return files.getItems().size();
}
 
Example #29
Source File: GoogleDriveFileObject.java    From hop with Apache License 2.0 5 votes vote down vote up
protected String[] doListChildren() throws Exception {
  String[] children = null;
  if ( isFolder() ) {
    id = id == null ? "root" : id;
    String fileQuery = "'" + id + "' in parents and trashed=false";
    FileList files = driveService.files().list().setQ( fileQuery ).execute();
    List<String> fileNames = new ArrayList<String>();
    for ( File file : files.getFiles() ) {
      fileNames.add( file.getName() );
    }
    children = fileNames.toArray( new String[0] );
  }
  return children;
}
 
Example #30
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 5 votes vote down vote up
private FileList getFileFromPackage(String packageId, String fileName) throws IOException {
  return driveApi
      .files()
      .list()
      .setQ("title = '" + fileName + "' and '" + packageId + "' in parents")
      .execute();
}