JAVA API call Compare response with Previous response - java

I am trying to make api call every 60 mins which returns json response like below:
[{
"queryId" : uniqueID,
"state": "FINISHED | FAILED | RUNNING"
},
{
"queryId" : uniqueID,
"state": "FINISHED | FAILED | RUNNING"
},
]
I want to run first time and prepare each document and store and for the next api call i want to compare current response with previous response with below condition:
1: if same queryId exit in previous response and state as FINISHED | FAILED don't consider to store.
So idea is to get every 60 secs new queryID which is running in system and store it for further analysis.
Below is my sample snipeet:
#Override
public void run() {
stopRequested = false;
while (!stopRequested)
{
try {
System.setProperty("javax.net.ssl.trustStore","");
System.setProperty("javax.net.ssl.trustStorePassword","");
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("", "".toCharArray());
}
});
URL url = new URL("");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.connect();
int responsecode = conn.getResponseCode();
if (responsecode != 200) {
throw new RuntimeException("HttpResponseCode: " + responsecode);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
JSONArray array = new JSONArray(response.toString());
System.out.println(array.length());
JSONArray presResponse = array;
for(int i=0; i < array.length(); i++)
{
JSONObject object = array.getJSONObject(i);
// Query
String queryId = object.getString("queryId");
String state = object.getString("state");
if (checkQryExit(queryId, state, presResponse)) {
String strResponse = String.format // metric return in json
("{\"queryId\":\"%s\"," + "\"state\":\"%s\"}", queryId, state);
System.out.println(strResponse);
}
}
} catch (Exception e) {
e.printStackTrace();
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Related

Send data(Client_id=1,Staff_id=2) from android application to tomcat server

i want to send data from android application to tomcat java server.
Data is just one is client_id which is 1 and second is staff_id which is 2.
after authenticate the client id and staff id from tomcat show me a toast of success....please help...
Code is here
public class MyAsyncTasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// display a progress dialog for good user experiance
}
#Override
protected String doInBackground(String... params) {
// implement API in background and store the response in current variable
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.1.13:8080/digitaldisplay/s/m/data");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
current += (char) data;
data = isw.read();
System.out.print(current);
}
// return the data to onPostExecute method
return current;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
return current;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(Register.this, "success", Toast.LENGTH_SHORT).show();
Log.d("data", s.toString());
// dismiss the progress dialog after receiving data from API
try {
// JSON Parsing of data
JSONArray jsonArray = new JSONArray(s);
JSONObject oneObject = jsonArray.getJSONObject(0);
// Pulling items from the array
client = Integer.parseInt(oneObject.getString("client"));
staff = Integer.parseInt(oneObject.getString("staff"));
} catch (JSONException e) {
e.printStackTrace();
}
} }}
The logic in your code looks off to me. This is the pattern I usually follow when making a REST call from an activity using HttpURLConnection:
try {
String endpoint = "http://192.168.1.13:8080/digitaldisplay/s/m/data";
URL obj = new URL(endpoint);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST"); // but maybe you want GET here...
con.setConnectTimeout(10000);
con.setDoInput(true);
con.setDoOutput(true);
JSONObject inputJSON = new JSONObject();
inputJSON.put("Client_id", 1);
inputJSON.put("Staff_id", 2);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(inputJSON.toString());
writer.flush();
writer.close();
os.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
} catch (SocketTimeoutException se) {
// handle timeout exception
responseCode = -1;
} catch (Exception e) {
// handle general exception
responseCode = 0;
}
The only major change in adapting the above code for GET would be that you wouldn't write your input data to the connection. Instead, you would just append query parameters to the URL. I am possibly guessing that you need POST here, since your URL doesn't have any query parameters in it.

Android Php Mysql Date Range Search

