Google+ API ItemScope getRatingValue returns null string - android

In my android app using the Google+ API, I am able to write moments of type "ReviewActivity" with the following code :
ItemScope rating = new ItemScope.Builder()
.setType("http://schema.org/Rating")
.setRatingValue(Float.toString(oeuvre.getRating()))
.setBestRating("5").setWorstRating("0").build();
ItemScope result = new ItemScope.Builder()
.setType("http://schema.org/Review").setName(titre)
.setUrl(urlfreebase)
.setDescription(oeuvre.getNomPeintre()).setReviewRating(rating)
.build();
ItemScope target = new ItemScope.Builder().setUrl(urlfreebase).build();
Moment moment = new Moment.Builder()
.setType("http://schemas.google.com/ReviewActivity")
.setTarget(target).setResult(result).build();
if (monPlusClient.isConnected()) {
monPlusClient.writeMoment(moment);
}
Its works, I can read them in my Google+ profile with my Desktop.
When I load moments, at the beginning of my app, I am also able to read my moments, but I am unable to get the rating value that was chose by the user.
In my listener :
public void onMomentsLoaded(ConnectionResult status,
MomentBuffer momentBuffer, String nextPageToken, String updated) {
...
}
I receive this target :
{"description":"Pablo Picasso","url":"https:\/\/developers.google.com\/+\/web\/snippet\/examples\/review","id":"https:\/\/developers.google.com\/+\/web\/snippet\/examples\/review","reviewRating":{"ratingValue":"4.0","worstRating":"0","bestRating":"5"},"name":"Le Pigeon aux petits pois"}
As you can see the rating is correctly set :
"reviewRating":{"ratingValue":"4.0","worstRating":"0","bestRating":"5"}
but when I try to read it through the API with :
ItemScope res = m.getResult();
String titre = res.getName();
String desc = res.getDescription();
String streval = res.getRatingValue();
the String streval is always null

