Programmatically Fetching Google+ status updates - java

Is there a way to programmatically fetch Google+ updates for a user's profile? I can't seem to find much in the documentation at https://developers.google.com/+/api/latest/people and http://developer.android.com/reference/com/google/android/gms/plus/model/people/Person.html about fetching statuses. I would like to fetch the data by making an HTTP request or if there is some sort of SDK for Android that will help me, that would work to.

The API you are looking for is plus.activities.list. This will list the Google+ equivalent of Facebook status updates. The referenced page has example code to get you started.
When accessing the API, you should use the Google API client as documented here.

The following code will be useful to retrieve the Http responses.
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.zip.GZIPInputStream;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GooglePlusStatusHelper {
public GooglePlusStatusHelper() {
}
public static void main(String... args) {
GooglePlusStatusHelper googlePlusStatusHelper = new GooglePlusStatusHelper();
try {
googlePlusStatusHelper.tagsUsed();
} catch (IOException e) {
e.printStackTrace();
}
}
private void tagsUsed() throws IOException {
URL url = createQuery("users");
Type dataType = new TypeToken<Wrapper<Status>>(){}.getType();
Status status = executeQuery(url, dataType);
System.out.println(status);
}
private URL createQuery(String inputParam) throws MalformedURLException {
String baseUrl = "http://api.example.com/" + inputParam ;
System.out.println(baseUrl);
URL url = new URL(baseUrl);
return url;
}
private Status executeQuery(URL url, Type clz) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
System.out.println("Response Code:" + conn.getResponseCode());
System.out.println("Response Message:" + conn.getResponseMessage());
System.out.println("TYPE:" + conn.getContentType());
InputStream content = conn.getInputStream();
String encoding = conn.getContentEncoding();
if (encoding != null && encoding.equals("gzip")) {
content = new GZIPInputStream(content);
}
String result = new Scanner(content, "UTF-8").useDelimiter("\\A").next();
content.close();
Gson gson = new Gson();
return gson.fromJson(result, clz);
}
}
Status class :
public class Status {
private int count;
private String status;
......
public String toString() {
String result = "\ncount: " + count +
"\status:" + status;
result = result + "\n------------";
return result;
}
}

Related

Is there a way to put a kind of identificator to asychronous requests?

I have a server and a client that sends requests. I don't need to identify the requests when it works in synch mode. But in asynch mode each request must have an identificator, so I could be sure that the response corresponds to exact request. The server is not to be updated, I have to put the identificator in the client's code. Is there a way do do it? I can't find out any.
Here is my main class. I guess all must be clear, the class is very simple.
public class MainAPITest {
private static int userId = 0;
private final static int NUM_OF_THREADS = 10;
private final static int NUM_OF_USERS = 1000;
public static void main(String[] args) {
Security.addProvider(new GammaTechProvider());
ExecutorService threadsExecutor = Executors.newFixedThreadPool(NUM_OF_THREADS);
for (int i = 0; i < NUM_OF_USERS; i++) {
MyRunnable user = new MyRunnable();
userId++;
user.uId = userId;
threadsExecutor.execute(user);
}
threadsExecutor.shutdown();
}
}
class MyRunnable implements Runnable {
int uId;
#Override
public void run() {
try {
abstrUser user = new abstrUser();
user.setUserId(uId);
user.registerUser();
user.chooseAndImplementTests();
user.revokeUser();
} catch (Exception e) {
e.printStackTrace();
}
}
}
User class describes the user's behaviour. It is long enough, idk if it is needed here. User runs a number of random tests. Each test has its own class that extends abstract test class, where the http connection is established:
import org.json.JSONObject;
import javax.xml.bind.DatatypeConverter;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public abstract class abstractRESTAPITest {
protected String apiUrl;
public abstractRESTAPITest() {
}
protected byte[] sendRequest(JSONObject jsonObject) throws IOException {
return this.sendRequest(jsonObject, (String) null, (String) null);
}
protected byte[] sendRequest(JSONObject jsonObject, String username, String password) throws IOException {
HttpURLConnection httpURLConnection = (HttpURLConnection) (new URL(this.apiUrl)).openConnection();
if (username != null && password != null) {
String userPassword = username + ":" + password;
httpURLConnection.setRequestProperty("Authorization", "Basic " + DatatypeConverter.printBase64Binary(userPassword.getBytes()));
}
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setDoOutput(true);
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.write(jsonObject.toString().getBytes());
dataOutputStream.flush();
System.out.println("REST send: " + jsonObject.toString());
if (httpURLConnection.getResponseCode() != 200) {
System.out.println("REST send error, http code " + httpURLConnection.getResponseCode() + " " + httpURLConnection.getResponseMessage());
throw new IOException();
} else {
byte[] responseBody = null;
StringBuilder data = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
data.append(line);
responseBody = data.toString().getBytes();
}
if (br != null) {
br.close();
}
return responseBody;
}
}
public abstract boolean test();
}
Now I am trying to transform the httpUrlConnection part of the code into a kind of this.
Jsonb jsonb = JsonbBuilder.create();
var client = HttpClient.newHttpClient();
var httpRequest = HttpRequest.newBuilder()
.uri(new URI(apiUrl))
.version(HttpClient.Version.HTTP_2)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonb.toJson(jsonObject)))
.build();
client.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());
It must send a JSON request and receive JSON response. HttpClient, introduced in Java11, has sendAsync native method, so I try to use it. But I don't understand fully how it works, so I have no success.