Can anyone help me? I'm developing an android app in android studio which will implement a Date Range search. the user will select the between date the "FROM" date and the "TO" date then the result will filter in a recyclerview. I'm using php mysql as our query. Hoping for a good and better reply. Thanks in advance
private class FilterDate extends AsyncTask {
ProgressDialog pdLoading = new ProgressDialog(Complaint.this);
HttpURLConnection conn;
URL url = null;
String from;
String to;
public FilterDate(String from,String to) {
this.from = from;
this.to = to;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.0.100/Android/filter.php");
} catch (MalformedURLException e) {
e.printStackTrace();
// TODO Auto-generated catch block
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
// add parameter to our above url
Uri.Builder builder1 = new Uri.Builder().appendQueryParameter("from", from);
String query1 = builder1.build().getEncodedQuery();
OutputStream os1 = conn.getOutputStream();
BufferedWriter writer1 = new BufferedWriter(new OutputStreamWriter(os1, "UTF-8"));
writer1.write(query1);
writer1.flush();
writer1.close();
os1.close();
conn.connect();
Uri.Builder builder2 = new Uri.Builder().appendQueryParameter("to", from);
String query2 = builder2.build().getEncodedQuery();
OutputStream os2 = conn.getOutputStream();
BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os1, "UTF-8"));
writer2.write(query2);
writer2.flush();
writer2.close();
os2.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread suggestion
ArrayList<String> dataList = new ArrayList<String>();
pdLoading.dismiss();
// pdLoading.dismiss();
List<DataComplaints> data = new ArrayList<>();
pdLoading.dismiss();
if (result.equals("no rows")) {
Toast.makeText(Complaint.this, "No Results found for entered query", Toast.LENGTH_SHORT).show();
} else {
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataComplaints healthData = new DataComplaints();
healthData.idNum = json_data.getString("student_number");
healthData.lastName = json_data.getString("lastname");
healthData.firstName = json_data.getString("firstname");
healthData.middleName = json_data.getString("middlename");
healthData.complaint = json_data.getString("common_type");
healthData.medicine = json_data.getString("medicinetype");
healthData.date = json_data.getString("date");
healthData.time = json_data.getString("time");
data.add(healthData);
dataList.add(json_data.getString("date"));
}
strArrData = dataList.toArray(new String[dataList.size()]);
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.studentList);
mAdapter = new AdapterComplaints(Complaint.this, data);
mRVFish.setAdapter(mAdapter);
mRVFish.setLayoutManager(new LinearLayoutManager(Complaint.this));
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(Complaint.this, "Error in Fetching Data", Toast.LENGTH_LONG).show();
Toast.makeText(Complaint.this, "Error!", Toast.LENGTH_LONG).show();
}
}
}
}
This is my query in php:
<?php
$host='127.0.0.1';
$username='root';
$pwd='';
$db="cjc_clinic";
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$From=$_POST['from'];
$To=$_POST['to'];
//$sql="SELECT * from studentcomplaint_view where lastname LIKE '%$name%'";
//$sql="SELECT * FROM studentcomplaint_view where CONCAT(lastname,' ',firstname) LIKE '%$name%'";
//$sql="SELECT * FROM studentcomplaint_view WHERE Date >= '$From' AND Date <='$To'";
$sql="SELECT * FROM studentcomplaint_view WHERE Date BETWEEN '$From' AND '$To'";
$query=mysqli_query($con,$sql);
if($query){
while($row=mysqli_fetch_array($query))
{
$data[]=$row;
}
print(json_encode($data));
}else
{
echo('Not Found ');
}
mysqli_close($con);
?>

Getting "Error parsing data org.json.JSONException: End of input at character 0 of" on reddit API

