I am trying to run google drive api starter code in my local and it is working fine when it is using com.google.api.client.auth.oauth2.Credential and results in 401 when it is using
com.google.auth.oauth2.GoogleCredentials.
I am a newbie, sorry if this is a stupid question. Please help me, I am trying to upload a file to my drive, it is working with a service account, but the upload is happening to the service account and I don't know how to access the service account files.
Here is the starter code I am using:
package com.google.drive.api.try;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
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.FileList;
import com.google.drive.api.try.write.UploadBasic;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.List;
public class DriveQuickstart {
private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
private static Drive service;
public static void main(String... args) throws IOException {
init();
UploadBasic.uploadBasic();
FileList result = service.files().list().setPageSize(10).setFields("nextPageToken, files(id, name)").execute();
List<File> files = result.getFiles();
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}
}
private static void init() {
try {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME).build();
} catch (Exception e) {
e.printStackTrace();
}
}
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
InputStream in = DriveQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
clientSecrets, DriveScopes.all())
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline").build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
return credential;
}
}
UploadBasic.java
package com.google.drive.api.try.write;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
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.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;
public class UploadBasic {
public static String uploadBasic() throws IOException {
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
.createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Build a new authorized API client service.
Drive service = new Drive.Builder(new NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer)
.setApplicationName("Drive samples").build();
// Upload file photo.jpg on drive.
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
// File's content.
java.io.File filePath = new java.io.File("files/photo.jpg");
// Specify media type and file-path for file.
FileContent mediaContent = new FileContent("image/jpeg", filePath);
try {
File file = service.files().create(fileMetadata, mediaContent).setFields("id").execute();
System.out.println("File ID: " + file.getId());
return file.getId();
} catch (GoogleJsonResponseException e) {
// TODO(developer) - handle error appropriately
System.err.println("Unable to upload file: " + e.getDetails());
throw e;
}
}
}
Related
I am trying to access to user email message from my android through the new gmail api. Google has provided the docs from Gmail api in java, but I am not able to figure it out .
My Code:
Mainactivty.java:
public class MainActivity extends AppCompatActivity {
public static final String TAG = "prince-main-activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button clickme = findViewById(R.id.clickme);
clickme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Gquickstart();
}
});
}
private void Gquickstart(){
GmailQuickstart gmailQuickstart = new GmailQuickstart();
try {
gmailQuickstart.create(getApplicationContext());
} catch (IOException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
}
}
GmailQuickstart.java
package com.novaapps.myapplication;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
/* class to demonstrate use of Gmail list labels API */
public class GmailQuickstart extends AsyncTask<String,Void,String> {
/** Application name. */
private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
/** Directory to store authorization tokens for this application. */
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_LABELS);
private static final String CREDENTIALS_FILE_PATH = "credentials.json";
private static Context context;
public static final String TAG = "nova-GmailQuickstart";
/**
* Creates an authorized Credential object.
* #param HTTP_TRANSPORT The network HTTP Transport.
* #return An authorized Credential object.
* #throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT, Context context) throws IOException {
// Load client secrets.
Log.d(TAG,"IN getCredentials");
InputStream in = context.getAssets().open("credentials.json");
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
Log.d(TAG,"clientSecrets " + String.valueOf(clientSecrets));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
Log.d(TAG,"Flow " + String.valueOf(flow));
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
//returns an authorized Credential object.
Log.d(TAG, String.valueOf(credential));
return credential;
}
public void create(Context context) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
Log.d(TAG,"IN Create Gmail");
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT, context))
.setApplicationName(APPLICATION_NAME)
.build();
// Print the labels in the user's account.
String user = "me";
ListLabelsResponse listResponse = service.users().labels().list(user).execute();
List<Label> labels = listResponse.getLabels();
if (labels.isEmpty()) {
System.out.println("No labels found.");
} else {
System.out.println("Labels:");
for (Label label : labels) {
System.out.printf("- %s\n", label.getName());
}
}
}
#Override
protected String doInBackground(String... strings) {
return null;
}
}
When I try to run this the app crashes,
here is the log:
Process: com.novaapps.myapplication, PID: 22447
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/sun/net/httpserver/HttpServer;
at com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver.getRedirectUri(LocalServerReceiver.java:127)
at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:108)
at com.novaapps.myapplication.GmailQuickstart.getCredentials(GmailQuickstart.java:72)
at com.novaapps.myapplication.GmailQuickstart.create(GmailQuickstart.java:82)
at com.novaapps.myapplication.MainActivity.Gquickstart(MainActivity.java:69)
at com.novaapps.myapplication.MainActivity.access$000(MainActivity.java:42)
at com.novaapps.myapplication.MainActivity$1.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
Moreover how to ask user to signin with his account so i can get the tokens . I still lack knowledge about android and java So some guidence is required
Thanks
P.S: I have created credentials on google developer console
I am trying to run the tutorial google drive api test
package Tests;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
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.FileList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
public class DriveQuickstart {
private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE_METADATA_READONLY);
private static final String CREDENTIALS_FILE_PATH = "credentials.json";
/**
* Creates an authorized Credential object.
* #param HTTP_TRANSPORT The network HTTP Transport.
* #return An authorized Credential object.
* #throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = DriveQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
// Print the names and IDs for up to 10 files.
FileList result = service.files().list()
.setPageSize(10)
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}
}
}
I have almost all jars mentioned and I have downloaded the config.json file. However I get the following error
WARNING: unable to change permissions for owner: C:\Users\aswat\git\bionovaQAnew\tokens
Exception in thread "main" java.lang.NoClassDefFoundError: org/mortbay/jetty/Handler
at com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver$Builder.build(LocalServerReceiver.java:205)
at Tests.DriveQuickstart.getCredentials(DriveQuickstart.java:57)
at Tests.DriveQuickstart.main(DriveQuickstart.java:64)
Caused by: java.lang.ClassNotFoundException: org.mortbay.jetty.Handler
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 3 more
I have tried out multiple answers mentioned in stackoverflow.com/questions/50687434/error-running-spark-main-class-exception-in-thread-thread-0-java-lang-noclas, but it doesnt help me. I have attached my buildpath dependencies as well. Please let me know what the issue is.
I use Ant and eclipse.
After many trials what worked for me was:
Added guava-11.0.2.jar
Removed google api client json 1 2 3 alpha.jar
Re downloaded the credential.json
Started a new project with just the required jars in resource file as shown attached
Good morning. My program wants to communicate with my google drive account. So I took example to see how I can do it. But I have the same error still now. Please help me.
The problem is on this line :
NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
When I'm execute I have this error:
com.google.api.client.http.javanet.NetHttpTransport.(Lcom/google/api/client/http/javanet/ConnectionFactory;Ljavax/net/ssl/SSLSocketFactory;Ljavax/net/ssl/HostnameVerifier;)
My source code:
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
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.FileList;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
public class DriveQuickstart {
static final String oz = org.apache.http.conn.ssl .SSLConnectionSocketFactory.class.getProtectionDomain (). getCodeSource(). getLocation (). getPath ();
private static final String APPLICATION_NAME = "DriveQuickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
// Directory to store user credentials for this application.
private static final java.io.File CREDENTIALS_FOLDER //
= new java.io.File(System.getProperty("user.home"), "credentials");
private static final String CLIENT_SECRET_FILE_NAME = "client_secret.json";
//
// Global instance of the scopes required by this quickstart. If modifying these
// scopes, delete your previously saved credentials/ folder.
//
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
java.io.File clientSecretFilePath = new java.io.File(CREDENTIALS_FOLDER, CLIENT_SECRET_FILE_NAME);
if (!clientSecretFilePath.exists()) {
throw new FileNotFoundException("Please copy " + CLIENT_SECRET_FILE_NAME //
+ " to folder: " + CREDENTIALS_FOLDER.getAbsolutePath());
}
// Load client secrets.
InputStream in = new FileInputStream(clientSecretFilePath);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
clientSecrets, SCOPES).setDataStoreFactory(new FileDataStoreFactory(CREDENTIALS_FOLDER))
.setAccessType("offline").build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static void main(String... args) throws IOException, GeneralSecurityException {
System.out.println("voici le path "+oz);
System.out.println("CREDENTIALS_FOLDER: " + CREDENTIALS_FOLDER.getAbsolutePath());
// 1: Create CREDENTIALS_FOLDER
if (!CREDENTIALS_FOLDER.exists()) {
CREDENTIALS_FOLDER.mkdirs();
System.out.println("Created Folder: " + CREDENTIALS_FOLDER.getAbsolutePath());
System.out.println("Copy file " + CLIENT_SECRET_FILE_NAME + " into folder above.. and rerun this class!!");
return;
}
// 2: Build a new authorized API client service.
NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
// 3: Read client_secret.json file & create Credential object.
Credential credential = getCredentials(HTTP_TRANSPORT);
// 5: Create Google Drive Service.
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) //
.setApplicationName(APPLICATION_NAME).build();
// Print the names and IDs for up to 10 files.
FileList result = service.files().list().setPageSize(10).setFields("nextPageToken, files(id, name)").execute();
List<File> files = result.getFiles();
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}
}
}
This is a jar dependency issue. Update your question with a screenshot of libs folder.
In order to work this please add the below jars in lib if not exists already
google-oauth-client-1.30.5.jar
google-oauth-client-java6-1.30.6.jar
google-oauth-client-jetty-1.30.6.jar
google-api-client-1.30.9.jar
google-http-client-1.34.0.jar
google-http-client-jackson2-1.34.2.jar
google-api-services-drive-v3-rev195-1.25.0.jar
httpclient-4.5.12.jar
Also, add the below lines of code just above where the exception is occurring to see from which jar they are referenced in
System.out.println(NetHttpTransport.class.getProtectionDomain().getCodeSource().getLocation().getPath());
System.out.println(GoogleNetHttpTransport.class.getProtectionDomain().getCodeSource().getLocation().getPath());
NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
use your class package while calling the class
HttpTransport httpTransport = new com.google.api.client.http.javanet.NetHttpTransport();
I hope it will work
According to Google Calendar API Quickstart for java (step 3), we can use
InputStream in = CalendarQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
to parse credentials.json.
However, it only works when running the file outside of Android Studio. Running the CalendarQuickStart.java main method (without running the app) in Android Studio will result nullpointer exception.
I found that using getAsset()is probably a way to get around the problem
InputStream in = context.getAssets().open(CREDENTIALS_FILE_PATH);.
Its' easy to set up asset folders but getting context to work is very tricky.
Here is my file path:
Here is my code:
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
public class CalendarQuickstart extends AppCompatActivity {
private static final String APPLICATION_NAME = "Google Calendar API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(CalendarScopes.CALENDAR_READONLY);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
/**
* Creates an authorized Credential object.
* #param HTTP_TRANSPORT The network HTTP Transport.
* #return An authorized Credential object.
* #throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = CalendarQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
//InputStream in = context.getAssets().open(CREDENTIALS_FILE_PATH);
System.out.println(in);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
// List the next 20 events from the primary calendar.
DateTime now = new DateTime(System.currentTimeMillis());
Events events = service.events().list("primary")
.setMaxResults(20)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
List<Event> items = events.getItems();
if (items.isEmpty()) {
System.out.println("No upcoming events found.");
} else {
System.out.println("Upcoming events");
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
if (start == null) {
start = event.getStart().getDate();
}
System.out.printf("%s (%s)\n", event.getSummary(), start);
}
}
}
}
What is a better way to run the CalendarQuickstart.java in Android Studio?
Is there any sample Java apps that show how to access Big Query using an OAuth service flow. Most of the apps seem to show web and desktop flows.
Thanks
Sure - try something like this (below). More examples of this type of flow here: https://developers.google.com/bigquery/authorization#service-accounts-server
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.Bigquery.Datasets;
import com.google.api.services.bigquery.model.DatasetList;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
public class JavaCommandLineServiceAccounts {
private static final String SCOPE = "https://www.googleapis.com/auth/bigquery";
private static final HttpTransport TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static Bigquery bigquery;
public static void main(String[] args) throws IOException, GeneralSecurityException {
GoogleCredential credential = new GoogleCredential.Builder().setTransport(TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("XXXXXXX#developer.gserviceaccount.com")
.setServiceAccountScopes(SCOPE)
.setServiceAccountPrivateKeyFromP12File(new File("my_file.p12"))
.build();
bigquery = new Bigquery.Builder(TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("BigQuery-Service-Accounts/0.1")
.setHttpRequestInitializer(credential).build();
Datasets.List datasetRequest = bigquery.datasets().list("publicdata");
DatasetList datasetList = datasetRequest.execute();
System.out.format("%s\n", datasetList.toPrettyString());
}
}