I try to use google drive api v3 to download file in java with this code i get it from github from this link this link of java file in github
package drive.sample;
import ...
public class MainActivity extends AppCompatActivity {
private static ByteArrayOutputStream downloadFile(String realFileId) throws IOException{
/* Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity for
guides on implementing OAuth2 for your application.*/
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();
try {
OutputStream outputStream = new ByteArrayOutputStream();
service.files().get(realFileId)
.executeMediaAndDownloadTo(outputStream);
return (ByteArrayOutputStream) outputStream;
}catch (GoogleJsonResponseException e) {
// TODO(developer) - handle error appropriately
System.err.println("Unable to move file: " + e.getDetails());
throw e;
}
}
}
// [END drive_download_file]
But when run app it show me this error
Error : type of HttpCredentialsAdapter (com. google . auth.Credentials) is erroneous
How i can solve this problem ?
Related
I am developing Android app that show solves math equation using google vision api and wolfram alpha api in java but I take error is that cloud vision api request failed.Check logs for details.How can I fix this error. I need your help for my graduation project. Please help me.
private void callCloudVision(final Bitmap bitmap) throws IOException {
// Do the real work in an async task, because we need to use the network anyway
new AsyncTask<Object, Void, String>() {
#Override
protected String doInBackground(Object... params) {
try {
Log.e("Line 255:", "This line has been executed");
HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
VisionRequestInitializer requestInitializer =
new VisionRequestInitializer(CLOUD_VISION_API_KEY) {
/**
* We override this so we can inject important identifying fields into the HTTP
* headers. This enables use of a restricted cloud platform API key.
*/
#Override
protected void initializeVisionRequest(VisionRequest<?> visionRequest)
throws IOException {
super.initializeVisionRequest(visionRequest);
String packageName = getPackageName();
visionRequest.getRequestHeaders().set(ANDROID_PACKAGE_HEADER, packageName);
String sig = PackageManagerUtils.getSignature(getPackageManager(), packageName);
visionRequest.getRequestHeaders().set(ANDROID_CERT_HEADER, sig);
}
};
Vision.Builder builder = new Vision.Builder(httpTransport, jsonFactory, null);
builder.setVisionRequestInitializer(requestInitializer);
Vision vision = builder.build();
BatchAnnotateImagesRequest batchAnnotateImagesRequest =
new BatchAnnotateImagesRequest();
batchAnnotateImagesRequest.setRequests(new ArrayList<AnnotateImageRequest>() {{
AnnotateImageRequest annotateImageRequest = new AnnotateImageRequest();
// Add the image
Image base64EncodedImage = new Image();
// Convert the bitmap to a JPEG
// Just in case it's a format that Android understands but Cloud Vision
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
byte[] imageBytes = byteArrayOutputStream.toByteArray();
// Base64 encode the JPEG
base64EncodedImage.encodeContent(imageBytes);
annotateImageRequest.setImage(base64EncodedImage);
// add the features we want
annotateImageRequest.setFeatures(new ArrayList<Feature>() {{
Feature textDetection = new Feature();
textDetection.setType("TEXT_DETECTION");
add(textDetection);
}});
// Add the list of one thing to the request
add(annotateImageRequest);
}});
Vision.Images.Annotate annotateRequest =
vision.images().annotate(batchAnnotateImagesRequest);
// Due to a bug: requests to Vision API containing large images fail when GZipped.
annotateRequest.setDisableGZipContent(true);
BatchAnnotateImagesResponse response = annotateRequest.execute();
return convertResponseToString(response);
} catch (GoogleJsonResponseException e) {
} catch (IOException e) {
}
return "Cloud Vision API request failed. Check logs for details.";
}
Seems like I missed something somewhere.I take this error in logcat.
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code": 403,
"errors": [
{
"domain": "global",
"message": "This API method requires billing to be enabled.
Please enable billing on project #285568034008 by visiting https://console.developers.google.com/billing/enable?project=285568034008 then retry.
If you enabled billing for this project recently, wait a few minutes for the action to propagate to our systems and retry.",
"reason": "forbidden"
}
],
"message": "This API method requires billing to be enabled. Please enable billing on project #285568034008 by visiting https://console.developers.google.com/billing/enable?project=285568034008 then retry. If you enabled billing for this project recently, wait a few minutes for the action to propagate to our systems and retry.",
"status": "PERMISSION_DENIED"
}
I had the same ptoblem, I think you must enable billing account.
In my android application, I'm integrating the Dialogflow V2 Agent. There's no specific SDK for Android yet. So I'm using the java client library from Dialogflow. followed the tutorial https://github.com/dialogflow/dialogflow-java-client-v2/issues/25.
I've added the dependencies(dialogflow & oauth2) and created a service account in the google-cloud console. Added the credential file into raw folder. followed the tutorial here https://github.com/dialogflow/dialogflow-java-client-v2/issues/25. Getting the error as
java.lang.NoSuchMethodError: No static method
decodeBase64(Ljava/lang/String;)[B in class
Lorg/apache/commons/codec/binary/Base64; or its super classes
(declaration of 'org.apache.commons.codec.binary.Base64' appears in
/system/framework/org.apache.http.legacy.boot.jar)
private void createDialogflow() {
try {
InputStream stream = getResources().openRawResource(R.raw.dialogflow_service_credentials);
GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
String projectId = ((ServiceAccountCredentials) credentials).getProjectId();
SessionsSettings.Builder settingsBuilder = SessionsSettings.newBuilder();
SessionsSettings sessionsSettings = settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();
sessionsClient = SessionsClient.create(sessionsSettings);
String uuid = UUID.randomUUID().toString();
session = SessionName.of(projectId, uuid);
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendMessage(String msg) {
// Java V2
setTypingMessage();
QueryInput queryInput = QueryInput.newBuilder().setText(TextInput.newBuilder().setText(msg).setLanguageCode("en-US")).build();
new RequestJavaV2Task(mContext, session, sessionsClient, queryInput).execute();
}
public void callbackV2(DetectIntentResponse response) {
removeTyingMessage();
if (response != null) {
// process aiResponse here
String botReply = response.getQueryResult().getFulfillmentText();
Log.d("botReply", "V2 Bot Reply: " + botReply);
setBotMessage(botReply);
} else {
Log.d("botReply", "Bot Reply: Null");
setBotMessage("There was some communication issue. Please Try again!");
}
}
Is there any clear documentations on how to integrate Dialogflow v2 into my android application.
The tutorial you were following was updated. In case anyone is facing this issue, according to the repo:
Save your CLIENT_ACCESS_TOKEN in gradle.properties
I want to use Youtube API to get the subscription list of a user. It requires oauth.
I read that implementing google sign in will make it easier to access this API
I followed Google's documentation and now I got the signing in working
I have these files now.
My question:
1) Which sample do I need to use, IdTokenActivity.java or RestApiActivity.java
2) How can I use the sample code to access Youtube API? It doesn't say and the documentation is confusing
Which sample do I need to use, IdTokenActivity.java or RestApiActivity.java ?
IdTokenActivity.java aims at retrieving an id_token. The id_token is a JWT token designed to be sent to a backend to authenticate the user as a real (trusted) Google user. You can find more information about the flow for the backend here.
RestApiActivity.java is used to consume Google API which is what you are trying to do.
How can I use the sample code to access Youtube API?
Here are the steps :
Go to Google Signin setup for Android, download google-services.json and place it in your app folder
in google developer console enable Youtube Data API
add the following to app build.gradle :
compile 'com.google.android.gms:play-services-auth:10.0.1'
compile 'com.google.api-client:google-api-client-android:1.22.0' exclude module: 'httpclient'
compile 'com.google.apis:google-api-services-youtube:v3-rev182-1.22.0'
with apply plugin: 'com.google.gms.google-services' to the bottom of your file
update the following to your top level build.gradle :
dependencies {
classpath 'com.google.gms:google-services:3.0.0'
}
Include the RestApiActivity.java in your project and update the following :
// Scope for reading user's contacts
private static final String YOUTUBE_SCOPE = "https://www.googleapis.com/auth/youtube";
...
// Configure sign-in to request the user's ID, email address, basic profile,
// and readonly access to contacts.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope(YOUTUBE_SCOPE))
.requestEmail()
.build();
and when the client is authenticated (in handleSignInResult) , request the subscription list as following :
/**
* AsyncTask that uses the credentials from Google Sign In to access Youtube subscription API.
*/
private class GetSubscriptionTask extends AsyncTask<Account, Void, List<Subscription>> {
#Override
protected void onPreExecute() {
showProgressDialog();
}
#Override
protected List<Subscription> doInBackground(Account... params) {
try {
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
RestApiActivity.this,
Collections.singleton(YOUTUBE_SCOPE));
credential.setSelectedAccount(params[0]);
YouTube youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("Google Sign In Quickstart")
.build();
SubscriptionListResponse connectionsResponse = youtube
.subscriptions()
.list("snippet")
.setChannelId("UCfyuWgCPu5WneQwuLBWd7Pg")
.execute();
return connectionsResponse.getItems();
} catch (UserRecoverableAuthIOException userRecoverableException) {
Log.w(TAG, "getSubscription:recoverable exception", userRecoverableException);
startActivityForResult(userRecoverableException.getIntent(), RC_RECOVERABLE);
} catch (IOException e) {
Log.w(TAG, "getSubscription:exception", e);
}
return null;
}
#Override
protected void onPostExecute(List<Subscription> subscriptions) {
hideProgressDialog();
if (subscriptions != null) {
Log.d(TAG, "subscriptions : size=" + subscriptions.size());
// Get names of all connections
for (int i = 0; i < subscriptions.size(); i++) {
Log.v(TAG, "subscription : " + subscriptions.get(i).getId());
}
} else {
Log.d(TAG, "subscriptions: null");
mDetailTextView.setText("None");
}
}
}
which is launched in lieu of GetContacts with :
new GetSubscriptionTask().execute(mAccount);
You can find a complete example here
I have an application on Google App Engine (hosted on appspot.com) which is going to be used by a few users to grab some stuff off the internet, save it in the Datastore and then write it to a Google Spreadsheet. I'm looking to use a Service Account to access the spreadsheet but I run into a 400 OK { "error" : "invalid_grant" } problem when I try to do anything, regardless of whether I try to create a file using the Drive API or access an existing file using Spreadsheets API.
I've turned on both Drive API and Drive SDK in the APIs Console and generated a P12 key. This is my method for building a GoogleCredential:
private GoogleCredential getGoogleCredential() throws IOException, GeneralSecurityException {
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(TRANSPORT)
.setJsonFactory(FACTORY)
.setServiceAccountId("1511XXX90247.apps.googleusercontent.com")
.setServiceAccountScopes(scopes)
.setServiceAccountPrivateKeyFromP12File(
new File("05a605b0fXXXd2a6be864be15d81a2bd629d3bd6-privatekey.p12"))
.setServiceAccountUser("XXX#gmail.com") // My personal e-mail address which I used to create the project
.build();
return credential;
}
The ServiceAccountID comes from the APIs Console. I've tried using 1511XXX90247#developer.gserviceaccount.com as my ServiceAccountUser as well as myappname#appspot.gserviceaccount.com. The scopes I'm using are as follows:
https://spreadsheets.google.com/feeds
https://docs.google.com/feeds
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
Here is the code that fails when I try to use Spreadsheets API:
SpreadsheetService service = new SpreadsheetService("name of my app");
service.setOAuth2Credentials(getGoogleCredential());
FeedURLFactory factory = FeedURLFactory.getDefault();
SpreadsheetQuery query = new SpreadsheetQuery(factory.getSpreadsheetsFeedUrl());
query.setTitleQuery("test");
SpreadsheetFeed feed = service.query(query, SpreadsheetFeed.class);
The code fails when the service tries execute the query.
Here's the Drive code I tried that also fails:
Drive drive = new Drive.Builder(TRANSPORT, FACTORY,
getGoogleCredential()).build();
com.google.api.services.drive.model.File file = new com.google.api.services.drive.model.File();
file.setTitle("test");
file.setMimeType("application/vnd.google-apps.spreadsheet");
drive.files().insert(file).execute(); // This is where the code fails
No matter what I try, I always seem to end up with the same ìnvalid grant` error. Here's a partial stacktrace:
com.google.gdata.util.AuthenticationException: Failed to refresh access token: 400 OK { "error" : "invalid_grant" }
at com.google.gdata.client.GoogleAuthTokenFactory$OAuth2Token.refreshToken(GoogleAuthTokenFactory.java:260)
at com.google.gdata.client.GoogleAuthTokenFactory.handleSessionExpiredException(GoogleAuthTokenFactory.java:702)
at com.google.gdata.client.GoogleService.handleSessionExpiredException(GoogleService.java:738) at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:680)
at com.google.gdata.client.Service.query(Service.java:1237)
at com.google.gdata.client.Service.query(Service.java:1178)
at spam.gwt.scraper.server.spreadsheets.APIConnector.doGet(APIConnector.java:66)
I've tried to look for answers everywhere, including but not limited to the Google Developers Spreadsheets Guide, this Service Account-related Stack Overflow question and this Google App Engine-specific Stack Overflow question. What with the developments (eg. Docs -> Drive) it's hard to find up-to-date info, never mind info that pertains specifically to GAE.
I use the builtin Service Account of the App Engine application rather than creating my own; this way the private key is save (not stored locally, only on app engine).
For Drive:
protected Drive createDriveService() throws BookingSheetException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleClientRequestInitializer keyInitializer =
new CommonGoogleClientRequestInitializer(API_KEY);
AppIdentityCredential credential =
new AppIdentityCredential.Builder(Arrays.asList(DriveScopes.DRIVE)).build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential)
.setGoogleClientRequestInitializer(keyInitializer)
.setApplicationName(appname).build();
return service;
}
For Spreadsheet:
private Credential creds;
/**
* Keep the expiration time of the access token to renew it before expiry
*/
private Calendar expirationTime = Calendar.getInstance();
protected void initCredentials() {
List<String> scopes = Arrays.asList("https://spreadsheets.google.com/feeds");
AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
expirationTime.setTime(accessToken.getExpirationTime());
expirationTime.add(Calendar.MINUTE,-REFRESH_MINUTES); //refresh some time before expiry
creds = new Credential(BearerToken.authorizationHeaderAccessMethod());
creds.setAccessToken(accessToken.getAccessToken());
}
public SpreadsheetUtil(String appname) {
myService = new SpreadsheetService(appname);
myService.setOAuth2Credentials(cred);
}
Make sure to creds.refreshToken() or reinitialize when they expire.
With the help of using the Google document Writing files to a blob store
I can store the file in Google Cloud in below way,
//My servlet Class
private StorageService storage = new StorageService();
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile(mime, fileName);
boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
byte[] b1 = new byte[BUFFER_SIZE];
int readBytes1;
storage.init(fileName, mime); // Calling my Java Class Here
while ((readBytes1 = is1.read(b1)) != -1) {
writeChannel.write(ByteBuffer.wrap(b1, 0, readBytes1));
storage.storeFile(b1, readBytes1);}
writeChannel.closeFinally();
I have a storage java class to store the data in Google cloud that is below here,
//My Storage Class
public class StorageService {
public static final String BUCKET_NAME = "MyBucket";
public void init(String fileName, String mime) throws Exception {
GSFileOptionsBuilder builder = new GSFileOptionsBuilder().setAcl("public_read").setBucket(BUCKET_NAME).setKey(fileName).setMimeType(mime);
AppEngineFile writableFile = fileService.createNewGSFile(builder.build());
boolean lock = true;
writeChannel = fileService.openWriteChannel(writableFile, lock);
bos = new BufferedOutputStream(Channels.newOutputStream(writeChannel));
public void storeFile(byte[] b, int readSize) throws Exception {
bos.write(b,0,readSize);
bos.flush();
}}
From the above reference i can store the file directly in Google cloud. But i need to store those files as blob values using the File service.
Can anyone suggest me an idea.
your help will be appreciated.
Have you add appengine service account into Google API Console Project ?
If you have not done, you should prepare Google API Console Project.
Confirm your appengine service account on "Application Settings" tab on GAE Admin Console
Create new Project on Google API Console. or Open API Console Project for your exists bucket.
Make enable "Google Cloud Storage" in "Services" tab.
Add appengine service account as team on API Console "Team" tab.