Java Code Examples for com.google.api.services.drive.model.File#setModifiedTime()

The following examples show how to use com.google.api.services.drive.model.File#setModifiedTime() . 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: DriveImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String importSingleFile(
    UUID jobId, Drive driveInterface, DigitalDocumentWrapper file, String parentId)
    throws IOException {
  InputStreamContent content =
      new InputStreamContent(
          null, jobStore.getStream(jobId, file.getCachedContentId()).getStream());
  DtpDigitalDocument dtpDigitalDocument = file.getDtpDigitalDocument();
  File driveFile = new File().setName(dtpDigitalDocument.getName());
  if (!Strings.isNullOrEmpty(parentId)) {
    driveFile.setParents(ImmutableList.of(parentId));
  }
  if (!Strings.isNullOrEmpty(dtpDigitalDocument.getDateModified())) {
    driveFile.setModifiedTime(DateTime.parseRfc3339(dtpDigitalDocument.getDateModified()));
  }
  if (!Strings.isNullOrEmpty(file.getOriginalEncodingFormat())
      && file.getOriginalEncodingFormat().startsWith("application/vnd.google-apps.")) {
    driveFile.setMimeType(file.getOriginalEncodingFormat());
  }
  return driveInterface.files().create(driveFile, content).execute().getId();
}
 
