Java Code Examples for com.google.api.services.drive.model.File#setMimeType()
The following examples show how to use
com.google.api.services.drive.model.File#setMimeType() .
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: GoogleDriveAdapter.java From jdrivesync with Apache License 2.0 | 6 votes |
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 2
Source File: BookmarkService.java From drivemarks with Apache License 2.0 | 6 votes |
/** * 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 3
Source File: GoogleDriveGetRuntimeTest.java From components with Apache License 2.0 | 6 votes |
@Test public void testRunAtDriverWithPath() throws Exception { String qA = "name='A' and 'root' in parents and mimeType='application/vnd.google-apps.folder'"; String qB = "name='B' and 'A' in parents and mimeType='application/vnd.google-apps.folder'"; String qC = "name='C' and 'B' in parents and mimeType='application/vnd.google-apps.folder'"; File file = new File(); file.setId("fileName-id"); file.setMimeType(GoogleDriveMimeTypes.MIME_TYPE_GOOGLE_DOCUMENT); when(drive.files().list().setQ(qA).execute()).thenReturn(createFolderFileList("A", false)); when(drive.files().list().setQ(qB).execute()).thenReturn(createFolderFileList("B", false)); when(drive.files().list().setQ(qC).execute()).thenReturn(createFolderFileList("C", false)); when(drive.files().get(anyString()).setFields(anyString()).execute()).thenReturn(file); // properties.file.setValue("/A/B/C"); testRuntime.initialize(container, properties); testRuntime.runAtDriver(container); assertEquals("C", container.getComponentData(TEST_CONTAINER, getStudioName(GoogleDriveGetDefinition.RETURN_FILE_ID))); assertNull(container.getComponentData(TEST_CONTAINER, getStudioName(GoogleDriveGetDefinition.RETURN_CONTENT))); }
Example 4
Source File: GoogleDrive.java From google-drive-ftp-adapter with GNU Lesser General Public License v3.0 | 6 votes |
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 5
Source File: GoogleDriveAdapter.java From jdrivesync with Apache License 2.0 | 6 votes |
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 6
Source File: GoogleDriveAdapter.java From jdrivesync with Apache License 2.0 | 6 votes |
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 7
Source File: GoogleDriveApiImpl.java From science-journal with Apache License 2.0 | 6 votes |
@Override public String getExperimentPackageId(Context context, String directoryId) throws IOException { // If we don't know it locally, but have the experiment locally, it must not exist yet. So, // create it remotely. File folder = new File(); folder.setTitle(context.getResources().getString(R.string.default_experiment_name)); folder.setMimeType(FOLDER_MIME_TYPE); folder.setParents(Collections.singletonList(new ParentReference().setId(directoryId))); File packageId = driveApi .files() .insert(folder) .setFields("id") .execute(); return packageId.getId(); }
Example 8
Source File: DriveImporter.java From data-transfer-project with Apache License 2.0 | 6 votes |
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 9
Source File: GoogleDriveApiImpl.java From science-journal with Apache License 2.0 | 5 votes |
@Override public String createNewSJFolder() throws IOException { File folder = new File(); folder.setTitle(FOLDER_NAME); folder.setMimeType(FOLDER_MIME_TYPE); folder.setParents(Collections.singletonList(new ParentReference().setId("root"))); File withId = driveApi .files() .insert(folder) .setFields("id") .execute(); return withId.getId(); }
Example 10
Source File: DriveSyncService.java From narrate-android with Apache License 2.0 | 5 votes |
private File getPhotosFolder() { try { File folder = getFile("photos"); if (folder == null) { File photos = new File(); photos.setTitle("photos"); photos.setAppDataContents(true); photos.setMimeType(FOLDER_MIME); photos.setParents(Arrays.asList(new ParentReference().setId(getAppFolder().getId()))); photos = service.files().insert(photos).execute(); return photos; } else { return folder; } } catch (Exception e) { e.printStackTrace(); if (!BuildConfig.DEBUG) Crashlytics.logException(e); } return null; }
Example 11
Source File: BookmarkService.java From drivemarks with Apache License 2.0 | 5 votes |
/** * Inserts a shortcut file into drivemarks folder with the * given title and link. * @param title * @param link * @return Inserted {@code File} object. * @throws IOException */ public File insert(String title, String link) throws IOException { Drive driveService = getDriveService(); File folder = createOrGetFolder("drivemarks"); // insert bookmark file File file = new File(); file.setTitle(title); file.setDescription(link); file.setMimeType(MIMETYPE_DRIVEMARK); file.setParents( Arrays.asList(new ParentReference().setId(folder.getId()))); return driveService.files().insert(file).execute(); }
Example 12
Source File: DriveMoveFeature.java From cyberduck with GNU General Public License v3.0 | 5 votes |
@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 13
Source File: AndroidGoogleDrive.java From QtAndroidTools with MIT License | 5 votes |
public String createFolder(String Name, String ParentFolderId) { if(mDriveService != null) { File FolderMetadata = new File(); File FolderData; FolderMetadata.setName(Name); FolderMetadata.setMimeType("application/vnd.google-apps.folder"); if(!ParentFolderId.isEmpty()) FolderMetadata.setParents(Collections.singletonList(ParentFolderId)); try { FolderData = mDriveService.files() .create(FolderMetadata) .setFields("id") .execute(); } catch(IOException e) { Log.d(TAG, e.toString()); return null; } return FolderData.getId(); } return null; }
Example 14
Source File: GoogleDriveListReaderTest.java From components with Apache License 2.0 | 5 votes |
@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 15
Source File: GoogleDriveListReaderTest.java From components with Apache License 2.0 | 5 votes |
@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 16
Source File: GoogleDriveFileObject.java From hop with Apache License 2.0 | 5 votes |
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 17
Source File: GoogleDriveInputReaderTest.java From components with Apache License 2.0 | 4 votes |
@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 |
@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 |
@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 |
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) {} } } }