Using Google Drive API from a Java Application

785 views
Skip to first unread message

userDSSR via StackOverflow

unread,
Nov 8, 2015, 11:04:08 PM11/8/15
to google-appengin...@googlegroups.com

I have problems writing a local file from my Hard Drive to Google Drive using Java. The end goal is to have the app on GAE and write directly to Google Drive. Based on the literature for Drive API's I have the following construct:

package com.d2d.googledrive;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.ParentReference;


public class GDFileInsert {

private static HttpTransport    httpTransport;
private static String           APPLICATION_NAME        = "my_app_name";
private static String           USER_EMAIL_ADDRESS      = "user...@gmail.com";
private static JacksonFactory   JSON_FACTORY            =  JacksonFactory.getDefaultInstance();
private static String           SERVICE_ACCOUNT_EMAIL   =  "account-1@my_app_name.iam.gserviceaccount.com";


public  static void main(String[] args) throws IOException, GeneralSecurityException {

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();   

    GoogleCredential credential = new GoogleCredential.Builder()
          .setTransport(httpTransport)
          .setJsonFactory(JSON_FACTORY)
          .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
          .setServiceAccountUser(USER_EMAIL_ADDRESS)
          .setServiceAccountScopes(DriveScopes.all())
          .setServiceAccountPrivateKeyFromP12File(
                  new java.io.File("Resources/d2dloads-8d4579d34d46.p12"))
          .build();

      Drive service = new Drive.Builder(httpTransport, JSON_FACTORY, null)
          .setHttpRequestInitializer(credential).setApplicationName(APPLICATION_NAME).build();



    // File's metadata.
    File body = new File();
    body.setTitle("My File Title");
    body.setDescription("My File Description");
    body.setMimeType("text/plain");

    String parentId = "ParentDir";

    // Set the parent folder.
    if (parentId != null && parentId.length() > 0) {
      body.setParents(
          Arrays.asList(new ParentReference().setId(parentId)));
    }

    String filename = "Resources/myfile.txt";

    // File's content.
    java.io.File fileContent = new java.io.File(filename);
    FileContent mediaContent = new FileContent("text/plain", fileContent);
    try {
      File file = service.files().insert(body, mediaContent).execute();

      // Uncomment the following line to print the File ID.
      System.out.println("Inserted File ID: " + file.getId());

    } catch (IOException e) {

      System.out.println("An error occured: " + e);

    }
}


}

When I run the program, it gives me an error as follows:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/api/services/drive/DriveScopes
at com.d2d.googledrive.GDFileInsert.main(GDFileInsert.java:36)

which is basically at ".setServiceAccountScopes(DriveScopes.all())". I have tried various options from using API_KEY to others, but was not successful. I did activate Google Drive API for my Project and also created Service Account Keys, API Keys and OAuth2 keys.

I am not sure what I am doing wrong. Any guidance will help. I have also attached the WEB-INF/Lib jars picture here

..enter image description here



Please DO NOT REPLY directly to this email but go to StackOverflow:
http://stackoverflow.com/questions/33602347/using-google-drive-api-from-a-java-application

userDSSR via StackOverflow

unread,
Nov 9, 2015, 9:54:06 AM11/9/15
to google-appengin...@googlegroups.com

EDIT 2:

@Konqi's suggestion worked for the issue above. Now there is another error of NullPointerException @ "File file = service.files().insert(body, mediaContent).execute()". I have the file defined that needs to be uploaded. Any guidance or suggestions.

Exception in thread "main" java.lang.NullPointerException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)
at com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127)
at com.google.api.client.json.jackson2.JacksonFactory.createJsonParser(JacksonFactory.java:96)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81)
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:88)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:268)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.media.MediaHttpUploader.executeCurrentRequestWithoutGZip(MediaHttpUploader.java:545)
at com.google.api.client.googleapis.media.MediaHttpUploader.executeCurrentRequest(MediaHttpUploader.java:562)
at com.google.api.client.googleapis.media.MediaHttpUploader.executeUploadInitiation(MediaHttpUploader.java:519)
at com.google.api.client.googleapis.media.MediaHttpUploader.resumableUpload(MediaHttpUploader.java:384)
at com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:336)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:418)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at com.d2d.googledrive.GDFileInsert.main(GDFileInsert.java:69)
Reply all
Reply to author
Forward
0 new messages