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

The following examples show how to use com.google.api.services.drive.model.File#setName() . 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: GoogleDriveFileObject.java    From hop with Apache License 2.0 6 votes vote down vote up
protected OutputStream doGetOutputStream( boolean append ) throws Exception {
  final File parent = getName().getParent() != null ? searchFile( getName().getParent().getBaseName(), null ) : null;
  ByteArrayOutputStream out = new ByteArrayOutputStream() {
    public void close() throws IOException {
      File file = new File();
      file.setName( getName().getBaseName() );
      if ( parent != null ) {
        file.setParents( Collections.singletonList( parent.getId() ) );
      }
      ByteArrayContent fileContent = new ByteArrayContent( "application/octet-stream", toByteArray() );
      if ( count > 0 ) {
        driveService.files().create( file, fileContent ).execute();
        ( (GoogleDriveFileSystem) getFileSystem() ).clearFileFromCache( getName() );
      }
    }
  };
  return out;
}
 
Example 2
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 3
Source File: GoogleDriveUtils.java    From components with Apache License 2.0 6 votes vote down vote up
/**
 * @param fileId ID of the fileName to copy
 * @param destinationFolderId folder ID where to copy the fileId
 * @param newName if not empty rename copy to this name
 * @param deleteOriginal remove original fileName (aka mv)
 * @return copied fileName ID
 * @throws IOException when copy fails
 */
public String copyFile(String fileId, String destinationFolderId, String newName, boolean deleteOriginal) throws IOException {
    LOG.debug("[copyFile] fileId: {}; destinationFolderId: {}, newName: {}; deleteOriginal: {}.", fileId, destinationFolderId,
            newName, deleteOriginal);
    File copy = new File();
    copy.setParents(Collections.singletonList(destinationFolderId));
    if (!newName.isEmpty()) {
        copy.setName(newName);
    }
    File resultFile = drive.files().copy(fileId, copy).setFields("id, parents").execute();
    String copiedResourceId = resultFile.getId();
    if (deleteOriginal) {
        drive.files().delete(fileId).execute();
    }

    return copiedResourceId;
}
 
Example 4
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public File createDirectory(File parentDirectory, String title) {
	File returnValue = null;
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		File remoteFile = new File();
		remoteFile.setName(title);
		remoteFile.setMimeType(MIME_TYPE_FOLDER);
		remoteFile.setParents(Arrays.asList(parentDirectory.getId()));
		LOGGER.log(Level.FINE, "Creating new directory '" + title + "'.");
		if (!options.isDryRun()) {
			returnValue = executeWithRetry(options, () -> drive.files().create(remoteFile).execute());
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to create directory: " + e.getMessage(), e);
	}
	return returnValue;
}
 
Example 5
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 6
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 7
Source File: GoogleBloggerImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String createAlbumFolder(Drive driveInterface) throws IOException {
  File fileMetadata = new File();
  LocalDate localDate = LocalDate.now();
  fileMetadata.setName("(Public)Imported Images on: " + localDate.toString());
  fileMetadata.setMimeType("application/vnd.google-apps.folder");
  File folder = driveInterface.files().create(fileMetadata).setFields("id").execute();
  driveInterface
      .permissions()
      .create(
          folder.getId(),
          // Set link sharing on, see:
          // https://developers.google.com/drive/api/v3/reference/permissions/create
          new Permission().setRole("reader").setType("anyone").setAllowFileDiscovery(false))
      .execute();
  return folder.getId();
}
 
Example 8
Source File: DriveMoveFeature.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
    try {
        if(status.isExists()) {
            delete.delete(Collections.singletonMap(renamed, status), connectionCallback, callback);
        }
        final String id = fileid.getFileid(file, new DisabledListProgressListener());
        if(!StringUtils.equals(file.getName(), renamed.getName())) {
            // Rename title
            final File properties = new File();
            properties.setName(renamed.getName());
            properties.setMimeType(status.getMime());
            session.getClient().files().update(id, properties).
                setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute();
        }
        // Retrieve the existing parents to remove
        final StringBuilder previousParents = new StringBuilder();
        final File reference = session.getClient().files().get(id)
            .setFields("parents")
            .setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable"))
            .execute();
        for(String parent : reference.getParents()) {
            previousParents.append(parent);
            previousParents.append(',');
        }
        // Move the file to the new folder
        session.getClient().files().update(id, null)
            .setAddParents(fileid.getFileid(renamed.getParent(), new DisabledListProgressListener()))
            .setRemoveParents(previousParents.toString())
            .setFields("id, parents")
            .setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable"))
            .execute();
        return new Path(renamed.getParent(), renamed.getName(), renamed.getType(),
            new DriveAttributesFinderFeature(session, fileid).find(renamed));
    }
    catch(IOException e) {
        throw new DriveExceptionMappingService().map("Cannot rename {0}", e, file);
    }
}
 
