com.google.api.services.drive.model.File.setParents()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(14.7k)|赞(0)|评价(0)|浏览(188)

本文整理了Java中com.google.api.services.drive.model.File.setParents()方法的一些代码示例,展示了File.setParents()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。File.setParents()方法的具体详情如下:
包路径:com.google.api.services.drive.model.File
类名称:File
方法名:setParents

File.setParents介绍

[英]The IDs of the parent folders which contain the file. If not specified as part of a create request, the file will be placed directly in the user's My Drive folder. If not specified as part of a copy request, the file will inherit any discoverable parents of the source file. Update requests must use the addParents and removeParents parameters to modify the parents list.
[中]包含该文件的父文件夹的ID。如果未指定为创建请求的一部分,则文件将直接放置在用户的“我的驱动器”文件夹中。如果未指定为复制请求的一部分,则该文件将继承源文件的任何可发现父级。更新请求必须使用addParents和removeParents参数来修改父列表。

代码示例

代码示例来源:origin: google/data-transfer-project

private String importSingleFolder(
  UUID jobId,
  Drive driveInterface,
  String folderName,
  String folderId,
  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();
 DriveFolderMapping mapping = new DriveFolderMapping(folderId, resultFolder.getId());
 jobStore.update(jobId, folderId, mapping);
 return resultFolder.getId();
}

代码示例来源:origin: google/data-transfer-project

private void importSingleFile(
  UUID jobId,
  Drive driveInterface,
  DigitalDocumentWrapper file,
  String parentId)
  throws IOException {
 InputStreamContent content = new InputStreamContent(
   null,
   jobStore.getStream(jobId, file.getCachedContentId()));
 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());
 }
 driveInterface.files().create(
   driveFile,
   content
 ).execute();
}

代码示例来源:origin: pentaho/pentaho-kettle

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() );
  }
 }
};

代码示例来源:origin: com.github.robozonky/robozonky-integration-stonky

public static com.google.api.services.drive.model.File copyFile(final Drive driveService,
                                final com.google.api.services.drive.model.File upstream,
                                final com.google.api.services.drive.model.File parent,
                                final String name) throws IOException {
  LOGGER.debug("Cloning master spreadsheet '{}', setting name: {}.", upstream.getId(), name);
  final com.google.api.services.drive.model.File f = new com.google.api.services.drive.model.File();
  f.setName(name);
  f.setParents(Collections.singletonList(parent.getId()));
  final com.google.api.services.drive.model.File result = driveService.files().copy(upstream.getId(), f)
      .setFields("id,name,modifiedTime")
      .execute();
  LOGGER.debug("Created a copy: {}.", result.getId());
  return result;
}

代码示例来源:origin: RoboZonky/robozonky

public static com.google.api.services.drive.model.File copyFile(final Drive driveService,
                                final com.google.api.services.drive.model.File upstream,
                                final com.google.api.services.drive.model.File parent,
                                final String name) throws IOException {
  LOGGER.debug("Cloning master spreadsheet '{}', setting name: {}.", upstream.getId(), name);
  final com.google.api.services.drive.model.File f = new com.google.api.services.drive.model.File();
  f.setName(name);
  f.setParents(Collections.singletonList(parent.getId()));
  final com.google.api.services.drive.model.File result = driveService.files().copy(upstream.getId(), f)
      .setFields("id,name,modifiedTime")
      .execute();
  LOGGER.debug("Created a copy: {}.", result.getId());
  return result;
}

代码示例来源:origin: siom79/jdrivesync

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);
  }
}

代码示例来源:origin: andresoviedo/google-drive-ftp-adapter

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);
  }
}

代码示例来源:origin: siom79/jdrivesync

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;
}

代码示例来源:origin: org.talend.components/components-googledrive-runtime

