How can I fix Cloud vision API request failed error? - java

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.

Related

Getting "You can not share this item because it has been flagged as inappropriate" while creating permissions for a file from a Google Service Account

I'm uploading a file to Google Drive using a Google Service Account. File is getting uploaded successfully.
But I need to share it with some stakeholders. So, while adding permissions to it, i'm getting this error: "message": "Bad Request. User message: "You cannot share this item because it has been flagged as inappropriate."
My code snippets are:
// create and return credential
private static Credential getCredentials2() throws IOException {
java.io.File serviceAccountCredsFile = new java.io.File("creds.json");
#SuppressWarnings("deprecation")
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(serviceAccountCredsFile))
.createScoped(SCOPES);
return credential;
}
// build and return an authorized drive client service
public static List<File> getDriveService() throws Exception {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
// Instantiating a client
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials2())
.setApplicationName(APPLICATION_NAME)
.build();
System.out.println("Successfully created the Drive service!!!!!!!!!!!!!!!!!!!!");
/***************************Uploading file on Google Drive Start*********************************/
File fileMetadata = new File();
fileMetadata.setName("1stFile.csv");
fileMetadata.setParents(Collections.singletonList("10Tt3rfkaeHr1JOUQYRPTfqQQ2jdDJcy"));
fileMetadata.setDescription("Testing upload");
fileMetadata.setMimeType("application/csv");
java.io.File fileTobeUploaded = new java.io.File("custid.csv");
FileInputStream inputStream = new FileInputStream(fileTobeUploaded);
InputStreamContent mediaContent = new InputStreamContent("application/csv", inputStream);
try {
File uploadedFile = service.files().create(fileMetadata, mediaContent)
.setSupportsAllDrives(true)
.execute();
com.google.api.services.drive.model.Permission newPermission = new com.google.api.services.drive.model.Permission() ;
newPermission.setType("user");
newPermission.setRole("writer");
newPermission.setEmailAddress("xyz#xyz.com");
service.permissions().create(createdFileId, newPermission)
.setSupportsAllDrives(true)
.execute();
After the execution of 'service.permissions().create()', i'm getting below error:
400 Bad Request
POST https://www.googleapis.com/drive/v3/files/16-wFWifo0HNZW6W1lujJiT1HO-1wLbK/permissions?supportsAllDrives=true
{
"code": 400,
"errors": [
{
"domain": "global",
"message": "Bad Request. User message: "You cannot share this item because it has been flagged as inappropriate."",
"reason": "invalidSharingRequest"
}
],
"message": "Bad Request. User message: "You cannot share this item because it has been flagged as inappropriate.""
}
Really need inputs in this. Thanks in advance!
This is an issue with the file itself and not related to the api
if your file was flagged you can go to the drive web application and request that the file be reviewed again review
if the file is uploaded to the server account drive account I don't think you can request a review.
remember there are several types of files that drive probably won't let you share .zip is one
Try setting the sendNotificationEmail to false when creating file permissions. This solved it for me allthough I am not quite sure what caused the error in the first place. Could have something to do with the service account's settings but I am just guessing. According to documentation the error can happen for several reasons but does not explicitly mention a solution for this specific message.
Hopefully this will help you!

Access Youtube API

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

Android HTTP Requests Working In Simulator But Not On Wear Device

I am making a simple Android Wear app to control my thermostats, and I'm sending POST requests with Volley to control them. Everything works great in the Android Wear simulator (the request works), but, while the app does load on my Moto 360, the volley request gets called but invariably times out.
Why could my volley request be failing on my watch but working on the simulator? Other apps' requests succeed on my watch (for example, the built-in weather app can load up weather data in about 3 seconds). And, the weirdest part: I had the app working (successfully making volley requests) on my watch, and, about a day after I installed it to my watch from Android Studio, it suddenly stopped loading data for no apparent reason.
What I've tried so far:
I have requested the Internet permission in my manifest.xml.
I have increased the timeout to 30 seconds (see my code below), which didn't change anything.
I have tried tethering my computer and the simulator to my phone's connection via Bluetooth (to replicate the Bluetooth connection my physical watch has to my phone), and the simulator made the request successfully still (albeit with a two-second delay), ruling out the possibility of Bluetooth being too slow.
I made sure the API level is low enough for my Marshmallow-running watch (my watch and the app are both API level 23).
I tried doing a quick test request to Google before the request to the company's servers with my thermostat data, and while the Google request returns the site's HTML code in the simulator, it times out on my watch (thirty seconds after the request is initiated).
I tried putting some dummy data into the recycler view data should be loaded into, and the dummy data indeed showed up, ruling out that the recycler view is broken.
I deleted the app from my watch and reinstalled it, and deleted the companion from my phone, reinstalled it, and deleted it again, all to no avail.
A lengthy chat with Google Support did not produce anything meaningful.
Here's my code (from my main view's adapter):
public void refreshThermostatsRecyclerView(RequestQueue queue) {
String url = "https://mobile.skyport.io:9090/login"; // login call to the thermostats server Skyport
Log.w("myApp", "Starting /login call to Skyport"); // this gets called on simulator and watch
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the response string.
Log.w("myApp", "Response is: " + response); // this gets called on the simulator but not the watch
try {
// there's some code to parse the data.
} catch (JSONException e) {
Log.w("myApp", "catching an error parsing the json."); // never gets called.
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.w("myApp", "Skyport request didn't work! " + error); // this always gets called on the watch, with the error being a timeout error (com.Android.Volley.timeouterror) but never gets called in the simulator
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> m = new HashMap<>();
m.put("Referer", "app:/VenstarCloud.swf");
// here I put some more headers
return m;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> m = new HashMap<>();
m.put("version", "3.0.5");
m.put("email", userEmail);
m.put("password", userToken);
return m;
}
};
// Add the request to the RequestQueue.
int socketTimeout1 = 30000; // times out 30 seconds after the request starts on the watch
RetryPolicy policy1 = new DefaultRetryPolicy(socketTimeout1, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy1);
queue.add(stringRequest);
}
Which is called from the onCreate() method in my Main Activity with this code:
RequestQueue queue = Volley.newRequestQueue(this);
refreshThermostatsRecyclerView(queue);
If you'd like to view the logs created by running this in the simulator and on the watch, they're on Google Drive here.
Edit 1: A reboot of my watch fixes the issue temporarily and allows the watch to make HTTP Requests again, but it breaks again once the watch disconnects from Bluetooth, connects to WiFi, disconnects from WiFi, and reconnects to Bluetooth (so it breaks every time I go across my apartment without my phone and then return).
Edit 2: I switched the volley requests all over to HTTPURLConnection Requests in an Async thread, and the same issues occur as with volley.
tl;dr: My app's Volley requests are working in the simulator but not on my Android Wear watch anymore (though Play Store-downloaded apps' similar requests work), how can I get a volley request to work again on my app on the watch?
As per these two conversations below, it seems that WiFi connectivity only allows Android Wear to connect to a phone over WiFi and not directly to the Internet. However, Android Wear 2.0 lets you use regular network APIs.
Direct internet connection on Android Wear?
Does Android Wear support direct access to the Internet?
So, for Android Wear 2.0+ Volley requests from wearable app should work.
If you want to use Android Wear <2.0, then:
On Wearable, in onCreate() add a key that indicates whether the phone should start collecting data.
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/shouldStart");
putDataMapReq.getDataMap().putBoolean(SHOULD_START_KEY, true);
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
PendingResult pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
On phone, in onDataChanged, check if wearable wants to start collecting data. If yes, start Volley request.
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
// DataItem changed
DataItem item = event.getDataItem();
if (item.getUri().getPath().compareTo("/shouldStart") == 0) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
boolean shouldStart = dataMap.getBoolean(SHOULD_START_KEY));
if(shouldStart) {
Volley.newRequestQueue(this).add(request);
}
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
// DataItem deleted
}
}
Then, your Volley request's onResponse should pass data back to Wearable.
public void onResponse(String response) {
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/data");
putDataMapReq.getDataMap().putString(DATA_KEY, true);
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
PendingResult pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
}
Finally, you can access data in your Wearable using onDataChanged and store it in your model for passing it onto adapter:
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
// DataItem changed
DataItem item = event.getDataItem();
if (item.getUri().getPath().compareTo("/data") == 0) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
parseAndpassToAdapter(dataMap.getString(DATA_KEY));
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
// DataItem deleted
}
}
You'll need Wearable.API to implement this and your class should implement DataApi.DataListener. For more information getting started, refer to Accessing the Wearable Data Layer and Syncing Data Items
Hope this helps.
I am also using volley on an Android wear app I built and I am running it on a Moto 360, I have run into the same problem a couple o times. Try restarting the device. Go to Settings > Restart. It sounds silly but it has worked for me.
You could try an alternative to volley if you can rule out the connection as the problem:
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.0'
compile 'com.android.support:design:23.1.0'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.google.api-client:google-api-client:1.20.0'
The versions are important.
Then to your request:
Map<String, String> contentParams = new HashMap<>();
InputStream is = null;
NetHttpTransport transport = null;
HttpRequest request = null;
HttpResponse resp = null;
HttpHeaders headers = new HttpHeaders();
JSONObject json = null;
try {
transport = new NetHttpTransport();
HttpRequestFactory factory = transport.createRequestFactory();
request = factory.buildPostRequest(new GenericUrl(url), null);
contentParams = getContentParameters();
headers.putAll(getHeaderParameters());
request.setHeaders(headers);
request.getUrl().putAll(contentParams);
resp = request.execute();
is = resp.getContent();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
string = getJSONFromInputStream(is);
json = new JSONObject(string);
}
} catch (Exception e) {
e.printStackTrace();
}
}
transport.shutdown();
protected Map<String, String> getContentParameters() {
Map<String, String> m = new HashMap<>();
m.put("version", "3.0.5");
m.put("email", userEmail);
m.put("password", userToken);
return m;
}
protected Map<String, String> getHeaderParameters() {
Map<String, String> m = new HashMap<>();
m.put("Referer", "app:/VenstarCloud.swf");
return m;
}
protected String getJSONFromInputStream(InputStream is) {
if (is == null)
throw new NullPointerException();
//instantiates a reader with max size
BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8 * 1024);
StringBuilder sb = new StringBuilder();
try {
//reads the response line by line (and separates by a line-break)
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//closes the inputStream
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Then just execute your code from a thread/asynctask/have it delay your frontend slightly
Edit:
Just in case there is a problem with appending a map:
for (Entry<String, String> entry : getHeaderParameters()) {
headers.put(entry.getKey(), entry.getValue());
}
for (Entry<String, String> entry : getContentParameters()) {
request.getUrl().put(entry.getKey(), entry.getValue());
}
Also as another note, make sure to change the return type from void on both those methods to Map
Is this not just the case of when the watch is connected to the phone via bluetooth the internet will not work, as wifi is turned off. If the watch is using wifi to connect to the phone then it will work.
I'm working on wear 2.0 app and just turn blueooth off on my phone for my watch to get internet connection.

how can i display progress bar for dailymotion cloud uploading

I am using Dailymotion cloud in my android app to upload videos to server.
i want to display progress bar while uploading but i don't know how can i get byte by byte value to update progress bar.
This is dailymotion cloud api link Dailymotion cloud api link
While searching on internet i found this progress bar in java but i don't know how can i implement into this method of dailymotion api.
I am using async task to display progress bar
Here is android code for uploading
try
{
CloudKey cloud = new CloudKey(user_id, api_key);
File f = new File(selectedVideoPath);
String media_id = cloud.mediaCreate(f);
System.out.println(media_id);
Log.d("Testing", "media_id is"+media_id);
}
And here is Dailymotion API's Cloud.class mediacreate() in which i want to display progress bar .. any idea
public String mediaCreate(File f) throws Exception
{
return this.mediaCreate(f, null, null);
}
public String mediaCreate(File f, DCArray assets_names, DCObject meta) throws Exception
{
String upload_url = this.fileUpload();
PostMethod filePost = null;
int status;
try
{
filePost = new PostMethod(upload_url);
Part[] parts = {
new FilePart("file", f)
};
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK)
{
ObjectMapper mapper = new ObjectMapper();
DCObject json_response = DCObject.create(mapper.readValue(filePost.getResponseBodyAsString(), Map.class));
return this.mediaCreate(json_response.pull("url"), assets_names, meta);
}
else
{
throw new DCException("Upload failed.");
}
}
catch (Exception e)
{
throw new DCException("Upload failed: " + e.getMessage());
}
finally
{
if (filePost != null)
{
filePost.releaseConnection();
}
}
}
I'm not able to find any api support for doing this with the DailyMotion class that you mentioned.
If you can edit the source of that library, then you could try extending MultipartRequestEntity and add support for callbacks for progress, and then just plug in that new class in the DailyMotion code in the mediaCreate method:
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
.. replace MultipartRequestEntity by the new one, eg. ExtendedMultipartRequestEntity.
See the answer by Tuler and others at File Upload with Java (with progress bar) to see how to do it.
Once you are getting updates via the callback, then you can hook up progress bar.