Yandex Api not translating properly in eclipse

Here is my code in TranslateAPI.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
public class TranslateAPI {
public static final String API_KEY = "pdct.1.1.20180924T090857Z.3e14b8b207704aef.9bdc409229b123003526815bb7062ed42616f26a";
private static String request(String URL) throws IOException {
URL url = new URL(URL);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStream inStream = urlConn.getInputStream();
String recieved = new BufferedReader(new InputStreamReader(inStream)).readLine();
System.setProperty("http.agent", "Chrome");
String agent = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("http.agent"));
inStream.close();
return recieved;
}
public static Map<String, String> getLangs() throws IOException {
String langs = request("https://translate.yandex.net/api/v1.5/tr.json/getLangs?key=" + API_KEY + "&ui=en");
langs = langs.substring(langs.indexOf("langs")+7);
langs = langs.substring(0, langs.length()-1);
String[] splitLangs = langs.split(",");
Map<String, String> languages = new HashMap<String, String>();
for (String s : splitLangs) {
String[] s2 = s.split(":");
String key = s2[0].substring(1, s2[0].length()-1);
String value = s2[1].substring(1, s2[1].length()-1);
languages.put(key, value);
}
return languages;
}
public static String translate(String text, String sourceLang, String targetLang) throws IOException {
String response = request("https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + API_KEY + "&text=" + text + "&lang=" + sourceLang + "-" + targetLang);
return response.substring(response.indexOf("text")+8, response.length()-3);
}
AND in workerthread.java:
String s=TranslateAPI.detectLanguage(abc);
System.out.println(s);
However,I am getting the follwing errror:
Server returned HTTP response code: 403 for URL: https://translate.yandex.net/api/v1.5/tr.json/detect?key=pdct.1.1.20180924T090857Z.3e14b8b207704aef.9bdc409229b123003526815bb7062ed42616f26a&text=cat
Can you please help? Thanks in advance
You are getting a 401 Error thus Your API Key is Invalid,
You can always go to Yandex's Developers page to get a new one.
Its always great to publish your private API here :D

Nested Json using Gson returning a null value

The project I am working on is trying to communicate with the FDA API and retrieve certain information. However, with my nested JSON, the object I am trying to retrieve is returning a null value. Does anybody know what I am doing wrong? Thank you and please let me know if I am missing any information.
URL I am trying to access information from:
https://api.fda.gov/drug/label.json?
JSON Tester Class
package com.example.user.searchbarapp;
import java.net.*;
import java.io.*;
import com.google.gson.*;
public class JSONTester {
public static void main(String[] args) throws Exception {
Gson g = new Gson();
URL FDAServer = new URL("https://api.fda.gov/drug/label.json?");
HttpURLConnection conn = (HttpURLConnection)
FDAServer.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8");
Medication advil = g.fromJson(inputStream, Medication.class);
System.out.print(advil);
}
}
Medication Class
package com.example.user.searchbarapp;
import java.net.URL;
import java.util.Arrays;
public class Medication {
private NestedMedication[] NestedMedication;
public Medication(com.example.user.searchbarapp.NestedMedication[] nestedMedication) {
NestedMedication = nestedMedication;
}
public com.example.user.searchbarapp.NestedMedication[] getNestedMedication() {
return NestedMedication;
}
public void setNestedMedication(com.example.user.searchbarapp.NestedMedication[] nestedMedication) {
NestedMedication = nestedMedication;
}
#Override
public String toString() {
return "Medication{" +
"NestedMedication=" + Arrays.toString(NestedMedication) +
'}';
}
}
NestedMedication Class
package com.example.user.searchbarapp;
public class NestedMedication {
String route;
#Override
public String toString() {
return "NestedMedication{" +
"route='" + route + '\'' +
'}';
}
}
Output
Medication{NestedMedication=null}
Process finished with exit code 0

Deploy a .bpmn file via REST

i want to deploy a BPMN-file with the REST-API of Activiti. But i always get a Bad Request (400) error...
Has anybody an idea what i'm doing wrong??? I use restlet to upload my code. My code is below.
Thank your very much :)
import java.io.File;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Disposition;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.representation.FileRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
public class REST {
private static String REST_URI = "http://localhost:8080/activiti-rest/service";
private static ClientResource getClientResource(String uri) {
ClientResource resource = new ClientResource(uri);
resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "kermit", "kermit");
return resource;
}
public static JSONArray postDeployments() throws JSONException, IOException {
String deploymentURI = REST_URI + "/repository/deployments";
File file = new File("C:\\Users\\Test\\Desktop\\process.bpmn");
FileRepresentation fr = new FileRepresentation(file, MediaType.TEXT_PLAIN);
System.out.println("Size sent: " + fr.getSize());
try{
Representation response = getClientResource(deploymentURI).post(file, MediaType.MULTIPART_FORM_DATA);
JSONObject object = new JSONObject(response.getText());
if (object != null) {
JSONArray dataArray = (JSONArray) object.get("data");
return dataArray;
}
}
catch(Exception e){
System.out.println("Error:");
e.printStackTrace();
}
return null;
}
}
You are not generating the multipart-form-data request properly with Restlet.
You could have done the following to deploy a business process to activiti REST API:
String deploymentURI = REST_URI + "/repository/deployments";
File file = new File("/home/toto/fake-process.bpmn20.xml");
FileRepresentation entity = new FileRepresentation(file, MediaType.MULTIPART_FORM_DATA);
FormDataSet fds = new FormDataSet();
FormData fd = new FormData("upload_file", entity);
fds.getEntries().add(fd);
fds.setMultipart(true);
try {
Representation response = getClientResource(deploymentURI).post(fds);
} catch (Exception e) {
System.out.println("Error:");
e.printStackTrace();
}
See also this post