Example 9
Source File: GoogleDriveUtil.java    From algorithms-sedgewick-wayne with MIT License 5 votes vote down vote up
public static String createWebPage(String webPageName, List<String> data) {
    File fileMetadata = new File();
    fileMetadata.setName(webPageName);

    // Create file in staging area
    String filePath = STAGING_AREA_DIRECTORY_PATH + webPageName;
    FileUtil.writeFile(filePath, data);

    java.io.File fileInStagingArea = new java.io.File(filePath);
    FileContent fileContent = new FileContent(TEXT_PLAIN_TYPE, fileInStagingArea);

    File file;
    try {
        file = driveService.files()
                .create(fileMetadata, fileContent)
                .setFields("id")
                .execute();
    } catch (IOException exception) {
        StdOut.println("There was an error when trying to create the new web page.");
        return null;
    }

    // Delete file from staging area
    FileUtil.deleteFile(filePath);

    return file.getId();
}
 
Example 10
Source File: GpgsClient.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
/**
 * Blocking version of {@link #saveGameState(String, byte[], long, ISaveGameStateResponseListener)}
 *
 * @param fileId
 * @param gameState
 * @param progressValue
 * @throws IOException
 */
public void saveGameStateSync(String fileId, byte[] gameState, long progressValue) throws IOException {

    java.io.File file = java.io.File.createTempFile("games", "dat");
    new FileHandle(file).writeBytes(gameState, false);

    // no type since it is binary data
    FileContent mediaContent = new FileContent(null, file);

    // find file on server
    File remoteFile = findFileByNameSync(fileId);

    // file exists then update it
    if (remoteFile != null) {

        // just update content, leave metadata intact.

        GApiGateway.drive.files().update(remoteFile.getId(), null, mediaContent).execute();

        Gdx.app.log(TAG, "File updated ID: " + remoteFile.getId());
    }
    // file doesn't exists then create it
    else {
        File fileMetadata = new File();
        fileMetadata.setName(fileId);

        // app folder is a reserved keyyword for current application private folder.
        fileMetadata.setParents(Collections.singletonList("appDataFolder"));

        remoteFile = GApiGateway.drive.files().create(fileMetadata, mediaContent)
                .setFields("id")
                .execute();

        Gdx.app.log(TAG, "File created ID: " + remoteFile.getId());
    }

}
 
Example 11
Source File: GoogleDriveUtils.java    From components with Apache License 2.0 5 votes vote down vote up
/**
 * Create a folder in the specified parent folder
 *
 * @param parentFolderId folder ID where to create folderName
 * @param folderName new folder's name
 * @return folder ID value
 * @throws IOException when operation fails
 */
public String createFolder(String parentFolderId, String folderName) throws IOException {
    File createdFolder = new File();
    createdFolder.setName(folderName);
    createdFolder.setMimeType(MIME_TYPE_FOLDER);
    createdFolder.setParents(Collections.singletonList(parentFolderId));

    return drive.files().create(createdFolder).setFields("id").execute().getId();
}
 
Example 12
Source File: GoogleDriveFileObject.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
protected void doCreateFolder() throws Exception {
  if ( !getName().getBaseName().isEmpty() ) {
    File folder = new File();
    folder.setName( getName().getBaseName() );
    folder.setMimeType( MIME_TYPES.FOLDER.mimeType );
    folder = driveService.files().create( folder ).execute();
    if ( folder != null ) {
      id = folder.getId();
      mimeType = MIME_TYPES.get( folder.getMimeType() );
    }
  }
}
 
Example 13
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 14
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 15
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 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) {}
		}
	}
}
 
