com.google.api.services.drive.model.File Java Examples

The following examples show how to use com.google.api.services.drive.model.File. 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: GoogleDriveIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
private static File uploadTestFile(ProducerTemplate template, String testName) {
    File fileMetadata = new File();
    fileMetadata.setTitle(GoogleDriveIntegrationTest.class.getName()+"."+testName+"-"+ UUID.randomUUID().toString());
    final String content = "Camel rocks!\n" //
            + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()) + "\n" //
            + "user: " + System.getProperty("user.name");
    HttpContent mediaContent = new ByteArrayContent("text/plain", content.getBytes(StandardCharsets.UTF_8));

    final Map<String, Object> headers = new HashMap<>();
    // parameter type is com.google.api.services.drive.model.File
    headers.put("CamelGoogleDrive.content", fileMetadata);
    // parameter type is com.google.api.client.http.AbstractInputStreamContent
    headers.put("CamelGoogleDrive.mediaContent", mediaContent);

    return template.requestBodyAndHeaders("google-drive://drive-files/insert", null, headers, File.class);
}
 
Example #2
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 #3
Source File: SyncAdapter.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all the files from a request.
 * 
 * @param request the request
 * @param excludeSharedWithMe true to exclude shared with me files
 * @return a map of file id to file
 */
private Map<String, File> getFiles(Files.List request, boolean excludeSharedWithMe)
    throws IOException {
  Map<String, File> idToFileMap = new HashMap<String, File>();
  do {
    FileList files = request.execute();

    for (File file : files.getItems()) {
      if (excludeSharedWithMe && file.getSharedWithMeDate() != null) {
        continue;
      }
      idToFileMap.put(file.getId(), file);
    }
    request.setPageToken(files.getNextPageToken());
  } while (request.getPageToken() != null && request.getPageToken().length() > 0);
  return idToFileMap;
}
 
Example #4
Source File: SyncTestUtils.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the files number on Google Drive
 * 
 * @param drive a Google Drive object
 * @throws IOException
 */
public static void checkFilesNumber(Drive drive) throws IOException {
  EndToEndTestUtils.instrumentation.waitForIdleSync();
  long startTime = System.currentTimeMillis();
  int trackNumber = EndToEndTestUtils.SOLO.getCurrentViews(ListView.class).get(0).getCount();
  List<File> files = getDriveFiles(EndToEndTestUtils.trackListActivity.getApplicationContext(),
      drive);
  while (System.currentTimeMillis() - startTime < MAX_TIME_TO_WAIT_SYNC) {
    try {
      if (files.size() == trackNumber) {
        return;
      }
      trackNumber = EndToEndTestUtils.SOLO.getCurrentViews(ListView.class).get(0).getCount();
      files = getDriveFiles(EndToEndTestUtils.trackListActivity.getApplicationContext(), drive);
      EndToEndTestUtils.sleep(EndToEndTestUtils.SHORT_WAIT_TIME);
      EndToEndTestUtils.findMenuItem(
          EndToEndTestUtils.trackListActivity.getString(R.string.menu_sync_now), true);
    } catch (GoogleJsonResponseException e) {
      Log.e(TAG, e.getMessage(), e);
    }
  }
  Assert.assertEquals(files.size(), trackNumber);
}
 
Example #5
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 #6
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 #7
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public List<File> listChildren(String parentId) {
	List<File> resultList = new LinkedList<File>();
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		Drive.Files.List request = drive.files().list().setFields("nextPageToken, files");
		request.setQ("trashed = false and '" + parentId + "' in parents");
		request.setPageSize(1000);
		LOGGER.log(Level.FINE, "Listing children of folder " + parentId + ".");
		do {
			FileList fileList = executeWithRetry(options, () -> request.execute());
			List<File> items = fileList.getFiles();
			resultList.addAll(items);
			request.setPageToken(fileList.getNextPageToken());
		} while (request.getPageToken() != null && request.getPageToken().length() > 0);
		if (LOGGER.isLoggable(Level.FINE)) {
			for (File file : resultList) {
				LOGGER.log(Level.FINE, "Child of " + parentId + ": " + file.getId() + ";" + file.getName() + ";" + file.getMimeType());
			}
		}
		removeDuplicates(resultList);
		return resultList;
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to execute list request: " + e.getMessage(), e);
	}
}
 