Error 403 "Access not configured" writing to bucket using JSON API

I am trying to write to Cloud Storage with the REST API using this code:
public static void insertData() {
try {
StorageObject st = new StorageObject();
//create the media object
Media m = new Media();
String content = "hi! this is a test";
m.setData(Base64.encodeBase64String(content.getBytes()));
m.setContentType("text/html");
st.setMedia(m);
//this gets me the credential, works for other APIs but not cloud storage
Storage storage = RequestBuilder.buildStorage();
//Create the insert and execute
Insert insert = storage.objects().insert("mybucket", st);
insert.execute();
} catch (IOException e) {
log.severe(e.getMessage());
}
}
This is my ACL entry as per the REST API:
"kind": "storage#bucketAccessControls",
"items": [
{
"kind": "storage#bucketAccessControl",
"id": "gammeprediction/allUsers",
"selfLink": "https://www.googleapis.com/storage/v1beta1/b/gammeprediction/acl/allUsers",
"bucket": "mybucket",
"entity": "allUsers",
"role": "OWNER"
}]
This is how I get the credential:
private static Credential authorize() {
GoogleCredential credential = null;
//load properties
Properties appProperties = new Properties();
appProperties.load(RequestBuilder.class
.getResourceAsStream("/app.properties"));
// creates an authorization with the key and service account given
InputStream is = RequestBuilder.class.getResourceAsStream("/"
+ appProperties.getProperty("app.keyFileName"));
PrivateKey pk;
try {
pk = PrivateKeys.loadFromKeyStore(KeyStore.getInstance("PKCS12"),
is, "notasecret", "privatekey", "notasecret");
credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(
appProperties
.getProperty("app.serviceAccount"))
.setServiceAccountPrivateKey(pk)
.setServiceAccountScopes(PredictionScopes.PREDICTION,
DriveScopes.DRIVE, StorageScopes.DEVSTORAGE_FULL_CONTROL).build();
return credential;
}
The permissions on the bucket are OWNER for allUsers, but I still get a 403 Forbidden "Access not configured" error. What could possibly be wrong?
Once the JSON API is generally available, this logic will work.
However, at the moment, the JSON API is in Limited Preview. Since an unknown user is not considered to be a member of the limited preview, completely anonymous queries via the REST API are currently not possible. Instead, you must provide at a bare minimum a whitelisted API key when you connect. If you provide no further identity information, you'll be treated as an anonymous user. Or, going further, you can use OAuth2 credentials instead to be treated as a registered user. For more, see: https://developers.google.com/storage/docs/json_api/
Is that a GWT RequestBuilder? I'm not entirely familiar with its use, unfortunately. If it helps, here's an example of setting up a connection with an API key using the Google API Java Client: https://code.google.com/p/google-api-java-client/wiki/OAuth2#Unauthenticated_access
Also, it looks like your call to setData() is passing a non-base64'd string, which will fail.

Categories