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

The following examples show how to use com.google.api.services.drive.model.File. These examples are extracted from open source projects. 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 Project: camel-quarkus   Source File: GoogleDriveResource.java    License: 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 2
Source Project: hop   Source File: GoogleDriveFileObject.java    License: 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
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
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 Project: data-transfer-project   Source File: DriveImporter.java    License: 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 6
Source Project: QtAndroidTools   Source File: AndroidGoogleDrive.java    License: 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 7
Source Project: gdx-gamesvcs   Source File: GpgsClient.java    License: 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 8
Source Project: components   Source File: GoogleDrivePutRuntimeTest.java    License: 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 9
@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 10
Source Project: components   Source File: GoogleDriveGetRuntimeTest.java    License: 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 11
Source Project: jdrivesync   Source File: GoogleDriveAdapter.java    License: 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 12
Source Project: narrate-android   Source File: DriveSyncService.java    License: 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 13
Source Project: wildfly-camel   Source File: GoogleDriveIntegrationTest.java    License: 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 14
@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 15
Source Project: science-journal   Source File: GoogleDriveApiImpl.java    License: 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 16
Source Project: jdrivesync   Source File: GoogleDriveAdapter.java    License: 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 17
Source Project: pentaho-kettle   Source File: GoogleDriveFileObject.java    License: 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 18
Source Project: mytracks   Source File: SyncAdapter.java    License: 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 19
Source Project: mytracks   Source File: SyncTestUtils.java    License: 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 20
Source Project: jdrivesync   Source File: GoogleDriveAdapter.java    License: 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 21
Source Project: components   Source File: GoogleDriveUtils.java    License: 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 22
Source Project: jdrivesync   Source File: GoogleDriveAdapter.java    License: 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 Project: components   Source File: GoogleDriveUtils.java    License: Apache License 2.0 5 votes vote down vote up
private String removeResource(String resourceId, boolean useTrash) throws IOException {
    if (useTrash) {
        drive.files().update(resourceId, new File().setTrashed(true)).execute();
    } else {
        drive.files().delete(resourceId).execute();
    }
    return resourceId;
}
 
Example 24
Source Project: jdrivesync   Source File: GoogleDriveWalker.java    License: Apache License 2.0 5 votes vote down vote up
private void walkInternal(SyncDirectory syncDirectory, GoogleDriveAdapter googleDriveAdapter, WalkerVisitor visitor) {
    if (syncDirectory.getRemoteFile().isPresent()) {
        File remoteFile = syncDirectory.getRemoteFile().get();
        List<File> remoteChildren = googleDriveAdapter.listChildren(remoteFile.getId());
        for (File file : remoteChildren) {
            if (googleDriveAdapter.fileNameValid(file)) {
	String relativePath = toRelativePath(file, syncDirectory);
	if (googleDriveAdapter.isDirectory(file)) {
		if (!fileShouldBeIgnored(relativePath, true, file)) {
			SyncDirectory subSyncDirectory = new SyncDirectory(Optional.empty(), Optional.of(file), relativePath, Optional.of(syncDirectory));
			syncDirectory.addChild(subSyncDirectory);
		}
	} else {
		if (!fileShouldBeIgnored(relativePath, false, file)) {
			SyncFile syncFile = new SyncFile(Optional.empty(), Optional.of(file), relativePath, Optional.of(syncDirectory));
			syncDirectory.addChild(syncFile);
		}
	}
}
        }
        WalkerVisitor.WalkerVisitorResult result = visitor.visitDirectory(syncDirectory);
        if (result == WalkerVisitor.WalkerVisitorResult.Continue) {
            Iterator<SyncItem> childrenIterator = syncDirectory.getChildrenIterator();
            while (childrenIterator.hasNext()) {
                SyncItem syncItem = childrenIterator.next();
                if (syncItem instanceof SyncDirectory) {
                    SyncDirectory subSyncDir = (SyncDirectory) syncItem;
                    walkInternal(subSyncDir, googleDriveAdapter, visitor);
                }
                childrenIterator.remove(); //free memory
            }
        }
    } else {
        LOGGER.log(Level.FINE, "Skipping directory '" + syncDirectory.getPath() + "' because remote file is not set.");
    }
}
 
Example 25
Source Project: jdrivesync   Source File: GoogleDriveAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isGoogleAppsDocument(File file) {
	String mimeType = file.getMimeType();
	if (mimeType != null && mimeType.startsWith("application/vnd.google-apps") && !mimeType.equals("application/vnd.google-apps.folder")) {
		LOGGER.log(Level.FINE, "Not touching file " + file.getId() + " because it is a Google Apps document.");
		return true;
	}
	return false;
}
 
Example 26
Source Project: data-transfer-project   Source File: DriveImporter.java    License: 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 27
Source Project: nomulus   Source File: DriveConnectionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateFolderAtRoot() throws Exception {
  when(files.insert(new File()
      .setTitle("title")
      .setMimeType("application/vnd.google-apps.folder")))
          .thenReturn(insert);
  assertThat(driveConnection.createFolder("title", null)).isEqualTo("id");
}
 
Example 28
Source Project: QtAndroidTools   Source File: AndroidGoogleDrive.java    License: 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 29
Source Project: components   Source File: GoogleDrivePutReaderTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 30
Source Project: jdrivesync   Source File: GoogleDriveWalker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void walk(WalkerVisitor walkerVisitor) {
    File remoteRootFile = googleDriveAdapter.getFile("root");
    remoteRootFile = getRemoteRootDir(remoteRootFile);
    java.io.File localRootFile = options.getLocalRootDir().get();
    SyncDirectory rootDirectory = new SyncDirectory(Optional.of(localRootFile), Optional.of(remoteRootFile), "/", Optional.empty());
    walkInternal(rootDirectory, googleDriveAdapter, walkerVisitor);
}