Example 17
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 18
Source File: GoogleDriveCopyRuntimeTest.java    From components with Apache License 2.0 4 votes vote down vote up
@Test
public void testRunAtDriverCopyFolder() throws Exception {
    final String q1 = "name='folder' and 'root' in parents and mimeType='application/vnd.google-apps.folder'";
    final String q2 = "'source-id' in parents and trashed=false";
    final String q3 = "'folder-id2' in parents and trashed=false";
    //
    FileList fsource = new FileList();
    List<File> fsfiles = new ArrayList<>();
    File fsfolder = new File();
    fsfolder.setMimeType(GoogleDriveMimeTypes.MIME_TYPE_FOLDER);
    fsfolder.setName("folder");
    fsfolder.setId(SOURCE_ID);
    fsfiles.add(fsfolder);
    fsource.setFiles(fsfiles);
    when(drive.files().list().setQ(eq(q1)).execute()).thenReturn(fsource);

    FileList flist = new FileList();
    List<File> ffiles = new ArrayList<>();
    File ffile = new File();
    ffile.setMimeType(GoogleDriveMimeTypes.MIME_TYPE_CSV);
    ffile.setName("fileName");
    ffile.setId("fileName-id");
    ffiles.add(ffile);
    File ffolder = new File();
    ffolder.setMimeType(GoogleDriveMimeTypes.MIME_TYPE_FOLDER);
    ffolder.setName("folder");
    ffolder.setId("folder-id2");
    ffiles.add(ffolder);
    flist.setFiles(ffiles);
    when(drive.files().list().setQ(eq(q2)).execute()).thenReturn(flist);
    when(drive.files().list().setQ(eq(q3)).execute()).thenReturn(emptyFileList);

    properties.copyMode.setValue(CopyMode.Folder);
    properties.source.setValue("/folder");
    properties.newName.setValue("");
    testRuntime.initialize(container, properties);
    testRuntime.runAtDriver(container);
    assertEquals(SOURCE_ID,
            container.getComponentData(TEST_CONTAINER, getStudioName(GoogleDriveCopyDefinition.RETURN_SOURCE_ID)));
    assertEquals(DESTINATION_ID,
            container.getComponentData(TEST_CONTAINER, getStudioName(GoogleDriveCopyDefinition.RETURN_DESTINATION_ID)));
}
 
Example 19
Source File: GoogleDriveCopyReaderTest.java    From components with Apache License 2.0 4 votes vote down vote up
@Test
public void testStartCopyFolder() throws Exception {
    final String q1 = "name='folder' and 'root' in parents and mimeType='application/vnd.google-apps.folder'";
    final String q2 = "'" + SOURCE_ID + "' in parents and trashed=false";
    final String q3 = "'folder-id2' in parents and trashed=false";
    //
    FileList fsource = new FileList();
    List<File> fsfiles = new ArrayList<>();
    File fsfolder = new File();
    fsfolder.setMimeType(GoogleDriveMimeTypes.MIME_TYPE_FOLDER);
    fsfolder.setName("folder");
    fsfolder.setId(SOURCE_ID);
    fsfiles.add(fsfolder);
    fsource.setFiles(fsfiles);
    when(drive.files().list().setQ(eq(q1)).execute()).thenReturn(fsource);

    FileList flist = new FileList();
    List<File> ffiles = new ArrayList<>();
    File ffile = new File();
    ffile.setMimeType(GoogleDriveMimeTypes.MIME_TYPE_CSV);
    ffile.setName("fileName");
    ffile.setId("fileName-id");
    ffiles.add(ffile);
    File ffolder = new File();
    ffolder.setMimeType(GoogleDriveMimeTypes.MIME_TYPE_FOLDER);
    ffolder.setName("folder");
    ffolder.setId("folder-id2");
    ffiles.add(ffolder);
    flist.setFiles(ffiles);
    when(drive.files().list().setQ(eq(q2)).execute()).thenReturn(flist);
    when(drive.files().list().setQ(eq(q3)).execute()).thenReturn(emptyFileList);

    properties.copyMode.setValue(CopyMode.Folder);
    properties.source.setValue("/folder");
    source.initialize(container, properties);
    BoundedReader reader = source.createReader(container);
    assertTrue(reader.start());
    IndexedRecord record = (IndexedRecord) reader.getCurrent();
    assertNotNull(record);
    assertEquals(2, record.getSchema().getFields().size());
    assertEquals(SOURCE_ID, record.get(0));
    assertEquals(DESTINATION_ID, record.get(1));
    reader.close();
    Map<String, Object> returnValues = reader.getReturnValues();
    assertNotNull(returnValues);
    assertEquals(SOURCE_ID, returnValues.get(GoogleDriveCopyDefinition.RETURN_SOURCE_ID));
    assertEquals(DESTINATION_ID, returnValues.get(GoogleDriveCopyDefinition.RETURN_DESTINATION_ID));
}
 
Example 20
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) {}
		}
	}
}