Example 2
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateFile(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.INFO, "Updating file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), remoteFile, new FileContent(determineMimeType(localFile), localFile));
			//updateRequest.setModifiedDate(true);
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example 3
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateMetadata(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.FINE, "Updating metadata of remote file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			File newRemoteFile = new File();
			newRemoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), newRemoteFile).setFields("modifiedTime");
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example 4
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void store(SyncDirectory syncDirectory) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncDirectory.getLocalFile().get();
		File remoteFile = new File();
		remoteFile.setName(localFile.getName());
		remoteFile.setMimeType(MIME_TYPE_FOLDER);
		remoteFile.setParents(createParentReferenceList(syncDirectory));
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		LOGGER.log(Level.FINE, "Inserting new directory '" + syncDirectory.getPath() + "'.");
		if (!options.isDryRun()) {
			File insertedFile = executeWithRetry(options, () -> drive.files().create(remoteFile).execute());
			syncDirectory.setRemoteFile(Optional.of(insertedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example 5
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateFile(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.INFO, "Updating file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), remoteFile, new FileContent(determineMimeType(localFile), localFile));
			//updateRequest.setModifiedDate(true);
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example 6
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateMetadata(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.FINE, "Updating metadata of remote file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			File newRemoteFile = new File();
			newRemoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), newRemoteFile).setFields("modifiedTime");
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example 7
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void store(SyncDirectory syncDirectory) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncDirectory.getLocalFile().get();
		File remoteFile = new File();
		remoteFile.setName(localFile.getName());
		remoteFile.setMimeType(MIME_TYPE_FOLDER);
		remoteFile.setParents(createParentReferenceList(syncDirectory));
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		LOGGER.log(Level.FINE, "Inserting new directory '" + syncDirectory.getPath() + "'.");
		if (!options.isDryRun()) {
			File insertedFile = executeWithRetry(options, () -> drive.files().create(remoteFile).execute());
			syncDirectory.setRemoteFile(Optional.of(insertedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example 8
Source File: GoogleDrive.java    From google-drive-ftp-adapter with GNU Lesser General Public License v3.0 6 votes vote down vote up
private File mkdir_impl(GFile gFile, int retry) {
    try {
        // New file
        logger.info("Creating new directory...");
        File file = new File();
        file.setMimeType("application/vnd.google-apps.folder");
        file.setName(gFile.getName());
        file.setModifiedTime(new DateTime(System.currentTimeMillis()));
        file.setParents(new ArrayList<>(gFile.getParents()));
        file = drive.files().create(file).setFields(REQUEST_FILE_FIELDS).execute();
        logger.info("Directory created successfully: " + file.getId());
        return file;
    } catch (IOException e) {
        if (retry > 0) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                throw new RuntimeException(e1);
            }
            logger.warn("Uploading file failed. Retrying... '" + gFile.getId());
            return mkdir_impl(gFile, --retry);
        }
        throw new RuntimeException("Exception uploading file " + gFile.getId(), e);
    }
}
 
Example 9
Source File: DriveTimestampFeature.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException {
    try {
        final String fileid = this.fileid.getFileid(file, new DisabledListProgressListener());
        final File properties = new File();
        properties.setModifiedTime(new DateTime(status.getTimestamp()));
        session.getClient().files().update(fileid, properties).setFields("modifiedTime").
            setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute();
    }
    catch(IOException e) {
        throw new DriveExceptionMappingService().map("Failure to write attributes of {0}", e, file);
    }
}
 
Example 10
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 11
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 12
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 13
Source File: GoogleDrive.java    From google-drive-ftp-adapter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Touches the file, changing the name or date modified
 *
 * @param fileId          the file id to patch
 * @param newName         the new file name
 * @param newLastModified the new last modified date
 * @return the patched file
 */
public GFile patchFile(String fileId, String newName, long newLastModified) {
    File patch = new File();
    if (newName != null) {
        patch.setName(newName);
    }
    if (newLastModified > 0) {
        patch.setModifiedTime(new DateTime(newLastModified));
    }
    return create(patchFile(fileId, patch, 3));
}
 
Example 14
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 4 votes vote down vote up
public void store(SyncFile syncFile) {
	final String mimeType = determineMimeType(syncFile.getLocalFile().get());
	Drive drive = driveFactory.getDrive(this.credential);
	InputStream inputStream = null;
	try {
		final java.io.File localFile = syncFile.getLocalFile().get();
		inputStream = new FileInputStream(localFile);
		if (options.getEncryptFiles().matches(syncFile.getPath(), false)) {
			inputStream = encryption.encrypt(Files.readAllBytes(localFile.toPath()));
		}
		File remoteFile = new File();
		remoteFile.setName(localFile.getName());
		remoteFile.setMimeType(mimeType);
		remoteFile.setParents(createParentReferenceList(syncFile));
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		LOGGER.log(Level.INFO, "Uploading new file '" + syncFile.getPath() + "' (" + bytesWithUnit(attr.size()) + ").");
		if (!options.isDryRun()) {
			long startMillis = System.currentTimeMillis();
			File insertedFile;
			long chunkSizeLimit = options.getHttpChunkSizeInBytes();
			if (localFile.length() <= chunkSizeLimit) {
				LOGGER.log(Level.FINE, "File is smaller or equal than " + bytesWithUnit(chunkSizeLimit) + ": no chunked upload");
				insertedFile = executeWithRetry(options, () -> resumableUploadNoChunking(mimeType, drive, localFile, remoteFile));
			} else {
				insertedFile = executeWithRetry(options, () -> resumableUploadChunking(drive, localFile, remoteFile, chunkSizeLimit));
			}
			long duration = System.currentTimeMillis() - startMillis;
			if(LOGGER.isLoggable(Level.FINE)) {
				LOGGER.log(Level.FINE, String.format("Upload took %s ms for %s bytes: %.2f KB/s.", duration, attr.size(), (float) (attr.size() / 1024) / (float) (duration / 1000)));
			}
			syncFile.setRemoteFile(Optional.of(insertedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	} finally {
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException ignored) {}
		}
	}
}
 
Example 15
Source File: GoogleDriveInputReaderTest.java    From components with Apache License 2.0 4 votes vote down vote up
@Test
public void testAdvance() throws Exception {
    dataSource = spy(dataSource);
    Drive drive = mock(Drive.class, RETURNS_DEEP_STUBS);
    GoogleDriveUtils utils = mock(GoogleDriveUtils.class, RETURNS_DEEP_STUBS);
    doReturn(drive).when(dataSource).getDriveService();
    doReturn(utils).when(dataSource).getDriveUtils();

    List mockList = mock(List.class, RETURNS_DEEP_STUBS);
    when(drive.files().list()).thenReturn(mockList);
    //
    // String qA = "name='A' and 'root' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false";
    //
    // when(drive.files().list().setQ(eq(qA)).execute()).thenReturn(createFolderFileList("A", false));
    //
    // GoogleDriveAbstractListReader alr = mock(GoogleDriveAbstractListReader.class);
    // doReturn(true).when(alr).start();

    inputProperties.getDatasetProperties().folder.setValue("A");

    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, f, f, f, f));

    when(mockList.execute()).thenReturn(fileList);

    dataSource.initialize(container, inputProperties);
    reader = (GoogleDriveInputReader) dataSource.createReader(container);
    reader.setLimit(2);
    assertTrue(reader.start());
    reader.getCurrent();
    assertTrue(reader.advance());
    reader.getCurrent();
    assertFalse(reader.advance());
}
 
Example 16
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 4 votes vote down vote up
public void store(SyncFile syncFile) {
	final String mimeType = determineMimeType(syncFile.getLocalFile().get());
	Drive drive = driveFactory.getDrive(this.credential);
	InputStream inputStream = null;
	try {
		final java.io.File localFile = syncFile.getLocalFile().get();
		inputStream = new FileInputStream(localFile);
		if (options.getEncryptFiles().matches(syncFile.getPath(), false)) {
			inputStream = encryption.encrypt(Files.readAllBytes(localFile.toPath()));
		}
		File remoteFile = new File();
		remoteFile.setName(localFile.getName());
		remoteFile.setMimeType(mimeType);
		remoteFile.setParents(createParentReferenceList(syncFile));
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		LOGGER.log(Level.INFO, "Uploading new file '" + syncFile.getPath() + "' (" + bytesWithUnit(attr.size()) + ").");
		if (!options.isDryRun()) {
			long startMillis = System.currentTimeMillis();
			File insertedFile;
			long chunkSizeLimit = options.getHttpChunkSizeInBytes();
			if (localFile.length() <= chunkSizeLimit) {
				LOGGER.log(Level.FINE, "File is smaller or equal than " + bytesWithUnit(chunkSizeLimit) + ": no chunked upload");
				insertedFile = executeWithRetry(options, () -> resumableUploadNoChunking(mimeType, drive, localFile, remoteFile));
			} else {
				insertedFile = executeWithRetry(options, () -> resumableUploadChunking(drive, localFile, remoteFile, chunkSizeLimit));
			}
			long duration = System.currentTimeMillis() - startMillis;
			if(LOGGER.isLoggable(Level.FINE)) {
				LOGGER.log(Level.FINE, String.format("Upload took %s ms for %s bytes: %.2f KB/s.", duration, attr.size(), (float) (attr.size() / 1024) / (float) (duration / 1000)));
			}
			syncFile.setRemoteFile(Optional.of(insertedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	} finally {
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException ignored) {}
		}
	}
}