I'm having some problems while uploading a .txt file with Google Drive API. Here's my code:
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
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.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class DriveCommandLine {
private static String CLIENT_ID = "client_id";
private static String CLIENT_SECRET = "client_secret";
private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
public static void main(String[] args) throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
.setAccessType("online")
.setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
System.out.println("Please open the following URL in your browser then type the authorization code:");
System.out.println(" " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
//Create a new authorized API client
Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
//Insert a file
File body = new File();
body.setTitle("Document Example");
body.setDescription("This is a test of Google Drive SDK");
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());
}
}
The problem it's in this line:
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
And the errors are:
Exception in thread "main" javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1836)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1794)
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1777)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1296)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1273)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:523)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1087)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:79)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:895)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:299)
at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest.execute(GoogleAuthorizationCodeTokenRequest.java:147)
**at DriveCommandLine.main(DriveCommandLine.java:43)**
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:90)
at sun.security.validator.Validator.getInstance(Validator.java:179)
at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:314)
at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:173)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:186)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1319)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:966)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1262)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1289)
... 10 more
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200)
at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120)
at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104)
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:88)
... 22 more
You cannot use this sample (that is for Google Application based on localhost (client-side)) with methods provided for WebApplication. You need to instantiate a Google Web Application (server-side using HttpServlet) and use the redirect URI for a doGet method to catch automatically the code and exchange data to get the correct Authorization. See OAuth 2.0 and OAuth 2.0 for WebApplication
Related
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
I am trying to upload a text file to my Google Drive account. No matter what, I always encounter an com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
Stacktrace:
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Forbidden",
"reason" : "forbidden"
} ],
"message" : "Forbidden"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:423)
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 chatterjee.sandeep.javabase.miscellaneous.DriveCommandLine.main(DriveCommandLine.java:69)
Here is line 69 of DriveCommandLine.java
File file = service.files().insert(body, mediaContent).execute();
Complete Code:
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
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.JsonFactory;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class DriveCommandLine {
private static String CLIENT_ID = "CLIENT_ID";
private static String CLIENT_SECRET = "CLIENT_SECRET";
private static String REDIRECT_URI = "REDIRECT_URI";
public static void main(String[] args) throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(DriveScopes.DRIVE_FILE)).setAccessType("online")
.setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI)
.build();
System.out
.println("Please open the following URL in your browser then type the authorization code:");
System.out.println(" " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
GoogleTokenResponse response = flow.newTokenRequest(code)
.setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential()
.setFromTokenResponse(response);
// Create a new authorized API client
Drive service = new Drive.Builder(httpTransport, jsonFactory,
credential).build();
// Insert a file
File body = new File();
body.setTitle("My document");
body.setDescription("A test document");
body.setMimeType("text/plain");
java.io.File fileContent = new java.io.File(
"/path/to/TextFile.txt");
FileContent mediaContent = new FileContent("text/plain", fileContent);
File file = service.files().insert(body, mediaContent).execute();
System.out.println("File ID: " + file.getId());
}
}
I have the following jars in my project build path:
commons-logging-1.1.1.jar
google-api-client-1.18.0-rc.jar
google-api-client-android-1.18.0-rc.jar
google-api-client-appengine-1.18.0-rc.jar
google-api-client-gson-1.18.0-rc.jar
google-api-client-jackson2-1.18.0-rc.jar
google-api-client-java6-1.18.0-rc.jar
google-api-client-servlet-1.18.0-rc.jar
google-api-services-drive-v1-rev123-1.18.0-rc.jar
google-http-client-1.18.0-rc.jar
google-http-client-android-1.18.0-rc.jar
google-http-client-appengine-1.18.0-rc.jar
google-http-client-gson-1.18.0-rc.jar
google-http-client-jackson2-1.18.0-rc.jar
google-http-client-jdo-1.18.0-rc.jar
google-oauth-client-1.18.0-rc.jar
google-oauth-client-appengine-1.18.0-rc.jar
google-oauth-client-java6-1.18.0-rc.jar
google-oauth-client-jetty-1.18.0-rc.jar
google-oauth-client-servlet-1.18.0-rc.jar
gson-2.1.jar
httpclient-4.0.3.jar
httpcore-4.0.1_1.jar
jackson-core-2.1.3.jar
jdo2-api-2.3-eb.jar
jetty-util-6.1.26.jar
jsr305-1.3.9.jar
transaction-api-1.1-rev-1.jar
At present I have two projects set up with Drive API enabled.
Now where do I properly set up the permissions to resolve this issue?
Also, what am I doing wrong here?
I had the same issue, I did the following change and it resolved the issue
1) Added SheetsScopes.DRIVE to the scopes to be given in authorize()
private static final List<String> SCOPES =
Arrays.asList(SheetsScopes.SPREADSHEETS,SheetsScopes.DRIVE);
2) Created a new directory, so that next time I run it, it will authenticate and save the credential to the newly created directory
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), ".credentials/2/sheets.googleapis.com-java-quickstart.json");
This issue happened when you change SCOPE and proceed to work with the old token. Just remove StoredCredential file.Idea
After a long time searching, I found this answer hidden in the search engine:
Change the line where you define scopes to:
private static final List<String> SCOPES = Arrays.asList(GmailScopes.MAIL_GOOGLE_COM);
https://stackoverflow.com/a/38599382/1317559
I just had this problem and it is likely that you have created the credential file using a scope that does not allow inserting a file. Remove the credential file and re-run.
For me issue was SCOPES, it was set to SheetsScopes.SPREADSHEETS_READONLY.
So I changed it to SheetsScopes.SPREADSHEETS, deleted the Token folder in the project directory and run the program again and it worked.
Been having same quota errors for months. Tried everything. It looks like problem on Google side.
Among all google products, Calendar API does not have any way to support their team. If anyone knows or have been able to contact Google team about Calendar API, let us know!
I had the same problem but in my case resolve this with:
private static final List<String> SCOPES =
Arrays.asList(DriveScopes.DRIVE);
from DriveScopes
and also create a new directory
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/2/drive-java-quickstart.json");
and i solved the problem
For me the problem was that the url was http... and it should be https...
Make sure to use DriveScopes.DRIVE for allowed SCOPE:
private static final List SCOPES = Collections.singletonList(DriveScopes.DRIVE);
Make sure to reset token directory path as below:
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT,
JSON_FACTORY, clientSecrets, SCOPES)
//.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setDataStoreFactory(new MemoryDataStoreFactory())
.setAccessType("offline")
.build();
Othewise it will always use the cached version.
I have downloaded the sample command line program for Youtube Analytics api and Youtube Data Api v3 and imported in eclipse.
So below I have mentioned the code for my OAuth 2.0 implementation class:
package com.google.api.services.samples.youtube.cmdline;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.StoredCredential;
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.http.HttpTransport;
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.DataStore;
import com.google.api.client.util.store.FileDataStoreFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
/**
* Shared class used by every sample. Contains methods for authorizing a user and caching credentials.
*/
public class Auth {
/**
* Define a global instance of the HTTP transport.
*/
public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
/**
* Define a global instance of the JSON factory.
*/
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
/**
* This is the directory that will be used under the user's home directory where OAuth tokens will be stored.
*/
private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials";
/**
* Authorizes the installed application to access user's protected data.
*
* #param scopes list of scopes needed to run youtube upload.
* #param credentialDatastore name of the credential datastore to cache OAuth tokens
*/
public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {
// Load client secrets.
Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json"));
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);
// Checks that the defaults have been replaced (Default = "Enter X here").
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println(
"Enter Client ID and Secret from https://code.google.com/apis/console/?api=youtube"
+ "into src/main/resources/client_secrets.json");
System.exit(1);
}
// This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
.build();
// Build the local server and bind it to port 8080
LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
// Authorize.
return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}
}
and here are the warnings and errors that i get:
Dec 05, 2014 3:35:45 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\admin\.oauth-credentials
Dec 05, 2014 3:35:45 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\admin\.oauth-credentials
2014-12-05 15:35:45.592:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2014-12-05 15:35:45.592:INFO::jetty-6.1.26
2014-12-05 15:35:45.622:WARN::failed SocketConnector#localhost:8080: java.net.BindException: Address already in use: JVM_Bind
2014-12-05 15:35:45.622:WARN::failed Server#532760d8: java.net.BindException: Address already in use: JVM_Bind
2014-12-05 15:35:45.622:INFO::Stopped SocketConnector#localhost:8080
IOException: java.net.BindException: Address already in use: JVM_Bind
java.io.IOException: java.net.BindException: Address already in use: JVM_Bind
at com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver.getRedirectUri(LocalServerReceiver.java:107)
at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:76)
at com.google.api.services.samples.youtube.cmdline.Auth.authorize(Auth.java:75)
at com.google.api.services.samples.youtube.cmdline.analytics.YouTubeAnalyticsReports.main(YouTubeAnalyticsReports.java:71)
Caused by: java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at org.mortbay.jetty.bio.SocketConnector.newServerSocket(SocketConnector.java:80)
at org.mortbay.jetty.bio.SocketConnector.open(SocketConnector.java:73)
at org.mortbay.jetty.AbstractConnector.doStart(AbstractConnector.java:283)
at org.mortbay.jetty.bio.SocketConnector.doStart(SocketConnector.java:147)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.Server.doStart(Server.java:235)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver.getRedirectUri(LocalServerReceiver.java:104)
... 3 more
i am stuck very badly...
Any help regarding this will be appreciated...
I am embarrassed that I'm simply failing with an example piece of code, but I'll blame it on the fact that it is late...
I have taken a copy and paste of: https://developers.google.com/gmail/api/quickstart/quickstart-java
and downloaded the client libraries: https://code.google.com/p/google-api-java-client/
and https://developers.google.com/api-client-library/java/apis/gmail/v1
When I run the sample, I get the following exception:
Exception in thread "main" java.lang.IllegalArgumentException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:76)
at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.getDetails(GoogleClientSecrets.java:82)
at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow$Builder.<init>(GoogleAuthorizationCodeFlow.java:195)
at com.emailreply.musterion.GmailApiQuickstart.main(GmailApiQuickstart.java:40)
Googling, I can't find a simple answer, so am assuming stupidity or a library missing/incorrect.
The libraries as I have them are:
/libs/commons-logging-1.1.1.jar
/libs/google-api-client-1.19.0.jar
/libs/google-api-client-android-1.19.0.jar
/libs/google-api-client-appengine-1.19.0.jar
/libs/google-api-client-gson-1.19.0.jar
/libs/google-api-client-jackson2-1.19.0.jar
/libs/google-api-client-java6-1.19.0.jar
/libs/google-api-client-servlet-1.19.0.jar
/libs/google-http-client-1.19.0.jar
/libs/google-http-client-android-1.19.0.jar
/libs/google-http-client-appengine-1.19.0.jar
/libs/google-http-client-gson-1.19.0.jar
/libs/google-http-client-jackson2-1.19.0.jar
/libs/google-http-client-jdo-1.19.0.jar
/libs/google-oauth-client-1.19.0.jar
/libs/google-oauth-client-appengine-1.19.0.jar
/libs/google-oauth-client-java6-1.19.0.jar
/libs/google-oauth-client-jetty-1.19.0.jar
/libs/google-oauth-client-servlet-1.19.0.jar
/libs/gson-2.1.jar
/libs/httpclient-4.0.1.jar
/libs/httpcore-4.0.1.jar
/libs/jackson-core-2.1.3.jar
/libs/jdo2-api-2.3-eb.jar
/libs/jetty-6.1.26.jar
/libs/jetty-util-6.1.26.jar
/libs/jsr305-1.3.9.jar
/libs/transaction-api-1.1.jar
google-api-services-gmail-v1-rev10-1.19.0.jar
The example mentioned above:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
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.jackson2.JacksonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.ListThreadsResponse;
import com.google.api.services.gmail.model.Thread;
public class GmailApiQuickstart {
// Check https://developers.google.ciom/gmail/api/auth/scopes for all available scopes
private static final String SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
private static final String APP_NAME = "Gmail API Quickstart";
// Email address of the user, or "me" can be used to represent the currently authorized user.
private static final String USER = "me";
// Path to the client_secret.json file downloaded from the Developer Console
private static final String CLIENT_SECRET_PATH = "./client_secret.json";
public static void main (String [] args) throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new BufferedReader(new InputStreamReader(GmailApiQuickstart.class.getResourceAsStream(CLIENT_SECRET_PATH))));
// Allow user to authorize via url.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
.setAccessType("online")
.setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build();
System.out.println("Please open the following URL in your browser then type the authorization code:\n" + url);
// Read code entered by user.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
// Generate Credential using retrieved code.
GoogleTokenResponse response = flow.newTokenRequest(code)
.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential()
.setFromTokenResponse(response);
// Create a new authorized Gmail API client
Gmail service = new Gmail.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(APP_NAME).build();
// Retrieve a page of Threads; max of 100 by default.
ListThreadsResponse threadsResponse = service.users().threads().list(USER).execute();
List<Thread> threads = threadsResponse.getThreads();
// Print ID of each Thread.
for (Thread thread : threads) {
System.out.println("Thread ID: " + thread.getId());
}
}
}
I replaced the reference to CLIENT_SECRET_PATH with:
new BufferedReader(new InputStreamReader(GmailApiQuickstart.class.getResourceAsStream(CLIENT_SECRET_PATH)))
for no other reason than to try something different. It does work and reads the file correctly.
Any ideas?
Right, after some more research (asking a colleague/genius), I found the problem. Basically the GoogleClientSecrets object was not being properly bound with the information from my client_secrets.json file. This meant that during authentication, objects were null resulting in the IllegalArgumentException.
So the original file which looked like this:
{
"private_key_id": "zzz",
"private_key": "-----BEGIN PRIVATE KEY-----\nxyz\n-----END PRIVATE KEY-----\n",
"client_email": "1234#developer.gserviceaccount.com",
"client_id": "1wdfghyjmp.apps.googleusercontent.com",
"type": "service_account"
}
was edited to look like this:
{
"web" : {
"private_key_id": "zzz",
"private_key": "-----BEGIN PRIVATE KEY-----\nxyz\n-----END PRIVATE KEY-----\n",
"client_email": "1234#developer.gserviceaccount.com",
"client_id": "1wdfghyjmp.apps.googleusercontent.com",
"type": "service_account"
}
}
This allowed me to progress through the code with authentication.
Hope this helps.
here is a working example of non-interactive auth for Google Non-interactive authorization with Google OAuth2
the problem is not in "web" tag in the client json, but rather in the fact that their example is for web authentication while their suggested way of generating credentials is for non-interactive "service account". they have multiple problems with their documentation.
I'm trying to upload file to my Google drive Account using Java. The file is uploaded but i'm getting an warning: WARNING: Application name is not set. Call Builder#setApplicationName.
Code is
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
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.JsonFactory;
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;
public class UploadFileGoogleDrive {
private static String CLIENT_ID = "*****";
private static String CLIENT_SECRET = "******";
private static String REDIRECT_URI = "****";
public static void main(String[] args) throws IOException{
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
.setAccessType("online")
.setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
System.out.println("Please open the following URL in your browser then type the authorization code:");
System.out.println(" " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
//Create a new authorized API client
Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
//Insert a file
File body = new File();
body.setTitle("My document");
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());
}
}
The Output is
May 24, 2014 11:59:14 AM com.google.api.client.googleapis.services.AbstractGoogleClient
WARNING: Application name is not set. Call Builder#setApplicationName.
File ID: 1Ze77mqHtKWDU3eVljATlHQ0U
The Google APIs Client Library for Java strongly encourages you to set an application name when constructing your clients, for use when troubleshooting requests against our server logs. You can see an example on how to set the application name in the Google Drive Java command line sample.