Microsoft Azure Translator Android API not working - android

I was trying to make a text translator app using Microsoft-translator-API but I am not able to receive any response from this API, I always get this message:
[microsoft-translator-api] Error retrieving translation: Unable to resolve host "datamarket.accesscontrol.windows.net": No address associated with hostname
even I have given correct client Id and client secret Id.
I tried this link but I don't know where to put the JSON-Simple.jar file. I tried this link too but still with no success. I am pasting my code below:
public String translateText() throws Exception {
Translate.setClientId("whateveritis");
Translate.setClientSecret("whateveritis");
translatedText = Translate.execute(
userText.getText().toString(),
languages[sEnterLan.getSelectedItemPosition()],
languages[sTransLan.getSelectedItemPosition()]);
Language detectedLanguage = Detect.execute(userText.getText()
.toString());
this.detectedLanguage = detectedLanguage.getName(Language.ENGLISH);
return translatedText;
}
By calling above function I can receive the translated text into a string variable but every time I get an exception.

According to your code and reference links, I think you were using the third party Java wrapper boatmeme/microsoft-translator-java-api for MS Azure Translator API. However, it's an old Java wrapper which wrappered the old & unavailable APIs from the old site Azure datamarket. There is a notice at this site, and all origin APIs had been migrated to Azure subscription.
DataMarket and Data Services are being retired and will stop accepting new orders after 12/31/2016. Existing subscriptions will be retired and cancelled starting 3/31/2017. Please reach out to your service provider for options if you want to continue service.
So I suggested that you can try to refer to my answer for the other SO thread Microsoft Translator API Java, How to get client new ID with Azure to create a cognitive service for Translator Text API on Azure portal and use it via the new REST APIs.
Hope it helps.

Related

Implementing Azure Communication Services - Chat in Android application

I'm trying to implement Chat functionality in the Android app using Azure Communication Services (Chat). I used https://learn.microsoft.com/en-us/azure/communication-services/quickstarts/chat/get-started?pivots=programming-language-android this link to set up the Android project. Inside the Android app, we need few configuration data of Azure communication resources like,
String endpoint = "https://<resource>.communication.azure.com";
String firstUserId = "<first_user_id>";
String secondUserId = "<second_user_id>";
String firstUserAccessToken = "<first_user_access_token>";
After going through Microsoft doc, I found this link Access Token Generation, a console application for creating Identity.ID and Access Token. And I used the same access token and Identity.ID which was generated by console application for FirstUserAccessToken and First UserID. Once this is done I ran the Android app, but I got a Null pointer exception while calling
CreateChatThreadResult createChatThreadResult = chatAsyncClient.createChatThread(createChatThreadOptions).get();
On calling .get app throws a exception.
java.lang.NullPointerException: Attempt to invoke virtual method 'int com.azure.android.core.http.HttpResponse.getStatusCode()' on a null object reference
First place, want to know whether the AccessToken and UserId that I'm using are correct or not.
Am I missing something here? Or is there any server-side setup to be done for the same?
First place, want to know whether the AccessToken and UserId that I'm using are correct or not.
Yes, using the CommunicationIdentityClient to create a user and issue a token is the right approach. Just make sure you specify the right scope. This example requires setting the CHAT scope.
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
CommunicationUserIdentifierAndToken result = communicationIdentityClient.createUserAndToken(scopes);
Recently, there's been a new option added to quickly generate Azure Communication Services access tokens for testing - you can do it directly in the Azure Portal.
I just quickly tried the finalized sample code from GitHub and it worked flawlessly. The steps I took:
installed Android Studio + Android 11 SDK (API level 30)
created a Pixel 4 device running Android 11
cloned the repo
replaced the endpoint, firstUserId, secondUserId, firstUserAccessToken with values generated in the Azure Portal
ran the sample + successfully debugged it

Google Cloud Datastore / Mobile Backend Starter - Permissions failure on update/updateAll calls

