Java Code Examples for com.google.api.services.drive.model.File#setParents()
The following examples show how to use
com.google.api.services.drive.model.File#setParents() .
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 |
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: GoogleDriveFileObject.java From pentaho-kettle with Apache License 2.0 | 6 votes |
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 3
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 4
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 5
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 6
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 7
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 8
Source File: GoogleDrivePutRuntimeTest.java From components with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { super.setUp(); properties = new GoogleDrivePutProperties("test"); properties.connection.setupProperties(); properties.connection.setupLayout(); properties.schemaMain.setupProperties(); properties.schemaMain.setupLayout(); properties.setupProperties(); properties.setupLayout(); properties = (GoogleDrivePutProperties) setupConnectionWithAccessToken(properties); properties.uploadMode.setValue(UploadMode.UPLOAD_LOCAL_FILE); properties.fileName.setValue(FILE_PUT_NAME); properties.localFilePath.setValue("c:/Users/undx/brasil.jpg"); properties.overwrite.setValue(true); properties.destinationFolder.setValue("root"); testRuntime = spy(GoogleDrivePutRuntime.class); doReturn(drive).when(testRuntime).getDriveService(); when(drive.files().list().setQ(anyString()).execute()).thenReturn(emptyFileList); // File putFile = new File(); putFile.setId(PUT_FILE_ID); putFile.setParents(Collections.singletonList(PUT_FILE_PARENT_ID)); when(drive.files().create(any(File.class), any(AbstractInputStreamContent.class)).setFields(anyString()).execute()) .thenReturn(putFile); }
Example 9
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 10
Source File: GoogleDrivePutReaderTest.java From components with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { super.setUp(); properties = new GoogleDrivePutProperties("test"); properties.connection.setupProperties(); properties.connection.setupLayout(); properties.schemaMain.setupProperties(); properties.schemaMain.setupLayout(); properties.setupProperties(); properties.setupLayout(); properties = (GoogleDrivePutProperties) setupConnectionWithAccessToken(properties); properties.uploadMode.setValue(UploadMode.UPLOAD_LOCAL_FILE); properties.fileName.setValue(FILE_PUT_NAME); properties.localFilePath .setValue(Paths.get(getClass().getClassLoader().getResource("service_account.json").toURI()).toString()); properties.overwrite.setValue(true); properties.destinationFolder.setValue("root"); when(drive.files().list().setQ(anyString()).execute()).thenReturn(emptyFileList); // File putFile = new File(); putFile.setId(PUT_FILE_ID); putFile.setParents(Collections.singletonList(PUT_FILE_PARENT_ID)); when(drive.files().create(any(File.class), any(AbstractInputStreamContent.class)).setFields(anyString()).execute()) .thenReturn(putFile); }
Example 11
Source File: GoogleDriveApiImpl.java From science-journal with Apache License 2.0 | 5 votes |
private void insertFile(java.io.File localFile, String packageId) throws IOException { FileContent content = new FileContent(MIME_TYPE, localFile); File file = new File(); file.setTitle(localFile.getName()); file.setParents(Collections.singletonList(new ParentReference().setId(packageId))); driveApi .files() .insert(file, content) .execute(); }
Example 12
Source File: GoogleDriveApiImpl.java From science-journal with Apache License 2.0 | 5 votes |
@Override public void insertExperimentLibraryFile(java.io.File libraryFile) throws IOException { File file = new File(); file.setTitle(EXPERIMENT_LIBRARY_PROTO); file.setParents(Collections.singletonList(new ParentReference().setId(APP_DATA_FOLDER))); FileContent content = new FileContent(MIME_TYPE, libraryFile); driveApi .files() .insert(file, content) .execute(); }
Example 13
Source File: GoogleDrivePutWriterTest.java From components with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { super.setUp(); properties = new GoogleDrivePutProperties("test"); properties.connection.setupProperties(); properties.connection.setupLayout(); properties.schemaMain.setupProperties(); properties.schemaMain.setupLayout(); properties.setupProperties(); properties.setupLayout(); properties = (GoogleDrivePutProperties) setupConnectionWithAccessToken(properties); properties.uploadMode.setValue(UploadMode.UPLOAD_LOCAL_FILE); properties.fileName.setValue("GoogleDrive Put test BR"); properties.localFilePath.setValue("c:/Users/undx/brasil.jpg"); properties.overwrite.setValue(true); properties.destinationFolder.setValue("root"); sink.initialize(container, properties); wop = (GoogleDriveWriteOperation) sink.createWriteOperation(); writer = new GoogleDrivePutWriter(wop, properties, container); when(drive.files().list().setQ(anyString()).execute()).thenReturn(emptyFileList); // File putFile = new File(); putFile.setId(PUT_FILE_ID); putFile.setParents(Collections.singletonList(PUT_FILE_PARENT_ID)); when(drive.files().create(any(File.class), any(AbstractInputStreamContent.class)).setFields(anyString()).execute()) .thenReturn(putFile); }
Example 14
Source File: DriveImporter.java From data-transfer-project with Apache License 2.0 | 5 votes |
private String importSingleFolder(Drive driveInterface, String folderName, String parentId) throws IOException { File newFolder = new File().setName(folderName).setMimeType(DriveExporter.FOLDER_MIME_TYPE); if (!Strings.isNullOrEmpty(parentId)) { newFolder.setParents(ImmutableList.of(parentId)); } File resultFolder = driveInterface.files().create(newFolder).execute(); return resultFolder.getId(); }
Example 15
Source File: RemoteGoogleDriveConnector.java From cloudsync with GNU General Public License v2.0 | 4 votes |
@Override public void remove(final Handler handler, final Item item) throws CloudsyncException { initService(handler); int retryCount = 0; do { try { refreshCredential(); final File _parentDriveItem = _getHistoryFolder(item); if (_parentDriveItem != null) { final ParentReference parentReference = new ParentReference(); parentReference.setId(_parentDriveItem.getId()); File driveItem = new File(); driveItem.setParents(Collections.singletonList(parentReference)); driveItem = service.files().patch(item.getRemoteIdentifier(), driveItem).execute(); if (driveItem == null) { throw new CloudsyncException("Couldn't make a history snapshot of item '" + item.getPath() + "'"); } } else { service.files().delete(item.getRemoteIdentifier()).execute(); } _removeFromCache(item.getRemoteIdentifier()); return; } catch (final IOException e) { retryCount = validateException("remote remove", item, e, retryCount); if(retryCount < 0) // TODO workaround - fix this later retryCount = 0; } } while (true); }
Example 16
Source File: validation.java From oncokb with GNU Affero General Public License v3.0 | 4 votes |
private static void getWorksheets() throws IOException, ServiceException { String propFileName = "properties/config.properties"; Properties prop = new Properties(); ValidationConfig config = new ValidationConfig(); InputStream inputStream = config.getStram(propFileName); if (inputStream != null) { try { prop.load(inputStream); } catch (IOException ex) { Logger.getLogger(validation.class.getName()).log(Level.SEVERE, null, ex); } } else { throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); } String REPORT_PARENT_FOLDER = prop.getProperty("google.report_parent_folder"); String REPORT_DATA_TEMPLATE = prop.getProperty("google.report_data_template"); System.out.println("Got drive service"); DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); Date date = new Date(); String fileName = "Data run " + dateFormat.format(date); File file = new File(); file.setTitle(fileName); file.setParents(Arrays.asList(new ParentReference().setId(REPORT_PARENT_FOLDER))); file.setDescription("New File created from server"); System.out.println("Copying file"); file = driveService.files().copy(REPORT_DATA_TEMPLATE, file).execute(); System.out.println("Successfully copied file. Start to change file content"); String fileId = file.getId(); URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full/" + fileId); SpreadsheetEntry spreadSheetEntry = spreadsheetService.getEntry(SPREADSHEET_FEED_URL, SpreadsheetEntry.class); WorksheetFeed worksheetFeed = spreadsheetService.getFeed( spreadSheetEntry.getWorksheetFeedUrl(), WorksheetFeed.class); worksheets = worksheetFeed.getEntries(); }
Example 17
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) {} } } }
Example 18
Source File: GoogleDriveCopyRuntimeTest.java From components with Apache License 2.0 | 4 votes |
@Before public void setUp() throws Exception { super.setUp(); testRuntime = spy(GoogleDriveCopyRuntime.class); doReturn(drive).when(testRuntime).getDriveService(); 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='fileName-copy-name' and mimeType!='application/vnd.google-apps.folder'"; final String q3 = "name='A' 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); when(drive.files().list().setQ(eq(q3)).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: 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 20
Source File: RemoteGoogleDriveConnector.java From cloudsync with GNU General Public License v2.0 | 4 votes |
@Override public void update(final Handler handler, final Item item, final boolean with_filedata) throws CloudsyncException, FileIOException { initService(handler); int retryCount = 0; do { try { refreshCredential(); if (item.isType(ItemType.FILE)) { final File _parentDriveItem = _getHistoryFolder(item); if (_parentDriveItem != null) { final File copyOfdriveItem = new File(); final ParentReference _parentReference = new ParentReference(); _parentReference.setId(_parentDriveItem.getId()); copyOfdriveItem.setParents(Collections.singletonList(_parentReference)); // copyOfdriveItem.setTitle(driveItem.getTitle()); // copyOfdriveItem.setMimeType(driveItem.getMimeType()); // copyOfdriveItem.setProperties(driveItem.getProperties()); final File _copyOfDriveItem = service.files().copy(item.getRemoteIdentifier(), copyOfdriveItem).execute(); if (_copyOfDriveItem == null) { throw new CloudsyncException("Couldn't make a history snapshot of item '" + item.getPath() + "'"); } } } File driveItem = new File(); final LocalStreamData data = _prepareDriveItem(driveItem, item, handler, with_filedata); if (data == null) { driveItem = service.files().update(item.getRemoteIdentifier(), driveItem).execute(); } else { final InputStreamContent params = new InputStreamContent(FILE, data.getStream()); params.setLength(data.getLength()); Update updater = service.files().update(item.getRemoteIdentifier(), driveItem, params); MediaHttpUploader uploader = updater.getMediaHttpUploader(); prepareUploader(uploader, data.getLength()); driveItem = updater.execute(); } if (driveItem == null) { throw new CloudsyncException("Couldn't update item '" + item.getPath() + "'"); } else if (driveItem.getLabels().getTrashed()) { throw new CloudsyncException("Remote item '" + item.getPath() + "' [" + driveItem.getId() + "] is trashed\ntry to run with --nocache"); } _addToCache(driveItem, null); return; } catch (final IOException e) { retryCount = validateException("remote update", item, e, retryCount); if(retryCount < 0) // TODO workaround - fix this later retryCount = 0; } } while (true); }