Implements of thread in Android doesn't work

I'm writing a basic application in Android, the application will be connected to MySql server by quest in PHP, in Android Internet connection have to make in diffrent thread, so I create class which implements Runnable interface.
package com.company.opax.loginmysql;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
/**
* Created by opax on 30.08.2015.
*/
public class HttpPostMethod implements Runnable{
private String fileInHost;
private ArrayList<PostParameters> postParameterses;
private StringBuffer postResult;
public HttpPostMethod(String fileInHost, ArrayList<PostParameters> postParameterses){
this.fileInHost = fileInHost;
this.postParameterses = new ArrayList<PostParameters>(postParameterses);
}
public String getResult() {
return postResult.toString();
}
#Override
public void run() {
try {
String urlParameters = generateParameters();
URLConnection conn = initializeUrlConnection();
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
postResult.append(line);
}
writer.close();
reader.close();
} catch (IOException e) {
Log.e("Exception", this.getClass().getName() + " name: " + e.toString());
}
}
private URLConnection initializeUrlConnection() throws MalformedURLException {
URL url = new URL(fileInHost);
URLConnection conn;
try {
conn = url.openConnection();
conn.setDoOutput(true);
}catch(IOException e){
throw new MalformedURLException();
}
return conn;
}
private String generateParameters(){
StringBuffer finishPostQuery = new StringBuffer();
for(PostParameters p : postParameterses){
finishPostQuery.append(p.getNameParam());
finishPostQuery.append("=");
finishPostQuery.append(p.getValueParam());
finishPostQuery.append("&");
}
if(!finishPostQuery.toString().equals("login=seba&password=pass&"))
throw new AssertionError("blad generatora zapytania: " + finishPostQuery);
return finishPostQuery.toString();
}
}
and login class:
public class Login {
private User user;
private final String paramLogin = "login";
private final String paramPass = "password";
public Login(User user){
this.user = user;
}
public boolean tryLogin(){
try{
ArrayList<PostParameters> postParameterses = new ArrayList<>();
postParameterses.add(new PostParameters(paramLogin, user.getUserName()));
postParameterses.add(new PostParameters(paramPass, user.getUserPass()));
HttpPostMethod httpPostMethod = new HttpPostMethod("http://blaba.php", postParameterses);
httpPostMethod.run();
Log.i("bla", httpPostMethod.getResult());
} catch (Exception e) {
Log.i("Exception", e.toString());
}
return false;
}
}
I'm trying to connect in other thread, but I still have an error: 'android.os.NetworkOnMainThreadException'
I would be grateful for the all suggestion what I do wrong.
Instead of:
httpPostMethod.run();
do:
new Thread(httpPostMethod).start();
In case your login call failed for some reasons (timeout, wrong login), you should report that somehow to user - this is what AsyncTask class is for. It allows you to run background code in doInBackkground, and after network operation ends - in onPostExecute you can execute UI related stuff - like show errors/results.
I suggest you two things.
First use AsyncTask instead of pure java threads.
But the main advice is to use a library that make http requests.
I like to use Retrofit, it may handle all request and thread part for you, but there are others.

Categories