Example #8
Source File: GoogleDriveUtils.java    From components with Apache License 2.0 6 votes vote down vote up
/**
 * @param sourceFolderId source folder ID
 * @param destinationFolderId folder ID where to copy the sourceFolderId's content
 * @param newName folder name to assign
 * @return created folder ID
 * @throws IOException when operation fails
 */
public String copyFolder(String sourceFolderId, String destinationFolderId, String newName) throws IOException {
    LOG.debug("[copyFolder] sourceFolderId: {}; destinationFolderId: {}; newName: {}", sourceFolderId, destinationFolderId,
            newName);
    // create a new folder
    String newFolderId = createFolder(destinationFolderId, newName);
    // Make a recursive copy of all files/folders inside the source folder
    String query = format(Q_IN_PARENTS, sourceFolderId) + Q_AND + Q_NOT_TRASHED;
    FileList originals = drive.files().list().setQ(query).execute();
    LOG.debug("[copyFolder] Searching for copy {}", query);
    for (File file : originals.getFiles()) {
        if (file.getMimeType().equals(MIME_TYPE_FOLDER)) {
            copyFolder(file.getId(), newFolderId, file.getName());
        } else {
            copyFile(file.getId(), newFolderId, file.getName(), false);
        }
    }

    return newFolderId;
}
 
