watson speech to text unauthorized request error401 - java

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.

Related

Restarting app server using AWS API

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.

Internal Server Error 500 in Google App Engine (that gets fixed temporarily by re-deploying)

I was making this app where it gets data from Google Spreadsheet using a library called gspread.
This is the code (in python) I used to get data from my Spreadsheet :
json_key = json.load(open('service.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
self.gc = gspread.authorize(credentials)
self.sheet = self.gc.open('Order Database').sheet1
self.menuSheet = self.gc.open('Menu and Stocking').sheet1
return self.menuSheet.get_all_values()
At the beginning the code was working fine, I was using OAuth 2.0 client IDs.
Later when I was working with my android app, to get the data from the website on that url, I started getting Internal Server 500 error, and I can access to that url even from chrome where other part of my website works fine. While searching for solution, I found some people saying to use a API Keys, so I created a server key and even used that, this is the android code :
HttpClient client = new DefaultHttpClient();
HttpGet request =new HttpGet(url);
request.addHeader("x-api-key",apikey);
HttpResponse response = client.execute(request);
BufferReader rd = new BufferReader(new InputStreamReader(response.getEntity().getContent()));
String line = rd.readLine();
The code works fine, at least thats what I think. Every time I get the Internal Server Error 500, if I deploy it again, it starts working fine, but only for a while, soon it starts showing the same error. Looking through the Dashboard of my project I found some detail of the error so I will also include that here :
HTTPError: 401: <HTML> <HEAD> <TITLE>Unauthorized</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <H1>Unauthorized</H1> <H2>Error 401</H2> </BODY> </HTML>
at request (/base/data/home/apps/s~gowcanteen/1.394247265273324301/lib/gspread/httpsession.py:75)
at get (/base/data/home/apps/s~gowcanteen/1.394247265273324301/lib/gspread/httpsession.py:79)
at get_cells_feed (/base/data/home/apps/s~gowcanteen/1.394247265273324301/lib/gspread/client.py:250)
at getMenuItems (/base/data/home/apps/s~gowcanteen/1.394247265273324301/server.py:24)
at API_MENU (/base/data/home/apps/s~gowcanteen/1.394247265273324301/main.py:61)
at dispatch_request (/base/data/home/apps/s~gowcanteen/1.394247265273324301/lib/flask/app.py:1461)
at full_dispatch_request (/base/data/home/apps/s~gowcanteen/1.394247265273324301/lib/flask/app.py:1475)
at handle_user_exception (/base/data/home/apps/s~gowcanteen/1.394247265273324301/lib/flask/app.py:1381)
at full_dispatch_request (/base/data/home/apps/s~gowcanteen/1.394247265273324301/lib/flask/app.py:1477)
at wsgi_app (/base/data/home/apps/s~gowcanteen/1.394247265273324301/lib/flask/app.py:1817)
I am new to developing and have very little knowledge about OAuths and Credentials, so there might be issues that I do not know and thats why unable to find the problem and fix it. I have added everything that I could think of that could have been related to this issue, so please I ask for your help.
Some of you may tell this question as duplicate and I know there were others who had similar problems. I checked those, it may be because of my lack of knowledge but I couldn't solve my problem with those. I would have thought of it as a problem in code but then why does deploying it again fixes the problem? And there were some that suggested to use API Key or credentials which I did, so if I have applied it in a wrong way, please correct me. Sorry for making this question too long.

Timeout exceptions when trying to insert big text files to Google Drive using the Java client library

I am using the Java client library for Google Drive API to upload some text files and convert them to Google doc format. The code runs on Google App Engine. The main code segment looks like this:
File fileMetadata = new File();
fileMetadata.setTitle("Document title");
fileMetadata.setDescription("Desc goes here");
fileMetadata.setMimeType("text/plain; charset=utf-8");
ByteArrayContent byteArrayContent = ByteArrayContent.fromString(
"text/plain; charset=utf-8", "Text file's content goes here");
Drive.Files.Insert insertRequest = driveService.files()
.insert(fileMetadata, byteArrayContent).setConvert(true);
File insertedFile = insertRequest.execute();
For small text files, the above code works fine. But when the text files are big (perhaps there are some other factors that I am not aware of), it would throw the following exception:
Uncaught exception from servlet
java.net.SocketTimeoutException: Timeout while fetching URL: https://www.googleapis.com/upload/drive/v2/files?convert=true&uploadType=resumable&upload_id=AEnB2UpPDz6jvM8zO2zPFxFHmoCiisplOf1Ui5fngZdI4qqoK6hwt_wtOt89RcW3QautW9FPlHKfMznYA4gmo95qdWthJQgWpQ
at com.google.appengine.api.urlfetch.URLFetchServiceImpl.convertApplicationException(URLFetchServiceImpl.java:145)
at com.google.appengine.api.urlfetch.URLFetchServiceImpl.fetch(URLFetchServiceImpl.java:45)
at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.fetchResponse(URLFetchServiceStreamHandler.java:419)
at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getInputStream(URLFetchServiceStreamHandler.java:298)
at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getResponseCode(URLFetchServiceStreamHandler.java:151)
at com.google.api.client.http.javanet.NetHttpResponse.<init>(NetHttpResponse.java:36)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:94)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:965)
at com.google.api.client.googleapis.media.MediaHttpUploader.executeCurrentRequestWithoutGZip(MediaHttpUploader.java:545)
at com.google.api.client.googleapis.media.MediaHttpUploader.resumableUpload(MediaHttpUploader.java:417)
at com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:336)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:418)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
Some people said it's due to the URLConnnection's timeout. But I am using the Java client library, which doesn't allow me to set the timeout explicitly. Also, the above exception happens at least 30 seconds after the insertRequest.execute() call.
I suspect the Java client library has set an internal timeout of 30 seconds... I hope some Google software engineers can take a look.
Any idea will be appreciated. Thanks very much.
This error is expected when you are uploading a big file. Try implementing a resumable upload. You can read more about the method as well as a sample in the following page: https://developers.google.com/drive/web/manage-uploads#resumable
Based on the Java library, you should add the following code before the insertRequest.execute()
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(useDirectUpload);
uploader.setProgressListener(new FileUploadProgressListener());