Using the Mobile Backend Starter (MBS) Android classes (those distributed as a sample project when creating a new project in Google Dev Console and demoed at Google I/O 2013) I'm able to insert new entities to the cloud datastore via calls to CloudBackendMessaging.insertAll or .updateAll. The latter will create entities if none exist so seems functionally identical to insert for new records.
The insertion/creation works fine. However when I attempt to update existing entries in the datastore, I received permissions errors e.g. (from the backend log)
Method: mobilebackend.endpointV1.updateAll
Error Code: 401
Reason: required
Message: Insuffient permission for updating a CloudEntity: XXXXXX by: USER: YYYYYYY
which results in a matching access error in the logcat client side.
In all cases I am using Secured access authenticating with a valid Google account (my own).
The entities being inserted are thus showing as "owned" by my user ID with "updated by" and "created by" showing my Google account's email address.
However when the update of the existing record is made, using exactly the same CloudBackendMessenger object and thus same credentials etc. the backend is telling me I can't update due to permissions issues. But surely if I just made the entity with the same credentials this can't be correct? Looking at the documentation it appears that I should be able to edit entities owned by the same user ID in all cases (regardless of the KindName and whether it is prepended [public], [private] or nothing).
Can anyone who has received permissions errors on UPDATES via Mobile Backend Starter for Datascore please shed any light? I have been banging my head over this for most of today.
I've faced the similar error "Insuffient permission for updating a CloudEntity" when using cloudBackendAsync.update(cloudEntity). I resolved it by making sure the cloudEntity has it's createdAt field set. createdAt is autogenerated and I think I am not supposed to touch it. But it worked for me. In my case I am first obtaining list of cloud entities. This is when I get createdAt field of cloud entities. Then when I am updating I setting the createdAt field from previously obtained entities.
Edit: Had to do similar thing for owner field also.
Similar to one of the comments above, I successfully got around this by getting the original CloudEntity before doing the insert/update/delete function.
CloudQuery cq = new CloudQuery("datastoretype");
cq.setLimit(1);
cq.setFilter(Filter.eq("_id",id));
cloudEntity.setId(id);
mProcessingFragment.getCloudBackend().get(cloudEntity, handler);
Thereafter it was trivial to do the following:
mProcessingFragment.getCloudBackend().update(cloudEntity, handler);
The docs definitely ought to be more clear on this, whether it is a strict requirement or bug.
The answers posted so far work around the problem if you don't mind all users being able to access the entity you are trying to update. However, a better solution that retains the access permissions is detailed by google here - https://cloud.google.com/cloud/samples/mbs/authentication
If you want to pass the user’s Google Account info to the backend on
each call, use the CloudBackend#setCredential() method (also available
on the subclasses, CloudBackendAsync and CloudBackendMessaging) to set
a GoogleAccountCredential object before calling any Mobile Backend
methods.
GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(this, "<Web Client ID>");
credential.setSelectedAccountName("<Google Account Name>");
cloudBackend.setCredential(credential);
Setting credientials enables the client to operate when the backend is
in “Secured by Client ID” mode and also sets createdBy/updatedBy/owner
properties of CloudEntity automatically.

Protecting my Google App Engine API Endpoints

I have been doing a lot of research recently on securing my app engine. Currently, I've been reading through the question below and the links in that question:
How do I restrict Google App Engine Endpoints API access to only my Android applications?
However, it doesn't answer my problem. My question is similar to the question above, restricting access to my endpoint API to only my app. The guy seemed to have got it working when he inputs a correct email into the credentials.
My question is if I can achieve the same results without having to input any credentials. I want it so that only my app can use my endpoint API so to prevent other apps from abusing it and using up my quota. I already got a client id for my android application, and have placed it within my #API annotation. To test if it worked, I made a random value for the client id in the #API notation of another api class. However, my app was still able to use methods from both class. Any help?
-Edit-
From reading from the docs and researching further, the endpoint way of authorizing apps is by authenticating the user and for my API to check if user is null. My question is that in the process of authenticating the user, is Google somehow able to read my app's SHA1 fingerprint and authorize it to its list of client ids? If so, how can I replicate this process in my endpoint so that I check the SHA1 fingerprint of the app making the request and compare it to a set value? I don't understand the mechanics behind the endpoints very well, so correct me if I am understanding this wrong.
If the android app has access, then the user has access. A motivated party has many options for inspecting your protocol, including putting the device behind transparent proxy or simply running the app through a debugger. I do suggest running your app through ProGuard before publishing, as this will make the process [a bit] more difficult.
Ultimately, you'll need to make your appengine API robust against untrusted parties. This is simply the state of the web.
How you can protect your endpoint API is described here: http://android-developers.blogspot.com/2013/01/verifying-back-end-calls-from-android.html
The secret is that you request a token from Google Play using the following scope: audience:server:client_id:9414861317621.apps.googleusercontent.com where 9414861317621.apps.googleusercontent.com is your ClientId.
Google Play will look up the id at your endpoints app and return a Google-signed JSON Web Token if it finds the id. Then you pass that id in with your request. Above article says you should pass it in with the body. I would possibly rather add another parameter for that because otherwise you can't pass your own entities anymore. Anyway, your server backend receives the token, and you ask Google as described if it is authentic, before you process the API request.
If you pass in the token using an extra parameter, you can catch it on the server side by adding HttpServletRequest to your endpoint signature and then using request.getHeader("Yourname") to read it out. Make sure you never add the parameter as a URL parameter as it may be logged somewhere.
public void endpointmethod(
// ... your own parameters here
final HttpServletRequest request
) throws ServiceException, OAuthRequestException {
request.getHeader("YourHeaderName") // read your header here, authenticate it with Google and raise OAuthRequestException if it can't be validated
On the Android side you can pass in your token when you build the endpoint api, like this, so you don't have to do it with each and every request:
Yourapiname.Builder builder = new Yourapiname.Builder(AndroidHttp.newCompatibleTransport(), getJsonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) {
httpRequest.setHeader(...);
}})
Hope this helps you make your endpoints API secure. It should.