Example #9
Source File: DriveImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateFile(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.INFO, "Updating file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), remoteFile, new FileContent(determineMimeType(localFile), localFile));
			//updateRequest.setModifiedDate(true);
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example #11
Source File: AndroidGoogleDrive.java    From QtAndroidTools with MIT License 6 votes vote down vote up
public File getFileMetadata(String FileId, String Fields)
{
    if(mDriveService != null)
    {
        File FileInfo;

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

        return FileInfo;
    }

    return null;
}
 
Example #12
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 #13
Source File: GpgsClient.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
/**
 * Blocking version of {@link #fetchGameStatesSync()}
 *
 * @return game states
 * @throws IOException
 */
public Array<String> fetchGameStatesSync() throws IOException {

    if (!driveApiEnabled)
        throw new UnsupportedOperationException();

    Array<String> games = new Array<String>();

    FileList l = GApiGateway.drive.files().list()
            .setSpaces("appDataFolder")
            .setFields("files(name)")
            .execute();

    for (File f : l.getFiles()) {
        games.add(f.getName());
    }

    return games;
}
 
Example #14
Source File: GoogleDriveResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Path("/read")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response readFile(@QueryParam("fileId") String fileId) {
    try {
        File response = producerTemplate.requestBody("google-drive://drive-files/get?inBody=fileId", fileId, File.class);
        if (response != null) {
            return Response.ok(response.getTitle()).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    } catch (CamelExecutionException e) {
        Exception exchangeException = e.getExchange().getException();
        if (exchangeException != null && exchangeException.getCause() instanceof GoogleJsonResponseException) {
            GoogleJsonResponseException originalException = (GoogleJsonResponseException) exchangeException.getCause();
            return Response.status(originalException.getStatusCode()).build();
        }
        throw e;
    }
}
 
Example #15
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 #16
Source File: GoogleDrivePutRuntimeTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunAtDriverTooManyFiles() throws Exception {
    FileList hasfilelist = new FileList();
    List<File> hfiles = new ArrayList<>();
    File hfile = new File();
    hfile.setId(FILE_PUT_NAME);
    hfiles.add(hfile);
    hfiles.add(new File());
    hasfilelist.setFiles(hfiles);
    when(drive.files().list().setQ(anyString()).execute()).thenReturn(hasfilelist);
    properties.overwrite.setValue(true);
    testRuntime.initialize(container, properties);
    try {
        testRuntime.runAtDriver(container);
        fail("Should not be here");
    } catch (Exception e) {
    }
}
 
Example #17
Source File: RemoteGoogleDriveConnector.java    From cloudsync with GNU General Public License v2.0 6 votes vote down vote up
@Override
public InputStream get(final Handler handler, final Item item) throws CloudsyncException
{
	initService(handler);

	int retryCount = 0;
	do
	{
		try
		{
			refreshCredential();

			final File driveItem = _getDriveItem(item);
			final String downloadUrl = driveItem.getDownloadUrl();
			final HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(downloadUrl)).execute();
			return resp.getContent();
		}
		catch (final IOException e)
		{
			retryCount = validateException("remote get", item, e, retryCount);
			if(retryCount < 0) // TODO workaround - fix this later
				retryCount = 0;
		}
	}
	while (true);
}
 
Example #18
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Long> getAllDriveExperimentVersions() throws IOException {
  FileList files =
      driveApi
          .files()
          .list()
          .setQ("title = '" + EXPERIMENT_PROTO_FILE + "'")
          .setFields("items(version,parents)")
          .execute();
  HashMap<String, Long> versionMap = new HashMap<>();
  if (!files.getItems().isEmpty()) {
    for (File f : files.getItems()) {
      versionMap.put(f.getParents().get(0).getId(), f.getVersion());
    }
  }
  return versionMap;
}
 
Example #19
Source File: DriveDefaultListServiceTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testSameFoldername() throws Exception {
    final String f1 = new AlphanumericRandomStringService().random();
    final String f2 = new AlphanumericRandomStringService().random();
    final Path parent = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, f1, EnumSet.of(Path.Type.directory));
    final Path folder = new Path(parent, f2, EnumSet.of(Path.Type.directory));
    final DriveFileidProvider provider = new DriveFileidProvider(session).withCache(cache);
    new DriveDirectoryFeature(session, provider).mkdir(parent, null, new TransferStatus());
    new DriveDirectoryFeature(session, provider).mkdir(folder, null, new TransferStatus());
    assertTrue(new DefaultFindFeature(session).find(folder));
    assertEquals(1, new DriveDefaultListService(session, provider).list(parent, new DisabledListProgressListener()).size());
    final String fileid = provider.getFileid(folder, new DisabledListProgressListener());
    final File body = new File();
    body.set("trashed", true);
    session.getClient().files().update(fileid, body).execute();
    new DriveDirectoryFeature(session, provider).mkdir(folder, null, new TransferStatus());
    assertEquals(2, new DriveDefaultListService(session, provider).list(parent, new DisabledListProgressListener()).size());
    new DriveDeleteFeature(session, provider).delete(Collections.singletonList(parent), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example #20
Source File: DriveSyncService.java    From narrate-android with Apache License 2.0 6 votes vote down vote up
private File getPhoto(String title) {
    try {
        List<File> photos = getPhotosContents();

        if (photos != null) {
            for (File f : photos) {
                if (f.getTitle().equalsIgnoreCase(title))
                    return f;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example #21
Source File: GoogleDriveGetRuntimeTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test(expected = ComponentException.class)
public void testManyFiles() throws Exception {
    FileList files = new FileList();
    List<File> fl = new ArrayList<>();
    File f1 = new File();
    fl.add(f1);
    File f2 = new File();
    fl.add(f2);
    files.setFiles(fl);
    String q1 = "name='A' and 'root' in parents and mimeType='application/vnd.google-apps.folder'";
    when(drive.files().list().setQ(q1).execute()).thenReturn(files);
    when(drive.files().list().setQ(any()).execute()).thenReturn(files);
    //
    properties.file.setValue("/A");
    testRuntime.initialize(container, properties);
    testRuntime.runAtDriver(container);
    fail("Should not be here");
}
 
Example #22
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateFile(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.INFO, "Updating file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), remoteFile, new FileContent(determineMimeType(localFile), localFile));
			//updateRequest.setModifiedDate(true);
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example #23
Source File: SyncUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Updates a drive file using info from a track. Returns true if successful.
 * 
 * @param drive the drive
 * @param driveFile the drive file
 * @param context the context
 * @param myTracksProviderUtils the myTracksProviderUtils
 * @param track the track
 * @param canRetry true if can retry
 */
public static boolean updateDriveFile(Drive drive, File driveFile, Context context,
    MyTracksProviderUtils myTracksProviderUtils, Track track, boolean canRetry)
    throws IOException {
  Log.d(TAG, "Update drive file for track " + track.getName());
  java.io.File file = null;

  try {
    file = SyncUtils.getTempFile(context, myTracksProviderUtils, track, true);
    if (file == null) {
      Log.e(TAG, "Unable to update drive file. File is null for track " + track.getName());
      return false;
    }

    String title = track.getName() + "." + KmzTrackExporter.KMZ_EXTENSION;
    File updatedFile = updateDriveFile(drive, driveFile, title, file, canRetry);

    if (updatedFile == null) {
      Log.e(
          TAG, "Unable to update drive file. Updated file is null for track " + track.getName());
      return false;
    }
    long modifiedTime = updatedFile.getModifiedDate().getValue();
    if (track.getModifiedTime() != modifiedTime) {
      track.setModifiedTime(modifiedTime);
      myTracksProviderUtils.updateTrack(track);
    }
    return true;
  } finally {
    if (file != null) {
      file.delete();
    }
  }
}
 
Example #24
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
public InputStream downloadFile(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);

	try {
		File remoteFile = syncItem.getRemoteFile().get();
		GenericUrl genericUrl = null;
		if(isGoogleAppsDocumentforExport(remoteFile)){
			Optional<String> exportMimeType = supportedGooglMimeType.get(remoteFile.getMimeType());
			Export export = drive.files().export(remoteFile.getId(), exportMimeType.get());
			genericUrl = export.buildHttpRequestUrl();
		}else{
			genericUrl = drive.files().get(remoteFile.getId()).set("alt", "media").buildHttpRequestUrl();
		}

		if (genericUrl != null) {
			HttpRequest httpRequest = drive.getRequestFactory().buildGetRequest(genericUrl);
			LOGGER.log(Level.FINE, "Downloading file " + remoteFile.getId() + ".");
			if (!options.isDryRun()) {
				HttpResponse httpResponse = executeWithRetry(options, () -> httpRequest.execute());
				return httpResponse.getContent();
			}
		} else {
			LOGGER.log(Level.SEVERE, "No download URL for file " + remoteFile);
		}
	} catch (Exception e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to download file: " + e.getMessage(), e);
	}
	return new ByteArrayInputStream(new byte[0]);
}
 
Example #25
Source File: TGDriveBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void createElement(final TGBrowserCallBack<TGBrowserElement> cb, final String name) {
	try {
		File file = new File();
		file.setTitle(name);
		file.setParents(Arrays.asList(new ParentReference().setId(this.folder.getFile().getId())));
		
		cb.onSuccess(new TGDriveBrowserFile(file, this.folder));
	} catch (RuntimeException e) {
		cb.handleError(e);
	}
}
 
Example #26
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 5 votes vote down vote up
private void updateFile(File serverFile, java.io.File localFile) throws IOException {
  FileContent content = new FileContent(MIME_TYPE, localFile);
  File file = new File();
  file.setTitle(serverFile.getTitle());
  file.setId(serverFile.getId());
  driveApi
      .files()
      .update(serverFile.getId(), file, content)
      .execute();
}
 
Example #28
Source File: RemoteGoogleDriveConnector.java    From cloudsync with GNU General Public License v2.0 5 votes vote down vote up
private File _getDriveItem(final Item item) throws CloudsyncException, IOException
{
	final String id = item.getRemoteIdentifier();

	if (cacheFiles.containsKey(id))
	{
		return cacheFiles.get(id);
	}

	File driveItem;

	try
	{
		driveItem = service.files().get(id).execute();
	}
	catch (HttpResponseException e)
	{

		if (e.getStatusCode() == 404)
		{
			throw new CloudsyncException("Couldn't find remote item '" + item.getPath() + "' [" + id + "]\ntry to run with --nocache");
		}

		throw e;
	}

	if (driveItem.getLabels().getTrashed())
	{
		throw new CloudsyncException("Remote item '" + item.getPath() + "' [" + id + "] is trashed\ntry to run with --nocache");
	}

	_addToCache(driveItem, null);
	return driveItem;
}
 
Example #29
Source File: SyncTestUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Removes all KML files on Google Drive.
 * 
 * @param drive a Google Drive object
 * @throws IOException
 */
public static void removeKMLFiles(Drive drive) throws IOException {
  List<File> files = getDriveFiles(
      EndToEndTestUtils.trackListActivity.getApplicationContext(), drive);
  for (int i = 0; i < files.size(); i++) {
    File file = files.get(i);
    removeFile(file, drive);
  }
}
 
Example #30
Source File: TGDriveBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void cdRoot(TGBrowserCallBack<Object> cb) {
	try {
		File file = new File();
		file.setId(ROOT_FOLDER);
		
		this.folder = new TGDriveBrowserFile(file, null);
		
		cb.onSuccess(this.folder);
	} catch (Throwable e) {
		cb.handleError(e);
	}
}