So I followed this tutorial to make a basic Picasawebalbums Api app. I got the tutorial here https://developers.google.com/picasa-web/docs/2.0/developers_guide_java
I had problems described here Create PicasawebService and here Error while using PicasawebService with GAE and here upload image to Picasa using picasawebservice in android
I solved the classNotFoundException and now have an authenticationException. I found some questions about that but none of them helped.
stack trace
Exception in thread "main" com.google.gdata.util.AuthenticationException: Error authenticating (check service name)
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthException(GoogleAuthTokenFactory.java:688)
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthToken(GoogleAuthTokenFactory.java:560)
at com.google.gdata.client.GoogleAuthTokenFactory.setUserCredentials(GoogleAuthTokenFactory.java:397)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:364)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:319)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:303)
at duh.Test.main(Test.java:37)
Here is my code
public static void main(String args[]) throws IOException, ServiceException, AuthenticationException{
PicasawebService myService = new PicasawebService(APP_NAME);
myService.setConnectTimeout(60000);
myService.setReadTimeout(60000);
myService.setUserCredentials(EMAIL, PASSWORD);
URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/samdup123?kind=album");
UserFeed myUserFeed = myService.getFeed(feedUrl, UserFeed.class);
for(AlbumEntry myAlbum : myUserFeed.getAlbumEntries()){
System.out.println(myAlbum.getTitle().getPlainText());
}
}
}
And my imports
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gdata.client.*;
import com.google.gdata.client.photos.*;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.*;
import com.google.gdata.data.media.*;
import com.google.gdata.data.photos.*;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
Line 37 from the stack trace points to myService.setUserCredentials(EMAIL, PASSWORD);
It seems like I need to drop this code entirely and use OAuth2 to get authenticated. I have read about that but it is very complicated reading and I have no idea what to use for my application. I found this code
SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
File p12 = new File("D:\\cgi\\RemedyClientTest\\src\\main\\resources\\RemedyClient-b04b4c2d956c.p12");
factory = FeedURLFactory.getDefault();
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
String [] SCOPESArray= {"https://spreadsheets.google.com/feeds", "https://spreadsheets.google.com/feeds/spreadsheets/private/full", "https://docs.google.com/feeds"};
final List SCOPES = Arrays.asList(SCOPESArray);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("1088335521358-ijasu5h7kauqbja6hih91l2c23amv7ft#developer.gserviceaccount.com")
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(p12)
.build();
service = new SpreadsheetService("Main");
service.setOAuth2Credentials(credential);
But I don't know how to 'translate' that to PicasawebAlbums. I have tried but fell short because I have no idea what jar files to import.
Am i right to assume that my problem is that I need to use Oauth2? Is there anything else I should use? If someone has a working application can you show me all of the imports you have because some of mine seem to be outdated and replaced by others and its all very confusing.
Related
I am trying to upload an mp4 file to my youtube channel using the YouTube Data API, however, I keep getting a 401 Unauthorized back.
Using the google console cloud I created an (unrestricted) API key. Afterwards, I enabled YouTube Data API v3
I then copied the java code snippet from the use cases documentation for making a Video.Insert call to their services.
The things I changed from the snippet (required):
I used the aforementioned API key to replace "YOUR_API_KEY"
And also replaced new File("YOUR_FILE") for obvious reasons. The file is a 17MB mp4 file.
Because the package provided with the snippet no longer comes with com.google.api.client.json.jackson2.JacksonFactory; Following this solution I included the dependency:
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
<version>1.29.2</version>
</dependency>
And I replaced JacksonFactory.getDefaultInstance() with new JacksonFactory()
Finally, as youtubeService.videos().insert(args) doesn't support a string as its first argument I replaced the string with a List.of() of the CSV string. I've also tried a List with each of the comma-seperated strings as items in the list but that doesn't seem to change the outcome either.
This results in the following request: https://youtube.googleapis.com/upload/youtube/v3/videos?key=MyKeyAware&part=snippet&part=status&uploadType=resumable
For good measure, here are the relevant dependencies I'm using (excluding the aforementioned dependency):
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.35.1</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-youtube</artifactId>
<version>v3-rev20220612-1.32.1</version>
</dependency>
I would really appreciate some help as I've been struggling with this issue for a while now!
Code:
package nl.phi.ysg.service.YoutubeApi;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.InputStreamContent;
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.youtube.YouTube;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoSnippet;
import com.google.api.services.youtube.model.VideoStatus;
import org.springframework.core.io.ClassPathResource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
public class YoutubeApiServiceImpl implements YoutubeApiService {
private static final String DEVELOPER_KEY = "...";
private static final String APPLICATION_NAME = "YSG";
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
/**
* Build and return an authorized API client service.
*
* #return an authorized API client service
* #throws GeneralSecurityException, IOException
*/
public static YouTube getService() throws GeneralSecurityException, IOException {
final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
return new YouTube.Builder(httpTransport, JSON_FACTORY, null).setApplicationName(APPLICATION_NAME).build();
}
public static void main(String[] args) throws GeneralSecurityException, IOException, GoogleJsonResponseException {
YouTube youtubeService = getService();
// Define the Video object, which will be uploaded as the request body.
Video video = new Video();
// Add the snippet object property to the Video object.
VideoSnippet snippet = new VideoSnippet();
snippet.setCategoryId("22");
snippet.setDescription("Description of uploaded video.");
snippet.setTitle("Test video upload.");
video.setSnippet(snippet);
// Add the status object property to the Video object.
VideoStatus status = new VideoStatus();
status.setPrivacyStatus("private");
video.setStatus(status);
File mediaFile = new ClassPathResource("test/test.mp4").getFile();
InputStreamContent mediaContent = new InputStreamContent("application/octet-stream", new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());
// Define and execute the API request
YouTube.Videos.Insert request = youtubeService.videos().insert(List.of("snippet,status"), video, mediaContent);
Video response = request.setKey(DEVELOPER_KEY).execute();
System.out.println(response);
}
}
It's unclear from your question but the error indicates that you're not including User authentication (OAuth) and this is required by the YouTube API:
See the Quickstart specifically creating OAuth client ID in step 2b.
The API key is used to authenticate your app.
The OAuth2 client ID is used to authenticate human users.
I am using a service account to access google doc files of users in my enterprise google account using impersonation.
See:
https://developers.google.com/drive/api/v3/about-auth#OAuth2Authorizing
So far so good.
Then, I need to download contents of Google Docs.
When calling Google Drive API to download the contents of a Google Doc, the documentation says to run the following:
https://developers.google.com/drive/api/v3/manage-downloads
Here is a java program that should reproduce the problem:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.SecurityUtils;
import com.google.api.services.drive.Drive;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
public class FetchGoogleDocContentsWithServiceAccount {
static int readTimeout = 60000;
static int connectTimeout = 60000;
static String serviceAccountId = "";
static String serviceAccountEmail = "";
static String serviceAccountPrivateKeyFile = "";
static String serviceAccountPrivateKeyFilePassword = "";
static String fileId = "";
static JacksonFactory jacksonFactory = new JacksonFactory();
static NetHttpTransport httpTransport = new NetHttpTransport();
static List<String> googleScopeList = Arrays.asList("https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/admin.directory.group.readonly",
"https://www.googleapis.com/auth/admin.directory.user.alias.readonly",
"https://www.googleapis.com/auth/admin.directory.group", "https://www.googleapis.com/auth/admin.directory.user",
"https://www.googleapis.com/auth/drive");
public static void main(String[] args) throws Exception {
Drive drive = (new Drive.Builder(httpTransport,
jacksonFactory,
getRequestInitializer(getGoogleCredentials())))
.setApplicationName("Sample app").build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
drive.files().export(fileId, "application/vnd.google-apps.document")
.executeMediaAndDownloadTo(baos);
System.out.println(baos.toString("UTF-8"));
}
public static HttpRequestInitializer getRequestInitializer(final GoogleCredential requestInitializer) {
return httpRequest -> {
requestInitializer.initialize(httpRequest);
httpRequest.setConnectTimeout(readTimeout);
httpRequest.setReadTimeout(connectTimeout);
};
}
public static GoogleCredential getGoogleCredentials() {
GoogleCredential credential;
try {
GoogleCredential.Builder b = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jacksonFactory).setServiceAccountId(serviceAccountId)
.setServiceAccountPrivateKey(SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
new FileInputStream(new File(serviceAccountPrivateKeyFile)), serviceAccountPrivateKeyFilePassword,
"privatekey", serviceAccountPrivateKeyFilePassword))
.setServiceAccountScopes(googleScopeList);
if (serviceAccountEmail != null) {
b = b.setServiceAccountUser(serviceAccountEmail);
}
credential = b.build();
} catch (IOException | GeneralSecurityException e1) {
throw new RuntimeException("Could not build client secrets", e1);
}
return credential;
}
}
When I have performed this operation, we are seeing that the viewedByMeTime field is actually being updated as the impersonated user.
This is not good, because now people think someone might have stolen access to their account. They are going to open tickets with the security team.
Is this expected? How can I make this stop? Is there another method in the API I can call to download the google docs without updating this timestamp?
Also opened a ticket on the github for the google drive java sdk: https://github.com/googleapis/google-api-java-client-services/issues/3160
Updating the viewedByMeTime field upon calling the endpoint is indeed intended behaviour. Any action performed through the API is considered the same way as if the user did that action manually (i.e. that field would be updated too when the user visits the document through the UI).
By using domain-wise delegation (or "user impersonation"), you have no way to avoid this issue.
The only workaround would be to give the service account access to this file, and let it export the file without domain-wide delegation. The viewedByMeTime field will be updated only for the service account itself, but not for the original owner of that file (or any other user having access to it).
I'm using Google API in Java and have the following code snippets.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
import java.lang.Object;
import java.util.ArrayList;
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.Drive.Files;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
public class DriveQuickstart {
private static final String APPLICATION_NAME = "DriveQuickstart";
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 = "C:/Quickstart/src/main/resources/client_secret.json";
// * Creates an authorized Credential object.
// * #param HTTP_TRANSPORT The network HTTP Transport.
// * #return An authorized Credential object.
// * #throws IOException If the client_secret.json file cannot be found.
// */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = new FileInputStream(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 {
try
{
// Build a new authorized API client service.
System.out.println("This is a test line");
//declare final variable NetHttpTransport and GoogleNetHttpTransport from import statements
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
System.out.println("This is the second test line");
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
System.out.println("This is the third test line");
// Print the names and IDs for 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());
}
}
Drive.Files var1 = service.files();
System.out.println("var1 = " + var1.toString());
Drive.Files.List var2 = var1.list();
if (var2 == null)
System.out.println("null");
else {
System.out.printf("Var2 size is: %d\n", var2.size() );
}
//iterate through map and print results
}
catch(Exception e){
System.out.println("error");
}
System.out.println("This is the fourth test line");
}
}
}
To go more into detail. I'm using a somewhat unconventional method to try it. I'm using only command line to run (no IDEs, no gradle).
Here is a link to an ss with my output in command prompt.
cmd output
Assuming that I am actually accessing the metadata in Google Drive, and that the Drive.Files is nested inside an Abstract Map (java.util.AbstractMap), I should be able to return the size of the map to get an idea of where it it searching by how many files it is returning.
I'm not sure what is going on. First time I compile and run, I get the tab opening in chrome asking for permission to gain access to metadata to drive.
Second time, it gives the "WARNING: unable to change permissions for everybody: " errors.
On top of that, var1 ('set to service.files()') returns com.google.api.services.drive.Drive$Files#458ad742 when using toString().
The subclass service.files().list() assigned to var2 should return a list of files in my Google Drive, but apparently it is not doing so.
I may be misunderstanding a lot of stuff, so bear with me. Thanks for the help.
In case people ask, I have tried the tutorial here
https://developers.google.com/drive/api/v3/quickstart/java
It opened the tab to ask for metadata access to google drive on whichever google account I selected.
storedcredential
So from that alone, I (think) connected to Google Drive.
However, the default code that is supposed to list the names and ids of 10 files doesn't do anything.
How am I running the program:
Here is the batch file that I'm using to compile and run the code in cmd.
jar cfe DriveQuickstart.jar Quickstart DriveQuickstart.class
javac -cp ./* DriveQuickstart.java
java -cp ./* DriveQuickstart
For some reason I don't know/understand, this was the only way that wouldn't return methods from the imported jar files not existing.
Familiarize yourself with the Java Quickstart to see how to get the results of the API calls.
Problems
1 - setPermissionsToOwnerOnly
I'm not sure what is going on. First time I compile and run, I get the tab opening in chrome asking for permission to gain access to metadata to drive. Second time, it gives the "WARNING: unable to change permissions for everybody: " errors.
This seems to be related to this issue. It could mean that the folder you are using to run your code from has different permissions than expected.
Does this happen if you place your code on your Desktop (as example) and then run it from there?
2 - toString()
On top of that, var1 ('set to service.files()') returns com.google.api.services.drive.Drive$Files#458ad742 when using toString(). The subclass service.files().list() assigned to var2 should return a list of files in my Google Drive, but apparently it is not doing so.
This weird looking string is how Java prints out an instance of a class.
com.google.api.services.drive.Drive$Files#458ad742
<NAMESPACE>$<CLASS>#<HASHCODE>
The fact that the toString method prints this out means that this method wasn't overwritten for this specific Class, so its calling the general Object.toString() method.
To print out what you want to see, try the nested methods.
I have client/server application. The server side must access a Spreadsheet on my own Google Drive.I make a test class to try to access to the spreadsheet list:
package com.eng.app;
import java.io.File;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.util.ServiceException;
public class TestGoogleCredential {
public static void main(String[] args) throws IOException,
InterruptedException, GeneralSecurityException, URISyntaxException, ServiceException {
List<String> SCOPES = Arrays
.asList("https://spreadsheets.google.com/feeds");
final HttpTransport TRANSPORT = new NetHttpTransport();
final JsonFactory JSON_FACTORY = new JacksonFactory();
File cert = new File(Credential.class.getClassLoader()
.getResource("<the_file>.p12").toURI());
HttpTransport transport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(<email-address>)
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(cert).build();
SpreadsheetService service = new SpreadsheetService("Inertia");
service.setOAuth2Credentials(credential);
String urlString = "https://spreadsheets.google.com/feeds/spreadsheets/private/full";
URL SPREADSHEET_FEED_URL = new URL(urlString);
// istantiate the feed to the spreadsheets
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,SpreadsheetFeed.class);
// the list of all spreadsheets
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
System.out.println(feed.getEntries().size());
// select the particular spreadsheet on Inertia Ontology
for (SpreadsheetEntry spreadsheetEntry : spreadsheets) {
System.out.println("founded");
}
}
}
But when I run the code the size is 0 and no spreadsheet is printed out.
I have also make another test coding a program that access (on localhost) the Spreadsheet list using my Google Credential instead the OAuth2 authorization and it works well (it prints out all my spreadsheet on my Google Drive).
service.setUserCredentials(username, password); //My personal Google Account
NB: when I deploy on a remote server the test-program with My personal Google Credential (not OAuth2), it was blocked by Google for security policies.
Please any ideas?
Thank you
try to modify this snippet
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("google-dev-console-email-address")
.setServiceAccountUser("your-gmail")
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(cert).build();
I'm just toying around with the google drive api (cloud storage) and figuring out how things work, I wrote some code in play framework where in global.java onStart access to the drive is gained and a test document is written to the drive. Locally this works fine but when I deploy my code to a new CloudBees app and visit the app I get this error in my log and I just can't figure out how to debug it:
Play server process ID is 7454
Oops, cannot start the server.
#6eonea90e: Cannot init the Global object
at play.api.WithDefaultGlobal$$anonfun$play$api$WithDefaultGlobal$$globalInstance$1.apply(Application.scala:57)
at play.api.WithDefaultGlobal$$anonfun$play$api$WithDefaultGlobal$$globalInstance$1.apply(Application.scala:51)
at play.utils.Threads$.withContextClassLoader(Threads.scala:18)
at play.api.WithDefaultGlobal$class.play$api$WithDefaultGlobal$$globalInstance(Application.scala:50)
at play.api.DefaultApplication.play$api$WithDefaultGlobal$$globalInstance$lzycompute(Application.scala:383)
at play.api.DefaultApplication.play$api$WithDefaultGlobal$$globalInstance(Application.scala:383)
at play.api.WithDefaultGlobal$class.global(Application.scala:66)
Link to complete CloudBees log
This is the code of Global.java:
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 com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.FileList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import play.*;
import play.Logger;
public class Global extends GlobalSettings {
private static String CLIENT_ID = "595172328396-l4kpto8ip9fpaea0k2987eeq8f42bged.apps.googleusercontent.com";
private static String CLIENT_SECRET = "EvTUvAodjGx2eW_d3k8oy8Fb";
private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
#Override
public void onStart(Application app) { try{
Logger.info("Application has started");
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(jsonFactory).setTransport(httpTransport).build()
.setRefreshToken("1/MZ4GTNA_HMbOcKDSqp6ymSd11dlkgxoMXxfWwhwMJRg").setAccessToken("ya29.AHES6ZQk7NDC-OCba7_yANc_uqWPLwDLl95TlT_DXgkLqrr6qmyLRw");;
//Create a new authorized API client
Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
//Insert a file
File body = new File();
body.setTitle("New 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();
Logger.info("List of stuff: " + service.children().toString());
Logger.info("File ID: " + file.getId()); }catch (IOException ex) {}
}
}
The google access token is only good for 1 hour. It does not seem as if you are actually requesting an access token with your refresh token... Instead it seems like you are setting one that was already issued.
You need to request an access token be fetched (using the refresh token)
The "fun" is that once you use the refresh token to generate a new access token, the old ones are invalidated... Or at least that is the experience I have found...