I solved this by using JSON strings :
ItemScope res = m.getResult();
String titre = res.getName();
String desc = res.getDescription();
try {
JSONObject jres = new JSONObject(res.toString());
JSONObject jeval = jres.getJSONObject("reviewRating");
String streval = jeval.getString("ratingValue");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

check playerSSign fail

When verifying the signature, the background server displays {"rtnCode":-1,"errMsg":"check playerSSign fail"}
The data provided by the client is
if(huaweiid != null){
PlayersClient player = Games.getPlayersClient(this, huaweiid);
player.getCurrentPlayer().addOnSuccessListener(new OnSuccessListener<Player>() {
#Override
public void onSuccess(Player player) {
String ts = player.getSignTs();
String playerId = player.getPlayerId();
int playerLevel = player.getLevel();
String playerSign = player.getPlayerSign();
//String displayName = player.getDisplayName();
//Uri hiResImageUri = player.getHiResImageUri();
//Uri iconImageUri = player.getIconImageUri();
JSONObject jo = new JSONObject();
try {
jo.put("signTs", ts);
jo.put("playerId", playerId);
jo.put("playerLevel", playerLevel);
jo.put("playerSign", playerSign);
EditText ed = findViewById(R.id.editText);
ed.setText(jo.toString());
Log.i("huawei user info", jo.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.i("huawei user info", Objects.requireNonNull(e.getMessage()));
}
}
});
}
Use the preceding four data items and the following description document:
https://developer.huawei.com/consumer/cn/doc/HMSCore-References-V5/verify-login-signature-0000001050123503-V5
An error always occurs during the verification in the background.
{"rtnCode":-1,"errMsg":"check playerSSign fail"}
appId/cpid is obtained from agconnect-services.json and agconnect-services.json is downloaded from the background.
what’s the reason?
The following table describes the typical setting errors of the input parameters. Please verify the parameter settings.
https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/faq-check-login-0000001050746133-V5

Issue with azure cognitive translation services

After getting the following code to work reliably for a month or so, it stopped working reliably a couple of days ago. About half the time it returns a properly translated string and the other half of the time it returns one of the following two messages:
java.io.FileNotFoundException:
https://api.cognitive.microsoft.com/sts/v1.0/issueToken
java.net.UnknownHostException: Unable to resolve host
"api.microsofttranslator.com": No address associated with hostname
The timing of this problem's beginning coincided with the expiration of my free azure cognitive services account however I migrated to a pay-as-you-go account yesterday and the problem continues.
Why is this happening?
static class translateMessageX extends AsyncTask<String, Void, String>
{
//input string array of 3 items
//[0]is the message to be translated
//[1]is the from language i.e. "english"
//[2]is the to language i.e. "spanish"
//[3]"echo" or "received"
String retString;
String inString = null;
String messageType = null;
String URLHolder = ""; //hold the URL here while we are translating the text
#Override
protected String doInBackground(String... params)
{
inString = params[0];
String from = params[1];
String to = params[2];
messageType = params[3];
int urlStart = inString.indexOf("http");
if (!(urlStart == -1))
{
URLHolder = inString.substring(urlStart);
inString = inString.substring(0, urlStart -1);
}
else
{
URLHolder = "";
}
Integer mesChars = params[0].length();
Integer tCharsLeft = GlobalStuff.getTranslationsFromSP();
if (tCharsLeft > 0)
{
if (tCharsLeft < mesChars) //we charge for both 'echo' and 'received' translations
{
GlobalStuff.updateTranslationInventory(tCharsLeft * -1);
}
else
{
GlobalStuff.updateTranslationInventory(mesChars * -1);
}
GlobalStuff.notifyListeners(this, "#uui", "notused", "notused" );
try
{
Language fromLang = GlobalStuff.getLang(from);
Language toLang = GlobalStuff.getLang(to);
//retString = Translate.execute(inString, fromLang, toLang);
//String debugstr = "look at retStr";
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", GlobalStuff.translateKey);
IOUtils.write("", authConn.getOutputStream(), "UTF-8");
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
System.out.println(token);
// Using the access token to build the appid for the request url
String appId = URLEncoder.encode("Bearer "+token, "UTF-8");
String text = URLEncoder.encode(inString, "UTF-8");
String translatorTextApiUrl = String.format("https://api.microsofttranslator.com/v2/http.svc/Translate?appid=%s&text=%s&from=%s&to=%s", appId, text, fromLang, toLang);
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
translateConn.setRequestMethod("GET");
translateConn.setRequestProperty("Accept", "application/xml");
retString = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
String debug = "look at retString";
}
catch (Exception e)
{
retString = e.toString();
}
}
else
{
retString = "OUT OF TRANSLATION CREDITS - " + inString;
}
return retString;
}
#Override
protected void onPostExecute(String result)
{
//rest of logic should be here??
String debug = "look at result";
String answer = extractTranslation(result);
.. . . .
Host not found looks like a simple connectivity error. These hosts do exist.
You can void the call to the token service by passing the key in the call to api.microsofttranslator.com directly:
https://cognitive.uservoice.com/knowledgebase/articles/1815385-api-translator-text-speech-using-the-api-key
That fixes one of the host not found problems, but not the other.
I would recommend though to not embed the key in the client application. It is safer to call the translator service from your own proxy service, where the proxy is able to safely identify your client as your client.

How get extra parameter from dynamic link using Firebase?

I have created dynamic link manually and i set some additional parameters on the link, like this: https://XXXXX.goo.gl/?link=https%3A%2F%2Fairbanq.send.com%2Fsendmoney&apn=com.xxxx.xxxx&amv=1&username=Adri&amount=7.00
But when the app is opened i just get: "https:// airbanq.send.com/sendmoney"
without the addiotional parameters
i am using this sample code
https://github.com/firebase/quickstart-android/tree/master/dynamiclinks
any help please,
Thanks
My code
public String buildDeepLink() {
// Get the unique appcode for this app.
String appCode = AirBanqApp.mContext.getString(R.string.app_code);
// Get this app's package name.
String packageName = AirBanqApp.mContext.getPackageName();
// Build the link with all required parameters
Uri.Builder builder = new Uri.Builder()
.scheme("https")
.authority(appCode + ".app.goo.gl")
.path("/")
.appendQueryParameter("link", deepLink)
.appendQueryParameter("apn", packageName);
// If the deep link is used in an advertisement, this value must be set to 1.
if (isAd) {
builder.appendQueryParameter("ad", "1");
}
// Minimum version is optional.
if (minVersion > 0) {
builder.appendQueryParameter("amv", Integer.toString(minVersion));
}
if (!TextUtils.isEmpty(androidLink)) {
builder.appendQueryParameter("al", androidLink);
}
if (!TextUtils.isEmpty(playStoreAppLink)) {
builder.appendQueryParameter("afl", playStoreAppLink);
}
if (!customParameters.isEmpty()) {
for (Map.Entry<String, String> parameter : customParameters.entrySet()) {
builder.appendQueryParameter(parameter.getKey(), parameter.getValue());
}
}
// Return the completed deep link.
return builder.build().toString();
}
Thats was my solution
i solved my issue, i assumed the "apn", "username" and "amount" they were part of the parameter "LINK" in the url, but no when i add the "&" i am adding parts to the main url, to add parameters to the "LINK" field i need to create first the url like this
https://airbanq.send.com/sendmoney?username=Adri&amount=7.00
then use URLEncoder.encode(queryParameters.toString(), "UTF-8");
to generate this
https%3A%2F%2Fairbanq.send.com%2Fsendmoney%253Fusername%253DAdri%2526amount%253D7.00
and then append to main url
https://xxxx.app.goo.gl/?link=https%3A%2F%2Fairbanq.send.com%2Fsendmoney%253Fusername%253DAdri%2526amount%253D7.00&apn=com.airbanq.airbanqapp&amv=1
public String buildDeepLink() {
// Get the unique appcode for this app.
String appCode = AirBanqApp.mContext.getString(R.string.app_code);
// Get this app's package name.
String packageName = AirBanqApp.mContext.getPackageName();
String queryParamters = "";
try {
queryParamters = generateQueryParameters();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (!TextUtils.isEmpty(queryParamters)) {
deepLink = deepLink + queryParamters;
}
// Build the link with all required parameters
Uri.Builder builder = new Uri.Builder()
.scheme("https")
.authority(appCode + ".app.goo.gl")
.path("/")
.appendQueryParameter("link", deepLink)
.appendQueryParameter("apn", packageName);
// If the deep link is used in an advertisement, this value must be set to 1.
if (isAd) {
builder.appendQueryParameter("ad", "1");
}
// Minimum version is optional.
if (minVersion > 0) {
builder.appendQueryParameter("amv", Integer.toString(minVersion));
}
if (!TextUtils.isEmpty(androidLink)) {
builder.appendQueryParameter("al", androidLink);
}
if (!TextUtils.isEmpty(playStoreAppLink)) {
builder.appendQueryParameter("afl", playStoreAppLink);
}
// Return the completed deep link.
return builder.build().toString();
}
private String generateQueryParameters() throws UnsupportedEncodingException {
StringBuilder queryParameters = new StringBuilder();
//server purposes
queryParameters.append("?*code*");
if (!customParameters.isEmpty()) {
for (Map.Entry<String, String> parameter : customParameters.entrySet()) {
queryParameters.append(String.format("&%1s=%2s", parameter.getKey(), parameter.getValue()));
}
}
return URLEncoder.encode(queryParameters.toString(), "UTF-8");
}
The official answer is that you need to escape/encode a URL string so that it can be safely placed inside a URL query.
I wish Firebase dynamic links would just say that about the link.
For Golang:
url.QueryEscape(urlstring)

asp.NET login using HTTP post method with jsoup

I am recently trying to develop a android app for my school friends so they do not have to use a web browser but an simple app to check their updated grades and exam schedule but since the school wont give permission to use their DB the only method is to do HTML parsing.
so I found this library Jsoup and an example and started writing my own code but it always brings me the page source of login in page (It doesnt log in at all)
public Document getHTMLsoure() {
Document doc=null;
try {
doc = Jsoup.connect("http://karinca.meliksah.edu.tr")
.data("ctl00$ContentPlaceHolder1$txtKullaniciAdi","usernm")
.data("ctl00$ContentPlaceHolder1$txtSifre", "passwd")
.data("ctl00$ContentPlaceHolder1$btnLogin", "Giriş")
.userAgent("Mozilla")
.post();
} catch (IOException e1) {
e1.printStackTrace();
}
return doc;
}
Please check it.
Result Kullanıcı adı yada şifre hatası !
Response res = Jsoup
.connect("https://karinca.meliksah.edu.tr/View/Login")
.userAgent("Mozilla")
.execute();
Document doc = res.parse();
String eventArgument = doc.select("input[name=__EVENTARGUMENT]").val();
String viewState = doc.select("input[name=__VIEWSTATE]").val();
String viewStateGenerator = doc.select("input[name=__VIEWSTATEGENERATOR]").val();
String eventValidation = doc.select("input[name=__EVENTVALIDATION]").val();
String asyncPost = "true";
String ct = "";
String body = doc.body().html();
int indexOf = body.indexOf("Sys.WebForms.PageRequestManager._initialize(");;
if(indexOf > -1){
int indexEnd = body.substring(indexOf).indexOf("');");
if(indexEnd > -1){
String temp = body.substring(indexOf, indexOf+indexEnd);
int indexStart = temp.lastIndexOf("'");
ct = temp.substring(indexStart+1,temp.length());
}
}
Document doc1 = Jsoup.connect("https://karinca.meliksah.edu.tr/View/Login.aspx")
.referrer("https://karinca.meliksah.edu.tr/View/Login")
.cookies(res.cookies())
.data(ct+"$ContentPlaceHolder1$ScriptManager2",ct+"$ContentPlaceHolder1$UpdatePanel1|"+ct+"$ContentPlaceHolder1$btnLogin")
.data(ct+"$ContentPlaceHolder1$txtKullaniciAdi","usernm")
.data(ct+"$ContentPlaceHolder1$txtSifre", "passwd")
.data("__EVENTTARGET",ct+"$ContentPlaceHolder1$btnLogin")
.data("__EVENTARGUMENT",eventArgument)
.data("__VIEWSTATE",viewState)
.data("__VIEWSTATEGENERATOR",viewStateGenerator)
.data("__EVENTVALIDATION",eventValidation)
.data("__ASYNCPOST",asyncPost)
.userAgent("Mozilla")
.post();
System.out.println(doc1.html());

Android convert CID location to Coordinates

I built an android app which can handle a share intent from Google Maps and show it's coordinates.
The problem is that they send a short url which I decode with Google's url shortner api and in some cases, the result long link is of this type: http://maps.google.com/?cid=3635533832900933072&hl=en&gl=us.
Can anyone help me on how to get the coresponding coordinates to "cid=3635533832900933072"
As far as I know there is no public API to get the location from a cid.
However, a possible workaround would be to parse the Google Maps output to obtain the latitude and longitude (though it may be brittle, if they change the result format).
(Although the url contains output=json, it's not actually json -- that's why I parse it with substring() and such instead of using JSONObject).
Try this code:
public static LatLng getCidCoordinates(String cid)
{
final String URL_FORMAT = "http://maps.google.com/maps?cid=%s&q=a&output=json";
final String LATLNG_BEFORE = "viewport:{center:{";
final String LATLNG_AFTER = "}";
final String LATLNG_SEPARATOR = ",";
final String LAT_PREFIX = "lat:";
final String LNG_PREFIX = "lng:";
try
{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(String.format(URL_FORMAT, cid));
HttpResponse response = client.execute(get);
String text = EntityUtils.toString(response.getEntity(), "UTF-8");
int startIndex = text.indexOf(LATLNG_BEFORE);
if (startIndex == -1)
return null;
startIndex += LATLNG_BEFORE.length();
int endIndex = text.indexOf(LATLNG_AFTER, startIndex);
// Should be "lat:<number>,lng:<number>"
String[] parts = text.substring(startIndex, endIndex).split(LATLNG_SEPARATOR);
if (parts.length != 2)
return null;
if (parts[0].startsWith(LAT_PREFIX))
parts[0] = parts[0].substring(LAT_PREFIX.length());
else
return null;
if (parts[1].startsWith(LNG_PREFIX))
parts[1] = parts[1].substring(LNG_PREFIX.length());
else
return null;
return new LatLng(Double.parseDouble(parts[0]), Double.parseDouble(parts[1]));
}
catch (NumberFormatException e)
{
e.printStackTrace();
return null;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
After reading this post yesterday, I found a new method to do it. I hope Google do not close this new API and hidden parameter. :)
You can use this API hidden parameter to get the coordinater. Usage: https://maps.googleapis.com/maps/api/place/details/json?cid=YOUR_CID&key=YOUR_KEY
It returns a result contains formatted address, place_id, name of the address and GPS coordinater.
Please see my blog to see more detail: https://leonbbs.blogspot.com/2018/03/google-map-cid-to-placeid-or-get.html
In latest Google Maps update, the share intent contains the address name in the body which can be decoded with Geocoder into coordinates.

Categories

Resources