/**
 * @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;
}

代码示例来源:origin: RoboZonky/robozonky

private File createSpreadsheet(final String name, final java.io.File export, final String mime) throws IOException {
  final FileContent fc = new FileContent(mime, export);
  final File parent = getOrCreateRoboZonkyFolder(); // retrieve Google folder in which to place the spreadsheet
  // convert the spreadsheet to Google Spreadsheet
  final File f = new File();
  f.setName(name);
  f.setParents(Collections.singletonList(parent.getId()));
  f.setMimeType(MIME_TYPE_GOOGLE_SPREADSHEET);
  LOGGER.debug("Creating a new Google spreadsheet: {}.", f);
  final File result = driveService.files().create(f, fc)
      .setFields(getFields())
      .execute();
  // and mark the time when the file was last updated
  LOGGER.debug("New Google spreadsheet created: {}.", result.getId());
  return result;
}

代码示例来源:origin: com.github.robozonky/robozonky-integration-stonky

private File createSpreadsheet(final String name, final java.io.File export, final String mime) throws IOException {
  final FileContent fc = new FileContent(mime, export);
  final File parent = getOrCreateRoboZonkyFolder(); // retrieve Google folder in which to place the spreadsheet
  // convert the spreadsheet to Google Spreadsheet
  final File f = new File();
  f.setName(name);
  f.setParents(Collections.singletonList(parent.getId()));
  f.setMimeType(MIME_TYPE_GOOGLE_SPREADSHEET);
  LOGGER.debug("Creating a new Google spreadsheet: {}.", f);
  final File result = driveService.files().create(f, fc)
      .setFields(getFields())
      .execute();
  // and mark the time when the file was last updated
  LOGGER.debug("New Google spreadsheet created: {}.", result.getId());
  return result;
}

代码示例来源:origin: org.talend.components/components-googledrive-runtime

/**
 * 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();
}

代码示例来源:origin: Talend/components

/**
 * @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;
}

代码示例来源:origin: Talend/components

/**
 * 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();
}

代码示例来源:origin: org.talend.components/components-googledrive-runtime

public File putResource(GoogleDrivePutParameters parameters) throws IOException {
  String folderId = parameters.getDestinationFolderId();
  File putFile = new File();
  putFile.setParents(Collections.singletonList(folderId));
  Files.List fileRequest = drive.files().list()
      .setQ(format(QUERY_NOTTRASHED_NAME_NOTMIME_INPARENTS, parameters.getResourceName(), MIME_TYPE_FOLDER, folderId));

代码示例来源:origin: Talend/components

public File putResource(GoogleDrivePutParameters parameters) throws IOException {
  String folderId = parameters.getDestinationFolderId();
  File putFile = new File();
  putFile.setParents(Collections.singletonList(folderId));
  Files.List fileRequest = drive.files().list()
      .setQ(format(QUERY_NOTTRASHED_NAME_NOTMIME_INPARENTS, parameters.getResourceName(), MIME_TYPE_FOLDER, folderId));

代码示例来源:origin: MrStahlfelge/gdx-gamesvcs

fileMetadata.setParents(Collections.singletonList("appDataFolder"));

代码示例来源:origin: iterate-ch/cyberduck

@Override
public Path touch(final Path file, final TransferStatus status) throws BackgroundException {
  try {
    final Drive.Files.Create insert = session.getClient().files().create(new File()
      .setName(file.getName())
      .setMimeType(status.getMime())
      .setParents(Collections.singletonList(fileid.getFileid(file.getParent(), new DisabledListProgressListener()))));
    final File execute = insert.setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute();
    return new Path(file.getParent(), file.getName(), file.getType(),
      new DriveAttributesFinderFeature(session, fileid).toAttributes(execute));
  }
  catch(IOException e) {
    throw new DriveExceptionMappingService().map("Cannot create file {0}", e, file);
  }
}

代码示例来源:origin: iterate-ch/cyberduck

@Override
public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
  try {
    final File copy = session.getClient().files().copy(fileid.getFileid(source, new DisabledListProgressListener()), new File()
      .setParents(Collections.singletonList(fileid.getFileid(target.getParent(), new DisabledListProgressListener())))
      .setName(target.getName()))
      .setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute();
    return new Path(target.getParent(), target.getName(), target.getType(),
        new PathAttributes(target.attributes()).withVersionId(copy.getId()));
  }
  catch(IOException e) {
    throw new DriveExceptionMappingService().map("Cannot copy {0}", e, source);
  }
}

代码示例来源:origin: iterate-ch/cyberduck

@Override
public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException {
  try {
    if(DriveHomeFinderService.TEAM_DRIVES_NAME.equals(folder.getParent())) {
      final TeamDrive execute = session.getClient().teamdrives().create(
        new UUIDRandomStringService().random(), new TeamDrive().setName(folder.getName())
      ).execute();
      return new Path(folder.getParent(), folder.getName(), folder.getType(),
        new PathAttributes(folder.attributes()).withVersionId(execute.getId()));
    }
    else {
      // Identified by the special folder MIME type application/vnd.google-apps.folder
      final Drive.Files.Create insert = session.getClient().files().create(new File()
        .setName(folder.getName())
        .setMimeType("application/vnd.google-apps.folder")
        .setParents(Collections.singletonList(fileid.getFileid(folder.getParent(), new DisabledListProgressListener()))));
      final File execute = insert
        .setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute();
      return new Path(folder.getParent(), folder.getName(), folder.getType(),
        new DriveAttributesFinderFeature(session, fileid).toAttributes(execute));
    }
  }
  catch(IOException e) {
    throw new DriveExceptionMappingService().map("Cannot create folder {0}", e, folder);
  }
}

相关文章