Hello I'm trying to use this endpoint www.reddit.com/reddits.json to show some list on android and I'm getting this error, below is my code.
I have this asynctask class on my main activity class:
private class AsyncListLoader extends AsyncTask<String, Integer, JSONObject>{
private JSONParser jsonParser = new JSONParser();
private static final String REDEEM_URL = "http://www.reddit.com/reddits.json";
private HashMap<String, String> param = new HashMap<>();
#Override
protected JSONObject doInBackground(String... params) {
JSONObject json = jsonParser.makeHttpRequest(REDEEM_URL, "GET", param);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
else {
Log.d("JSON result", "is null");
}
return null;
}
#Override
protected void onPostExecute(JSONObject s) {
try {
if(!s.has("kind")){
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
else {
JSONObject list = s.getJSONObject("data");
JSONArray childrens = list.getJSONArray("children");
for(int i = 0; i < childrens.length(); i++){
JSONObject o = childrens.getJSONObject(i).getJSONObject("data");
Feed f = new Feed(o.getString("icon_img"),o.getString("banner_img"),o.getString("display_name"));
MainActivity.this.adapter.add(f);
}
}
} catch (JSONException e){
e.printStackTrace();
}
}
}
makehttpRequest when get:
if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
I tested out another json endpoints on the web and they are working. I dont have any idea why is this happening.
EDIT:
No param is being used so the url is fine.
The json is valid, I checked this in differents websites.

Proper Use of Keep Alive For Loop

I'm working to make a thread that monitors a web api to get the latest announcement via JSON. I cannot test this currently, so I'm unsure if anything needs to be changed with this. I've read through other questions but everyone else doesn't seem to be using a loop to keep getting a response.
public void run(){
try {
URL url = new URL(announcementsURL);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Connection", "keep-alive");
http.setUseCaches(false);
http.setAllowUserInteraction(false);
http.setConnectTimeout(10);
http.setReadTimeout(10);
while (true){
http.connect();
int status = http.getResponseCode();
if (status == 201){
BufferedReader br = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
String json = sb.toString();
JSONParser parser = new JSONParser();
JSONObject jsonResponse = (JSONObject) parser.parse(json);
if (!(lastAnnouncement == (long) jsonResponse.get("time"))){
//String announcement = (String) jsonResponse.get("message");
//TODO What to do with announcement...
}
}
http.getInputStream().close();
http.disconnect();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
this.interrupt();
try {
this.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}

HttpUrlConnection sometimes gives EOF exception

I am using HttpUrlConnection and using POST method to get some data from web server. Sometimes, I get the response and at times I get EOFexception
These are the solutions are I have already tried :
1) System.setProperty("http.keepAlive", "false");
2) if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
connection.setRequestProperty("Connection", "close");
}
Below is my code from AsyncTask class;
CODE :
#Override
protected JSONObject doInBackground(KeyValuePair... keyValuePairs) {
JSONObject jsonResponse = new JSONObject();
HttpURLConnection connection = null;
// check if is Internet is available before making a network call
if (isInternetAvailable()) {
try {
jsonResponse = new JSONObject();
URL url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "UTF-8");
if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
connection.setRequestProperty("Connection", "close");
}
// setting post params
StringBuilder builder = new StringBuilder();
for (int i = 0; i < keyValuePairs.length; i++) {
builder.append(URLEncoder.encode(keyValuePairs[i].getKey(), "UTF-8") + "=" + URLEncoder.encode(keyValuePairs[i].getValue(), "UTF-8") + "&");
GeneralUtils.print("key : " + keyValuePairs[i].getKey() + ", value : " + keyValuePairs[i].getValue());
}
String postData = builder.toString();
postData = postData.substring(0, postData.length() - 1);
GeneralUtils.print("postData " + postData);
byte[] postDataByteArr = postData.getBytes();
connection.setFixedLengthStreamingMode(postDataByteArr.length);
connection.setConnectTimeout(20000);
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(postData);
dataOutputStream.flush();
dataOutputStream.close();
GeneralUtils.print("respCode " + connection.getResponseCode());
// if connection was not successful
if (connection.getResponseCode() != 200) {
jsonResponse.put("status", "Failure");
jsonResponse.put("message", "Something went wrong. Please Try Again");
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
String response = sb.toString();
GeneralUtils.print("NetworkCall Server response " + response);
jsonResponse = new JSONObject(response);
}
} catch (JSONException e) {
GeneralUtils.print("NetworkCall.JSONEx 162 " + e);
} catch (MalformedURLException e) {
GeneralUtils.print("NetworkCall.MalformedURLEx " + e);
} catch (IOException e) {
try {
jsonResponse.put("status", "No Internet Connection");
jsonResponse.put("message", "Please check your Internet connection and try again");
} catch (JSONException e1) {
GeneralUtils.print("NetworkCall.JSONEx " + e);
}
} finally {
connection.disconnect();
}
} else {
// if Internet is not available
try {
jsonResponse.put("status", "No Internet Connection");
jsonResponse.put("message", "Please check your Internet connection and try again");
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonResponse;
}
Many many thanks in advance!
As of now I am following a workaround posted here
which essentially dictates trying to connect N number of times to bypass the EOF exception issue.
In my case, when I catch EOFException, I call the doInBackground again depending upon the reconnectCount;
CODE :
catch (IOException e) {
try {
if (reConnectCount <= 10) {
reConnectCount++;
jsonResponse = doInBackground(keyValuePairs);
} else {
jsonResponse.put("status", "No Internet Connection");
jsonResponse.put("message", "Please check your Internet connection and try again");
}
} catch (JSONException e1) {
GeneralUtils.print("NetworkCall.JSONEx " + e);
}
}
Where jsonResponse essentially holds server response in JSON form. So, whenever doInBackground is successfully executed (i.e. does not get Caught and returns jsonResponse), we overwrite the calling doInBackground's jsonResponse object.

Categories