jInstagram - How to establish connection?

I want to build an app in Java based on live showing certain photos of Instagram tagged with a particular hashtag. I'm currently trying to use jInstagram, but I can't understand the flow of the API Instagram. It's not like the Twitter API. Instagram API seems to call for a server in the middle of my app and their servers, while Twitter API gave me access to the gardenhose without a lot of work. And, overall, thanks to the nice samples on Twitter4J.org
I'd be grateful if somebody can help me to start with. I just want to get live photos with certain hashtag of Instagram but I don't know if I'd should set up a server or where they give me an access token.
First you need to register your app to instagram's website and get your apiKey and apiSecret. Then you can choose a callback URL and a scope.
InstagramService service = new InstagramAuthService()
.apiKey("e607b7XXXce54e729bXXXXf40162")
.apiSecret("651cXXX2ab348a3XXXXa7ae90c6d")
.callback("http://www.cagdasalagoz.com")
.scope("basic public_content likes comments follower_list relationships")
.build();
After this, you can get the authorization like this.
String authorizationUrl = service.getAuthorizationUrl();
System.out.println(authorizationUrl); //paste in browser
Scanner sc = new Scanner(System.in);
System.out.println("Paste the code gotten in the browser (at the end of the URL): ");
String verCode = sc.nextLine(); //SCAN VERIFIER CODE
Verifier verifier = new Verifier(verCode);
Token accessToken = service.getAccessToken(verifier); //Token successfully gotten
//** RUNS OK UP TO THIS LINE INCLUDED **//
Instagram instagram = new Instagram(accessToken); //Ok
About getting the posts by a tag can be achived by this method I guess.
String tag="seaside";
instagram.getRecentMediaFeedTags(tag);
You can learn more about jInstagram from this page.

How to upload file from GAE to Amazon S3 using URLFetchService?

I am trying to upload files to Amazon S3 from Google App Engine (in Java) using the URLFetchService, but I am not getting very far. For a start I have never done any REST programming before, nor GAE.
I have looked through the documentation for S3, and have come up with the following code. Am I going along the right path?
final URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();
final URL url = new URL("http", AWS_BUCKET+".s3.amazonaws.com/myFile.jpg", "");
final HTTPRequest request = new HTTPRequest(url, HTTPMethod.PUT, followRedirects());
request.addHeader(new HTTPHeader("Content-Type", contentType));
request.addHeader(new HTTPHeader("Content-Length", Integer.toString(pictureBytes.length)));
request.addHeader(new HTTPHeader("Expect", "100-continue"));
request.addHeader(new HTTPHeader("Authorization", "AWS "+AWS_ACCESS_KEY+":"+AWS_SECRET_KEY));
request.setPayload(pictureBytes);
urlFetchService.fetch(request);
When I run the above code, I get Entity enclosing requests cannot be redirected without user intervention as an error message.
Thanks in advance for any hints/tips/pointers/URLs/solutions :)
Cheers
Rich
Ok, after all that, the sample code from Amazon themselves works just fine!
I wasn't expecting the Amazon code to work because of the sandbox that GAE/J runs in, but I should've tested it first.

Categories