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

The following examples show how to use com.google.api.services.drive.model.File#getId() . 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: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 7 votes vote down vote up
@Override
public String getRemoteExperimentLibraryFileId() throws IOException {
  FileList fileList =
      driveApi
          .files()
          .list()
          .setSpaces(APP_DATA_FOLDER)
          .setQ(EXPERIMENT_LIBRARY_QUERY)
          .execute();
  if (!fileList.getItems().isEmpty()) {
    File firstFile = fileList.getItems().get(0);
    if (firstFile != null) {
      return firstFile.getId();
    }
  }
  return null;
}
 
Example 2
Source File: GoogleDriveFileObject.java    From hop with Apache License 2.0 6 votes vote down vote up
private void resolveFileMetadata() throws Exception {
  String parentId = null;
  if ( getName().getParent() != null ) {
    File parent = searchFile( getName().getParent().getBaseName(), null );
    if ( parent != null ) {
      FileType mime = MIME_TYPES.get( parent.getMimeType() );
      if ( mime.equals( FileType.FOLDER ) ) {
        parentId = parent.getId();
      }
    }
  }

  String fileName = getName().getBaseName();
  File file = searchFile( fileName, parentId );
  if ( file != null ) {
    mimeType = MIME_TYPES.get( file.getMimeType() );
    id = file.getId();
  } else {
    if ( getName().getURI().equals( GoogleDriveFileProvider.SCHEME + ":///" ) ) {
      mimeType = FileType.FOLDER;
    }
  }
}
 
Example 3
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 4
Source File: GoogleBloggerImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String uploadImage(ASObject imageObject, Drive driveService, String parentFolderId)
    throws IOException {
  String url;
  String description = null;
  // The image property can either be an object, or just a URL, handle both cases.
  if ("Image".equalsIgnoreCase(imageObject.objectTypeString())) {
    url = imageObject.firstUrl().toString();
    if (imageObject.displayName() != null) {
      description = imageObject.displayNameString();
    }
  } else {
    url = imageObject.toString();
  }
  if (description == null) {
    description = "Imported photo from: " + url;
  }
  HttpURLConnection conn = imageStreamProvider.getConnection(url);
  InputStream inputStream = conn.getInputStream();
  File driveFile = new File().setName(description).setParents(ImmutableList.of(parentFolderId));
  InputStreamContent content = new InputStreamContent(null, inputStream);
  File newFile = driveService.files().create(driveFile, content).setFields("id").execute();

  return "https://drive.google.com/thumbnail?id=" + newFile.getId();
}
 
Example 5
Source File: AndroidGoogleDrive.java    From QtAndroidTools with MIT License 6 votes vote down vote up
public String getRootId()
{
    if(mDriveService != null)
    {
        File FileInfo;

        try
        {
            FileInfo = mDriveService.files()
                                    .get("root")
                                    .execute();
        }
        catch(IOException e)
        {
            Log.d(TAG, e.toString());
            return null;
        }

        return FileInfo.getId();
    }

    return null;
}
 
Example 6
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@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 7
Source File: GoogleDriveFileObject.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private void resolveFileMetadata() throws Exception {
  String parentId = null;
  if ( getName().getParent() != null ) {
    File parent = searchFile( getName().getParent().getBaseName(), null );
    if ( parent != null ) {
      FileType mime = MIME_TYPES.get( parent.getMimeType() );
      if ( mime.equals( FileType.FOLDER ) ) {
        parentId = parent.getId();
      }
    }
  }

  String fileName = getName().getBaseName();
  File file = searchFile( fileName, parentId );
  if ( file != null ) {
    mimeType = MIME_TYPES.get( file.getMimeType() );
    id = file.getId();
  } else {
    if ( getName().getURI().equals( GoogleDriveFileProvider.SCHEME + ":///" ) ) {
      mimeType = FileType.FOLDER;
    }
  }
}
 
Example 8
Source File: GoogleDriveFileSystem.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private FileStatus toFileStatus(File metadata) {
  return new FileStatus(metadata.getSize() == null ? 0L : metadata.getSize(),
                        FOLDER_MIME_TYPE.equals(metadata.getMimeType()),
                        -1,
                        -1,
                        metadata.getModifiedTime().getValue(),
                        new Path(metadata.getId()));
}
 
Example 9
Source File: GoogleDriveFileObject.java    From hop 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 10
Source File: Snippets.java    From java-samples with Apache License 2.0 5 votes vote down vote up
public String copyPresentation(String presentationId, String copyTitle) throws IOException {
    Drive driveService = this.driveService;
    // [START slides_copy_presentation]
    File copyMetadata = new File().setName(copyTitle);
    File presentationCopyFile =
            driveService.files().copy(presentationId, copyMetadata).execute();
    String presentationCopyId = presentationCopyFile.getId();
    // [END slides_copy_presentation]
    return presentationCopyId;
}
 
