I am having trouble connecting to the Drive API with my generated service account. I followed the list of instructions on this link page . However, when I run my code, I get a null pointer exception when it downloads my file to my disk. I'm not sure what I'm doing wrong here. My goal is to create a command line application that I can use to download files to my disk without any user interaction. My code is below
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.*;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
public class DomainAuth {
private static final String SERVICE_ACCOUNT_EMAIL = "972752586307-ecmn7ckdt2o1s3h37canak97d9pa11b7@developer.gserviceaccount.com";
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "mykey2.p12";
public static void main(String[] args) {
try {
Drive service = getDriveService(SERVICE_ACCOUNT_EMAIL);
File body = new File();
body.setTitle("My document3");
body.setDescription("A test document");
body.setMimeType("text/plain");
java.io.File fileContent = new java.io.File("document.txt");
FileContent mediaContent = new FileContent("text/plain", fileContent);
File file = service.files().insert(body, mediaContent).execute();
System.out.println("File ID: " + file.getId());
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Drive getDriveService(String userEmail) throws GeneralSecurityException,
IOException {
java.io.File key = new java.io.File("key.p12");
System.out.println(key.getAbsolutePath());
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Arrays.asList(DriveScopes.DRIVE))
.setServiceAccountUser(userEmail)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
return service;
}
}
source
share