I tried to use the code from IBM Watson GitHub repository I had to change a little bit for some errors I got when pasting it. I tried then to run the code to see it transcript from an audio file to text. But I got error 401 unauthorized. I tried to see solutions but didn't find one. Her is my code,
SpeechToText service = new SpeechToText();
IamOptions options1 = new IamOptions.Builder()
.apiKey("{apikey}")
.build();
service.setIamCredentials(options1);
File audio = new File("C:\\Users\\usern\\Downloads\\audio-file.FLAC");
RecognizeOptions options = new RecognizeOptions.Builder()
.audio(audio)
.contentType(HttpMediaType.AUDIO_FLAC)
.build();
SpeechRecognitionResults transcript = service.recognize(options).execute().getResult();
System.out.println(transcript);
So the answer was for me to solve this was to add service.setEndPoint("https://gateway-lon.watsonplatform.net/speech-to-text/api");
as the second line. URL for me was found looking at the Credentials at the IBM cloud service website, not that the URL might be different compared to mine where mine is located at London.
I need to restart my AWS app server, for this I tried to use AWS API and have done the following:
1) Used the aws java sdk maven repository
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-elasticbeanstalk</artifactId>
<version>1.11.86</version>
</dependency>
2) Used the below code segment:
AWSElasticBeanstalk client = new AWSElasticBeanstalkClient();
RestartAppServerRequest request = new RestartAppServerRequest()
.withEnvironmentId("<myEnvId>")
.withEnvironmentName("<myEnvName>");
RestartAppServerResult response = client.restartAppServer(request);
I get the below error:
com.amazonaws.services.elasticbeanstalk.model.AWSElasticBeanstalkException: No Environment found for EnvironmentId = ''. (Service: AWSElasticBeanstalk; Status Code: 400; Error Code: InvalidParameterValue; Request ID: 4d025449-ed00-11e6-8405-4d5eb8e5ecd9)
The <myEnvId> and <myEnvName> are correct as they are taken from the AWS dashboard.
I also tried including the aws.accessKeyId and aws.secretKey to java system properties. Still I get the same error.
Is there something I am missing or doing wrong? Please advice.
Thanks,
Clyde
It sounds like you need to configure the region. For example to configure the region to us-west-2 you would use the following code:
AWSElasticBeanstalk client = new AWSElasticBeanstalkClient();
client.configureRegion(Regions.US_WEST_2);
Thanks to all who posted. I manged to solve the issue. The code segment used is as follows:
AWSElasticBeanstalk client = new AWSElasticBeanstalkClient();
client.setEndpoint(<set your endpoint>);
RestartAppServerRequest request = new RestartAppServerRequest()
.withEnvironmentId(<set your env id>)
.withEnvironmentName(<set your env name>);
RestartAppServerResult response = client.restartAppServer(request);
This worked find.
I found the follow note, which describes exactly what I'd like to do:
Note: If your users are only uploading resources (writing) to an access-controlled bucket, you can use the resumable uploads functionality of Google Cloud Storage, and avoid signing URLs or requiring a Google account. In a resumable upload scenario, your (server-side) code authenticates and initiates an upload to Google Cloud Storage without actually uploading any data. The initiation request returns an upload ID, which can then be used in a client request to upload the data. The client request does not need to be signed because the upload ID, in effect, acts as an authentication token. If you choose this path, be sure to transmit the upload ID over HTTPS.
https://cloud.google.com/storage/docs/access-control#Signed-URLs
However, I cannot figure out how to do this with the Google Cloud Storage Library for Java.
https://developers.google.com/resources/api-libraries/documentation/storage/v1/java/latest/
I can't find any reference to resumable files, or getting the URL for a file anywhere in this API. How can I do this?
That library does not expose the URLs that it creates to its caller, which means you can't use it to accomplish this. If you want to use either signed URLs or the trick you mention above, you'll need to implement it manually.
I would advise going with the signed URL solution over the solution where the server initializes the resumable upload, if possible. It's more flexible and easier to get right, and there are some odd edge cases with the latter method that you could run into.
Someone wrote a up a quick example of signing a URL from App Engine a while back in another question: Cloud storage and secure download strategy on app engine. GCS acl or blobstore
You can build the url yourself. Here is an example :
OkHttpClient client = new OkHttpClient();
AppIdentityService appIdentityService = credential.getAppIdentityService();
Collection<String> scopes = credential.getScopes();
String accessToken = appIdentityService.getAccessToken(scopes).getAccessToken();
Request request = new Request.Builder()
.url("https://www.googleapis.com/upload/storage/v1/b/" + bucket + "/o?name=" + fileName + "&uploadType=resumable")
.post(RequestBody.create(MediaType.parse(mimeType), new byte[0]))
.addHeader("X-Upload-Content-Type", mimeType)
.addHeader("X-Upload-Content-Length", "" + length)
.addHeader("Origin", "http://localhost:8080")
.addHeader("Origin", "*")
.addHeader("authorization", "Bearer "+accessToken)
.build();
Response response = client.newCall(request).execute();
return response.header("location");
It took some digging, but I came up with the following which does the right thing. Some official documentation on how to do this would have been nice, especially because the endpoint for actually triggering the resumable upload is different from what the docs call out. What is here came from using the gsutil tool to sign requests and then working out what was being done. The under-documented additional thing is that the code which POSTs to this URL to get a resumable session URL must include the "x-goog-resumable: start" header to trigger the upload. From there, everything is the same as the docs for performing a resumable upload to GCS.
import base64
import datetime
import time
import urllib
from google.appengine.api import app_identity
SIGNED_URL_EXPIRATION = datetime.timedelta(days=7)
def SignResumableUploadUrl(gcs_resource_path):
"""Generates a signed resumable upload URL.
Note that documentation on this ability is sketchy. The canonical source
is derived from running the gsutil program to generate a RESUMABLE URL
with the "-m RESUMABLE" argument. Run "gsutil help signurl" for info and
the following for an example:
gsutil -m RESUMABLE -d 10m keyfile gs://bucket/file/name
Note that this generates a URL different from the standard mechanism for
deriving a resumable start URL and the initiator needs to add the header:
x-goog-resumable:start
Args:
gcs_resource_path: The path of the GCS resource, including bucket name.
Returns:
A full signed URL.
"""
method = "POST"
expiration = datetime.datetime.utcnow() + SIGNED_URL_EXPIRATION
expiration = int(time.mktime(expiration.timetuple()))
signature_string = "\n".join([
method,
"", # content md5
"", # content type
str(expiration),
"x-goog-resumable:start",
gcs_resource_path
])
_, signature_bytes = app_identity.sign_blob(signature_string)
signature = base64.b64encode(signature_bytes)
query_params = {
"GoogleAccessId": app_identity.get_service_account_name(),
"Expires": str(expiration),
"Signature": signature,
}
return "{endpoint}{resource}?{querystring}".format(
endpoint="https://storage.googleapis.com",
resource=gcs_resource_path,
querystring=urllib.urlencode(query_params))
String sourceUrlString="http://maps.googleapis.com/maps/api/geocode/xml?address="+searchWord+"&sensor=true";//searchWord-parameter to be passed
Source source=new Source(new URL(sourceUrlString));
Element alpha=source.getFirstElement("location");
String beta[]=new String[100];
String lat=alpha.getContent().getFirstElement("lat").getContent().toString();
String lng=alpha.getContent().getFirstElement("lng").getContent().toString();
THE error pointed out by google app engine is in the above bold statements it says null pointer exception but on local server it returns the value and the code works fine.
wat are the possible solution to the above problem?and as of what i have come to conclusion is google app engine does not support Http request .is it true?
You need to use URL Fetch service to issue HTTP requests and receive responses:
One example:
import urllib2
url = "http://www.google.com/"
try:
result = urllib2.urlopen(url)
doSomethingWithResult(result)
except urllib2.URLError, e:
handleError(e)
I've been unable to make a "DELETE" request using the code below :
URLFetchService fetchService = URLFetchServiceFactory.getURLFetchService();
URL posturl = new URL("http://www.example.com/comment?token=xxx");
HTTPResponse response = fetchService.fetch(new HTTPRequest(posturl, HTTPMethod.DELETE));
int responseCode = response.getResponseCode();
This is for Google Appengine. The 'DELETE' request is for the facebook graph API. The above code gives me a status code 400 - Bad Request.
This is for face4j an open source java library that I've built for the facebook graph API.
This isn't really an App Engine problem; it just means that the destination webserver wouldn't accept your request.
If you're actually trying to send a DELETE to example.com, that's your problem. If that's supposed to be a scrubbed URL, you've omitted the detail that would facilitate troubleshooting.