getting Google oauth authorization token from Android- return with invalid_scope/ Unknown error

I try to use Google oauth to authenticate users on my android app.
Then I would like to send it to my app server so it can connect at any time with Google calendar.
I tried to use
GoogleAuthUtil.getToken(getApplicationContext(), mAccountName, mScope);
Following this article:
https://developers.google.com/accounts/docs/CrossClientAuth
When I use it with scope
mScope = "oauth2:https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
I get a token, which is valid for an hour
But when I try to get an authorization code (so I can get a refresh token that is valid for longer time, using
mScope2 ="oauth2:server:client_id:{CLIENT_ID}.apps.googleusercontent.com"+ ":api_scope:https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
I receive either "invalid_scope" or "Unknown" exceptions.
What am I doing wrong?
EDIT:
OK, After creating a new app on google API console and adding plus.login to the scope I get a code, but for some reason my server can't resolve this token. When tying to resolve server gets an error about the redirection URL.
BTW, When I do the web flow with same parameters it works.
OK, found the solution, I expected Google to have a lot better documentation about working with Google Oauth and Android. A few things you have to know to work with Android and offline token
When you create google Client ID Don't create a service application before you create a web application
Must include https://www.googleapis.com/auth/plus.login in your scope
The weirdest, to resolve the one time authorization code on my server, I had to use the redirection URL from the Android client ID details (which doesn't even look like a url) and not from the Web client details on Google API console.
That scope string is only documented to work when passed to GoogleAuthUtil(), see http://developer.android.com/reference/com/google/android/gms/auth/GoogleAuthUtil.html, on Android. But it would be cool if it worked on iOS too; our infrastructure there is a little behind where we’re at on Android.
I have had the same issue then i realised that my app is not published and is in debug mode, so i had to add test users to the Google project -> Consent Screen, then i was able to fetch the token for the added test user.
You just need to follow the correct steps/format for specifying the scopes. Find them here https://developers.google.com/android/guides/http-auth#SpecifyingScopes

How to use a server to store/receive data?

I am wondering what is required to setup a server so that you can store data on it, and then have an application send requests to it to store and receive data. More specifically, I am working on an Android application where a user will generate data and then that should be stored on a server so other users can access it. But I do not know how setting up a server to be capable of this works. I have worked on Android applications in the past that sends requests (put, post, get, etc) to a server, but that back end was already set up for me. Any info or resources about setting this up would be great.
There are many, many different ways to accomplish this.
Since you're already working with a Google technology, Android - you could start by creating a Google App Engine project. Following the tutorials you can get started setting up a simple back end solution that will store data for you and you can make requests to it for that data.
Another advantage to this for you is that you don't have to learn how to install software on a server and all the dependencies that arise from that, etc. Simply set up a new account and push-button deploy through Eclipse or command line.
And since you've used Java in Android, you can use JAva for Google App Engine (GAE) too!
Getting started: http://code.google.com/appengine/docs/java/gettingstarted/introduction.html
You can try ready to use BAAS/PAAS services to store your data, e.g. QuickBlox for Android http://quickblox.com/developers/Android, where you can manipulate with your data with few strings
QBLocation location = new QBLocation();
location.setLatitude(35.0);
location.setLongitude(53.0);
location.setStatus("I'm at this place");
String someImportantString = "Dr. Henry Walton Indiana Jones";
QBLocations.createLocation(location, new QBCallbackImpl() {
#Override
public void onComplete(Result result, Object context) {
// retrieve context object inside callback
String passedContextObject = (String) context;
System.out.println(passedContextObject);
// do stuff with result
}
}, someImportantString);
All logic of data exchange with server is encapsulated in framework.

Categories

Resources