Example 11
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
private void delete(File file) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		String id = file.getId();
		if (isGoogleAppsDocument(file)) {
			LOGGER.log(Level.FINE, String.format("Not deleting file '%s' because it is a Google Apps document.", id));
			return;
		}
		if (options.isNoDelete()) {
			LOGGER.log(Level.FINE, String.format("Not deleting file '%s' because option --no-delete is set.", id));
			return;
		}
		if (options.isDeleteFiles()) {
			LOGGER.log(Level.FINE, "Deleting file " + id + " (" + file.getName() +").");
			if (!options.isDryRun()) {
				executeWithRetry(options, () -> drive.files().delete(id).execute());
			}
		} else {
			LOGGER.log(Level.FINE, "Trashing file " + id + " (" + file.getName() +").");
			if (!options.isDryRun()) {
				executeWithRetry(options, () -> drive.files().update("{'trashed':true}", file).execute()); //trash(id).execute());
			}
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to delete file: " + e.getMessage(), e);
	}
}
 
Example 12
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
private void delete(File file) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		String id = file.getId();
		if (isGoogleAppsDocument(file)) {
			LOGGER.log(Level.FINE, String.format("Not deleting file '%s' because it is a Google Apps document.", id));
			return;
		}
		if (options.isNoDelete()) {
			LOGGER.log(Level.FINE, String.format("Not deleting file '%s' because option --no-delete is set.", id));
			return;
		}
		if (options.isDeleteFiles()) {
			LOGGER.log(Level.FINE, "Deleting file " + id + " (" + file.getName() +").");
			if (!options.isDryRun()) {
				executeWithRetry(options, () -> drive.files().delete(id).execute());
			}
		} else {
			LOGGER.log(Level.FINE, "Trashing file " + id + " (" + file.getName() +").");
			if (!options.isDryRun()) {
				executeWithRetry(options, () -> drive.files().update("{'trashed':true}", file).execute()); //trash(id).execute());
			}
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to delete file: " + e.getMessage(), e);
	}
}
 
Example 13
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 14
Source File: SyncTestUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Gets KML files from Google Drive of current account.
 * 
 * @param context the context of application
 * @param drive a Google Drive object
 * @return KML file on Google drive
 * @throws IOException
 */
public static List<File> getDriveFiles(Context context, Drive drive) throws IOException {
  File folder = SyncUtils.getMyTracksFolder(context, drive);
  if (folder == null) {
    return new ArrayList<File>();
  }
  String folderId = folder.getId();
  return drive.files().list()
      .setQ(String.format(Locale.US, SyncUtils.MY_TRACKS_FOLDER_FILES_QUERY, folderId)).execute()
      .getItems();
}
 
Example 15
Source File: SyncAdapter.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the folder id..
 */
private String getFolderId() throws IOException {
  File folder = SyncUtils.getMyTracksFolder(context, drive);
  if (folder == null) {
    throw new IOException("folder is null");
  }
  String id = folder.getId();
  if (id == null) {
    throw new IOException("folder id is null");
  }
  return id;
}
 
Example 16
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 17
Source File: AndroidGoogleDrive.java    From QtAndroidTools with MIT License 5 votes vote down vote up
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 18
Source File: DriveImporter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
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 19
Source File: RemoteGoogleDriveConnector.java    From cloudsync with GNU General Public License v2.0 4 votes vote down vote up
@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);
}
 
Example 20
Source File: Snippets.java    From java-samples with Apache License 2.0 4 votes vote down vote up
public BatchUpdatePresentationResponse imageMerging(String templatePresentationId,
                                                    String imageUrl,
                                                    String customerName) throws IOException {
    Slides slidesService = this.service;
    Drive driveService = this.driveService;
    String logoUrl = imageUrl;
    String customerGraphicUrl = imageUrl;

    // [START slides_image_merging]
    // Duplicate the template presentation using the Drive API.
    String copyTitle = customerName + " presentation";
    File content = new File().setName(copyTitle);
    File presentationFile =
            driveService.files().copy(templatePresentationId, content).execute();
    String presentationId = presentationFile.getId();

    // Create the image merge (replaceAllShapesWithImage) requests.
    List<Request> requests = new ArrayList<>();
    requests.add(new Request()
            .setReplaceAllShapesWithImage(new ReplaceAllShapesWithImageRequest()
                    .setImageUrl(logoUrl)
                    .setReplaceMethod("CENTER_INSIDE")
                    .setContainsText(new SubstringMatchCriteria()
                            .setText("{{company-logo}}")
                            .setMatchCase(true))));
    requests.add(new Request()
            .setReplaceAllShapesWithImage(new ReplaceAllShapesWithImageRequest()
                    .setImageUrl(customerGraphicUrl)
                    .setReplaceMethod("CENTER_INSIDE")
                    .setContainsText(new SubstringMatchCriteria()
                            .setText("{{customer-graphic}}")
                            .setMatchCase(true))));

    // Execute the requests.
    BatchUpdatePresentationRequest body =
            new BatchUpdatePresentationRequest().setRequests(requests);
    BatchUpdatePresentationResponse response =
            slidesService.presentations().batchUpdate(presentationId, body).execute();

    // Count total number of replacements made.
    int numReplacements = 0;
    for(Response resp: response.getReplies()) {
        numReplacements += resp.getReplaceAllShapesWithImage().getOccurrencesChanged();
    }

    System.out.println("Created merged presentation with ID: " + presentationId);
    System.out.println("Replaced " + numReplacements + " shapes instances with images.");
    // [END slides_image_merging]
    return response;
}