I'm trying to insert contacts details to a MySQL database,
Here is my code :
public void SyncContact(){
ContentResolver cr = getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
JSONArray ja = new JSONArray();
HashMap<String,String> hashmap_contactList = new HashMap<String, String>();
String id="";
String name="";
String mobileNo="";
String emailContact="";
String orgName="";
String title="";
String note="";
String street="";
String dob="";
int i = 0;
while (phones.moveToNext()) {
id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
mobileNo = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
if(emailCur.getCount()>0) {
while (emailCur.moveToNext()) {
emailContact = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
}else{
emailContact="";
}
emailCur.close();
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,null, orgWhere, orgWhereParams, null);
if(orgCur.getCount()>0) {
if (orgCur.moveToFirst()) {
orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
}
}else{
orgName="";
title="";
}
orgCur.close();
String[] noteWhereParams = new String[]{id,ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, orgWhere, noteWhereParams, null);
if(noteCur.getCount()>0) {
if (noteCur.moveToFirst()) {
note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
}
}else{
note="";
}
noteCur.close();
String[] addrWhereParams = new String[]{id,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,null, orgWhere, addrWhereParams, null);
if(addrCur.getCount()>0){
while(addrCur.moveToNext()) {
street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
}
}else {
street="";
}
addrCur.close();
String[] selectionArgs = new String[] {id,ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE};
Cursor dobCur = cr.query(ContactsContract.Data.CONTENT_URI, null, orgWhere, selectionArgs, null);
if(dobCur.getCount()>0) {
if (dobCur.moveToFirst()) {
dob = dobCur.getString(dobCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.DATA));
}
}else {
dob="";
}
dobCur.close();
if(!hashmap_contactList.containsKey(name)){
hashmap_contactList.put(name, " ");
System.out.println("!! Contact ID is : " + id);
System.out.println("!! Contact Name is : " + name);
System.out.println("!! Contact Number is : " + mobileNo);
System.out.println("!!prepare Email " + emailContact );
System.out.println("!!prepare Comapny name:" + orgName);
System.out.println("!!prepare Designation :" + title);
System.out.println("!!prepare Note :" + note);
System.out.println("!!prepare Street:" + street);
System.out.println("!!hello dob :" + dob);
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put("contact_uniqueid",id);
jsonObject.put("contact_name",name);
jsonObject.put("contact_number",mobileNo);
jsonObject.put("email",emailContact);
jsonObject.put("oraganization",orgName);
jsonObject.put("job_title",title);
jsonObject.put("address",street);
jsonObject.put("note",note);
jsonObject.put("dob",dob);
ja.put(jsonObject);
mainjson.put("data",ja);
}catch (Exception e){
e.printStackTrace();
}
i++;
}
}
phones.close();
System.out.println("!!json " + mainjson);
try {
Log.d("!!!main_json", mainjson.toString(1));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ContactSync contactSync = new ContactSync();
contactSync.execute();
}
public class ContactSync extends AsyncTask<String,Void,String>{
String JsonString;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpPost post = new HttpPost(str_url);
try{
StringEntity entity = new StringEntity(mainjson.toString());
post.setEntity(entity);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
BasicResponseHandler handler = new BasicResponseHandler();
String response = client.execute(post, handler);
System.out.println("!!Response : " + response);
JSONObject jsonObject = new JSONObject(response);
System.out.println("!!Response " + jsonObject);
System.out.println("!! " + jsonObject.getString("data"));
JSONObject success_status = jsonObject.getJSONObject("data");
System.out.println("!!Succes MSg :" + success_status.getString("success"));
if(success_status.getString("success").toString().equalsIgnoreCase("true"))
{
System.out.println("Response after data inserted....."+success_status.getString("success").toString());
CommonFunction.saveSharedPreference(CommonFunction.contactsync_flag, "1", SplashActivity.this);
}
}catch (Exception e){
e.printStackTrace();
System.out.println("!! : "+e.getMessage());
System.out.println("!!!!!!manishhhhhhh......" );
}
return null;
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
And the API Code is :
public function temp(){
$_POST = json_decode(file_get_contents('php://input'), true);
$this->load->library('form_validation');
$boolean = TRUE;
$data = array();
$contact_data = $_POST['data'];
$i=0;
foreach($contact_data AS $row){
$fields['contact_uniqueid']=$row['contact_uniqueid'];
$fields['contact_name']=$row['contact_name'];
$fields['contact_number']=$row['contact_number'];
$fields['email']=$row['email'];
$fields['oraganization']=$row['oraganization'];
$fields['job_title']=$row['job_title'];
$fields['address']=$row['address'];
$fields['note']=$row['note'];
$fields['dob']=$row['dob'];
$data[$i] = $fields;
$i++;
}
$this->express_model->set_table('contact_list');
$data_obj = $this->express_model->saveBatch($data);
if ($boolean == TRUE)
{
$final_data['data']['success'] = 'true';
$final_data['data']['message'] = 'Data inserted successfully';
print_r(json_encode($final_data));
}
exit;
}
All contacts details are inserted into the database and I have to get "true" in the JSON response but I'm getting this error:
<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
and I use PHP API written in codeigniter.
check the data type into your database schema and try to insert the appropriate value..
Mostly it happen when we use DateTime data type for fields
Related
I am using JsonArray as input in my REST API. Here I attached my coding part.
After deployment I getting input value as null or internal server error or glass-fish error. Kindly suggest some ideas to resolve this issue.
I tried to change #Consumes(MediaType.APPLICATION_JSON) to #Consumes("application/json") and also command the #XmlRootElement annotation.
This is TransactionData.java class:
#Path("/CreditProcess")
public class TransactionData {
//private Object ipxml;
#POST
#Path("/SOHold")
//#Consumes("application/json")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public TransactionDataResponse Serv(TransactionDataRequest req) throws IOException, JPISException, Exception {
String Status = null, ErrorCode = null;
TransactionDataResponse ObjRes = new TransactionDataResponse();
CommonFunction ObjCF = new CommonFunction();
String SessionId = "";
boolean boolREADINI;
String Webservice = "Hold_Creation";
boolREADINI = ObjCF.ReadINIProperties();
String MISC_ID = "";
String PID = "", SaleOrder = "", Hold_Type = "", Hold_Status = "",
Approved_User = "", Date = "", Remarks = "", Hold_Desc = "", SO_COUNT = "", CH_COUNT = "", flag = "",WorkitemID="";
String Output_data = "", Input_data = "";
DMSXmlResponse Query_Response = null;
SessionId = ObjCF.ConnectCabinet(Webservice);
// PID = req.get();
ObjCF.ReportLog("Input_data request---" + req, Webservice);
JSONArray Data = new JSONArray();
try {
ObjCF.ReportLog("Before Check1---", Webservice);
Data = req.getData();
ObjCF.ReportLog("After Check2---"+Data, Webservice);
int size = Data.size();
for (int row = 0; row < size; row++) {
ObjCF.ReportLog("test1--", Webservice);
JSONObject obj;
HashMap<String, String> passedValues = (HashMap<String, String>) Data.get(row);
ObjCF.ReportLog("test2-- ", Webservice);
// ObjCF.ReportLog("test2--Data.get(i)" + Data.get(i), Webservice);
// obj = (JSONObject) Data.get(i);
for (Entry<String, String> mapTemp : passedValues.entrySet()) {
if (mapTemp.getKey().equalsIgnoreCase("SalesOrder")) {
SaleOrder = mapTemp.getValue();
ObjCF.ReportLog("json SaleOrder" + SaleOrder, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_Type")) {
Hold_Type = mapTemp.getValue();
ObjCF.ReportLog("json Hold_Type" + Hold_Type, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_status")) {
Hold_Status = mapTemp.getValue();
ObjCF.ReportLog("json SaleOrder" + Hold_Status, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Approved_User")) {
Approved_User = mapTemp.getValue();
ObjCF.ReportLog("json Approved_User" + Approved_User, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Date_Time")) {
Date = mapTemp.getValue();
ObjCF.ReportLog("json Date" + Date, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Remarks")) {
Remarks = mapTemp.getValue();
ObjCF.ReportLog("json Remarks" + Remarks, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_status_Desc")) {
Hold_Desc = mapTemp.getValue();
ObjCF.ReportLog("json Hold_Desc" + Hold_Desc, Webservice);
}
}
}
} catch(Exception e){
}
}
}
This is my TransactionDataRequest.java class:
import com.newgen.Utils.CommonFunction;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.json.simple.JSONArray;
#XmlRootElement
public class TransactionDataRequest {
private JSONArray Data;
CommonFunction ObjCF = new CommonFunction();
public JSONArray getData() {
ObjCF.ReportLog("Inside getData---", "Hold_Creation");
ObjCF.ReportLog("Inside getData return data---" + Data, "Hold_Creation");
return Data;
}
#XmlElement(name = "Data")
public void setData( JSONArray Data) {
ObjCF.ReportLog("Inside Data:---" + Data, "Hold_Creation");
this.Data = Data;
ObjCF.ReportLog("After this Data:---" + Data, "Hold_Creation");
}
}
I have 7 protocols, and I want to be shown on the site. But the site shows only 4 protocols, although there are 7 protocols in the JSON file. I decided to check with a debugger, it passes 4 protocols without errors. But starting with the fifth protocol, such an error comes out.
I have error
org.json.JSONException) org.json.JSONException: JSONObject["routes"] not found.
My controller
#Controller
public class LookingGlassController {
private final static String BGP_URL = "http://80.241.0.85/api/protocols/bgp";
private final static String BGP_DETAILS_URL = "http://80.241.0.85/api/protocol/";
private final static String TABLE_URL = "http://80.241.0.85/api/routes/table/";
private final static String ROUT_URL = "http://80.241.0.85/api/route/";
/**
*
* #param lang
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/bgp")
public ModelAndView bgp(#PathVariable String lang) {
List<BGPData> bgpDateList = new ArrayList<>();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(BGP_URL), Charset.forName("UTF-8")));
JSONObject protocols = json.getJSONObject("protocols");
Map<String, Object> prots = protocols.toMap();
for (String prot_name : prots.keySet()) {
JSONObject prot = protocols.getJSONObject(prot_name);
String protocol = prot.getString("protocol");
String neighborAddress = prot.getString("neighbor_address");
String description = prot.getString("description");
Integer asn = prot.getInt("neighbor_as");
String tableName = prot.getString("table");
String status = prot.getString("bgp_state");
Integer routeImport = prot.getJSONObject("routes").getInt("imported");
Integer routeExport = prot.getJSONObject("routes").getInt("exported");
Integer importLimit = prot.getInt("import_limit");
String tableLink = "/" + lang + "/lookingglass/table/" + tableName;
String protocolDetailLink = "/" + lang + "/lookingglass/bgpdetails/" + protocol;
BGPData bgpData = new BGPData();
bgpData.setProtocol(protocol);
bgpData.setProtocolDetailLink(protocolDetailLink);
bgpData.setNaighbord(neighborAddress);
bgpData.setDescription(description);
bgpData.setAsn(asn);
bgpData.setTableName(tableName);
bgpData.setStatus(status);
bgpData.setRouteImport(routeImport);
bgpData.setRouteExport(routeExport);
bgpData.setImportLimit(importLimit);
bgpData.setTableLink(tableLink);
bgpDateList.add(bgpData);
}
} catch (IOException | JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("lang", lang);
outMap.put("bgpDataList", bgpDateList);
outMap.put("lgSearchData", new LgSearchData());
return new ModelAndView("/site/lookingglass/bgp", outMap);
}
/**
*
* #param lang
* #param protocol
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/bgpdetails/{protocol}")
public ModelAndView bgp_details(#PathVariable String lang, #PathVariable String protocol) {
BGPDetailData bgpDetalisData = new BGPDetailData();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(BGP_DETAILS_URL + protocol), Charset.forName("UTF-8")));
JSONObject protocolJs = json.getJSONObject("protocol");
String bird_protocol = protocolJs.getString("bird_protocol");
String state = protocolJs.getString("state");
String state_changed = protocolJs.getString("state_changed");
String connection = protocolJs.getString("connection");
String description = protocolJs.getString("description");
Integer preference = protocolJs.getInt("preference");
String input_filter = protocolJs.getString("input_filter");
String output_filter = protocolJs.getString("output_filter");
Integer import_limit = protocolJs.getInt("import_limit");
String limit_action = protocolJs.getString("limit_action");
Integer routes_imported = protocolJs.getJSONObject("routes").getInt("imported");
Integer routes_exported = protocolJs.getJSONObject("routes").getInt("exported");
Integer routes_preferred = protocolJs.getJSONObject("routes").getInt("preferred");
JSONObject jsO = protocolJs.getJSONObject("route_changes").getJSONObject("import_updates");
String route_change_import_updates = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("import_withdraws");
String route_change_import_withdraws = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("export_updates");
String route_change_export_updates = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("export_withdraws");
String route_change_export_withdraws = getRouteChange(jsO);
String bgp_state = protocolJs.getString("bgp_state");
String neighbor_address = protocolJs.getString("neighbor_address");
Integer neighbor_as = protocolJs.getInt("neighbor_as");
String neighbor_id = "";
try {
neighbor_id = protocolJs.getString("neighbor_id");
} catch (JSONException ex) {
}
String neighbor_capabilities = "";
try {
JSONArray ar = protocolJs.getJSONArray("neighbor_capabilities");
for (Object aspo : ar) {
neighbor_capabilities += (String) aspo + " ";
}
} catch (JSONException ex) {
neighbor_capabilities = "n/a";
}
String session = "";
try {
JSONArray ar = protocolJs.getJSONArray("bgp_session");
for (Object aspo : ar) {
session += (String) aspo + " ";
}
} catch (JSONException ex) {
session = "n/a";
}
String source_address = "";
try {
source_address = protocolJs.getString("source_address");
} catch (JSONException ex) {
session = "n/a";
}
Integer hold_timer = null;
try {
hold_timer = protocolJs.getInt("hold_timer");
} catch (JSONException ex) {
session = "n/a";
}
Integer route_limit_at = null;
try {
route_limit_at = protocolJs.getInt("route_limit_at");
} catch (JSONException ex) {
session = "n/a";
}
Integer keepalive = null;
try {
keepalive = protocolJs.getInt("keepalive");
} catch (JSONException ex) {
session = "n/a";
}
bgpDetalisData.setProtocol(protocol);
bgpDetalisData.setBird_protocol(bird_protocol);
bgpDetalisData.setState(state);
bgpDetalisData.setState_changed(state_changed);
bgpDetalisData.setConnection(connection);
bgpDetalisData.setDescription(description);
bgpDetalisData.setPreference(preference);
bgpDetalisData.setInput_filter(input_filter);
bgpDetalisData.setOutput_filter(output_filter);
bgpDetalisData.setImport_limit(import_limit);
bgpDetalisData.setLimit_action(limit_action);
bgpDetalisData.setRoutes_imported(routes_imported);
bgpDetalisData.setRoutes_exported(routes_exported);
bgpDetalisData.setRoutes_preferred(routes_preferred);
bgpDetalisData.setRoute_change_import_updates(route_change_import_updates);
bgpDetalisData.setRoute_change_import_withdraws(route_change_import_withdraws);
bgpDetalisData.setRoute_change_export_updates(route_change_export_updates);
bgpDetalisData.setRoute_change_export_withdraws(route_change_export_withdraws);
bgpDetalisData.setBgp_state(bgp_state);
bgpDetalisData.setNeighbor_address(neighbor_address);
bgpDetalisData.setNeighbor_as(neighbor_as);
bgpDetalisData.setNeighbor_id(neighbor_id);
bgpDetalisData.setNeighbor_capabilities(neighbor_capabilities);
bgpDetalisData.setBgp_session(session);
bgpDetalisData.setSource_address(source_address);
bgpDetalisData.setHold_timer(hold_timer);
bgpDetalisData.setRoute_limit_at(route_limit_at);
bgpDetalisData.setKeepalive(keepalive);
} catch (IOException | JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("lang", lang);
outMap.put("bgpDetails", bgpDetalisData);
return new ModelAndView("/site/lookingglass/bgp_details", outMap);
}
/**
*
* #param jsO
* #return
*/
private String getRouteChange(JSONObject jsO) {
String out = "";
try {
Integer received = jsO.getInt("received");
out += "recived: " + received + ", ";
} catch (JSONException ex) {
}
try {
Integer rejected = jsO.getInt("rejected");
out += "rejected: " + rejected + ", ";
} catch (JSONException ex) {
}
try {
Integer filtered = jsO.getInt("filtered");
out += "filtered: " + filtered + ", ";
} catch (JSONException ex) {
}
try {
Integer ignored = jsO.getInt("ignored");
out += "ignored: " + ignored + ", ";
} catch (JSONException ex) {
}
try {
Integer accepted = jsO.getInt("accepted");
out += "accepted: " + accepted + ", ";
} catch (JSONException ex) {
}
return out.substring(0, out.length() - 2);
}
/**
*
* #param lang
* #param name
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/table/{name}")
public ModelAndView table(#PathVariable String lang, #PathVariable String name) {
List<TableData> tableDateList = new ArrayList<>();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(TABLE_URL + name), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
routes.forEach(action -> {
JSONObject rout = (JSONObject) action;
String network = rout.getString("network");
String gateway = rout.getString("gateway");
Integer metric = rout.getInt("metric");
Boolean primary = rout.getBoolean("primary");
Integer communities = 0;
String aspath = "";
JSONArray ar = rout.getJSONObject("bgp").getJSONArray("as_path");
for (Object aspo : ar) {
aspath += (String) aspo + " ";
}
try {
JSONArray ar1 = rout.getJSONObject("bgp").getJSONArray("communities");
communities = ar1.length();
} catch (JSONException ex) {
}
String networkLink = "/" + lang + "/lookingglass/route/" + network;
TableData tableData = new TableData();
tableData.setNetwork(network);
tableData.setNetworkLink(networkLink);
tableData.setGateway(gateway);
tableData.setMetric(metric);
tableData.setCommunities(communities);
tableData.setAspath(aspath);
tableData.setPrimary(primary);
tableDateList.add(tableData);
});
} catch (IOException ex) {
name = "UNKNOWN";
} catch (JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("tableDataList", tableDateList);
outMap.put("tableName", name);
return new ModelAndView("/site/lookingglass/table", outMap);
}
/**
*
* #param lang
* #param ip
* #param mask
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/route/{ip}/{mask}")
public ModelAndView rout(#PathVariable String lang, #PathVariable String ip, #PathVariable String mask) {
String net;
List<TableData> tableDateList = new ArrayList<>();
try {
net = ip + "/" + mask;
String url = ROUT_URL + URLEncoder.encode(net, "UTF-8");
JSONObject json = new JSONObject(IOUtils.toString(new URL(url), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
routes.forEach(action -> {
JSONObject rout = (JSONObject) action;
String network = rout.getString("network");
String gateway = rout.getString("gateway");
Integer metric = rout.getInt("metric");
Boolean primary = rout.getBoolean("primary");
String inter_face = rout.getString("interface");
String age = rout.getString("age");
String from_protocol = rout.getString("from_protocol");
String origin = rout.getJSONObject("bgp").getString("origin");
Integer med = null;
try {
med = rout.getJSONObject("bgp").getInt("med");
} catch (JSONException ex) {
}
String localPref = rout.getJSONObject("bgp").getString("local_pref");
String aspath = "";
JSONArray ar = rout.getJSONObject("bgp").getJSONArray("as_path");
for (Object aspo : ar) {
aspath += (String) aspo + " ";
}
String type = "";
JSONArray ar1 = rout.getJSONArray("type");
for (Object t : ar1) {
type += (String) t + " ";
}
String communitiesList = "";
try {
JSONArray ar2 = rout.getJSONObject("bgp").getJSONArray("communities");
for (Object o : ar2) {
JSONArray ar3 = (JSONArray) o;
communitiesList += "(";
int index = 0;
for (Object o1 : ar3) {
if (index > 0) {
communitiesList += ", ";
}
communitiesList += (Integer) o1;
index++;
}
communitiesList += ") ";
}
} catch (JSONException ex) {
}
if (communitiesList.isEmpty()) {
communitiesList = null;
}
TableData tableData = new TableData();
tableData.setNetwork(network);
tableData.setGateway(gateway);
tableData.setMetric(metric);
tableData.setAspath(aspath);
tableData.setInter_face(inter_face);
tableData.setAge(age);
tableData.setFromProtocol(from_protocol);
tableData.setType(type);
tableData.setOrigin(origin);
tableData.setLocalPref(localPref);
tableData.setCommunitiesList(communitiesList);
tableData.setMed(med);
tableData.setPrimary(primary);
tableDateList.add(tableData);
});
} catch (IOException | JSONException ex) {
net = "UNKNOWN";
}
Map<String, Object> outMap = new HashMap();
outMap.put("tableDataList", tableDateList);
outMap.put("net", net);
return new ModelAndView("/site/lookingglass/route", outMap);
}
/**
*
* #param lang
* #param lgSearchData
* #param result
* #param model
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/search")
public ModelAndView search(#PathVariable String lang,
#Valid #ModelAttribute("lgSearchData") LgSearchData lgSearchData,
BindingResult result,
ModelMap model) {
String ip = lgSearchData.getIp();
if (ip == null || ip.isEmpty()) {
return new ModelAndView("redirect:/" + lang + "/lookingglass/bgp");
}
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(ROUT_URL + URLEncoder.encode(ip, "UTF-8")), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
JSONObject rout = routes.getJSONObject(0);
if (rout != null) {
String network = rout.getString("network");
return new ModelAndView("redirect:/" + lang + "/lookingglass/route/" + network);
}
} catch (IOException | JSONException ex) {
}
return new ModelAndView("/site/lookingglass/bgp");
}
}
I have 7 protocols
enter image description here
On site show only 4 protocols(((
enter image description here
Information about protocol
enter image description here
Ok, this issue is because it is not found routes field in JSON object then you need to check if the JSON object has this field, I created a method called getRoutesAsJSONObject(JSONObject jsonObject) this method check if a JSON object has routes then return the routes as JSON object else creates a JSON Object and adds routes as JSONObject with imported, exported and preferred values to 0.
#Controller
public class LookingGlassController {
private final static String BGP_URL = "http://80.241.0.85/api/protocols/bgp";
private final static String BGP_DETAILS_URL = "http://80.241.0.85/api/protocol/";
private final static String TABLE_URL = "http://80.241.0.85/api/routes/table/";
private final static String ROUT_URL = "http://80.241.0.85/api/route/";
/**
*
* #param lang
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/bgp")
public ModelAndView bgp(#PathVariable String lang) {
List<BGPData> bgpDateList = new ArrayList<>();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(BGP_URL), Charset.forName("UTF-8")));
JSONObject protocols = json.getJSONObject("protocols");
Map<String, Object> prots = protocols.toMap();
for (String prot_name : prots.keySet()) {
JSONObject prot = protocols.getJSONObject(prot_name);
String protocol = prot.getString("protocol");
String neighborAddress = prot.getString("neighbor_address");
String description = prot.getString("description");
Integer asn = prot.getInt("neighbor_as");
String tableName = prot.getString("table");
String status = prot.getString("bgp_state");
JSONObject routesAsJSONObject = getRoutesAsJSONObject(prot);
Integer routeImport = routesAsJSONObject.getInt("imported");
Integer routeExport = routesAsJSONObject.getInt("exported");
Integer importLimit = prot.getInt("import_limit");
String tableLink = "/" + lang + "/lookingglass/table/" + tableName;
String protocolDetailLink = "/" + lang + "/lookingglass/bgpdetails/" + protocol;
BGPData bgpData = new BGPData();
bgpData.setProtocol(protocol);
bgpData.setProtocolDetailLink(protocolDetailLink);
bgpData.setNaighbord(neighborAddress);
bgpData.setDescription(description);
bgpData.setAsn(asn);
bgpData.setTableName(tableName);
bgpData.setStatus(status);
bgpData.setRouteImport(routeImport);
bgpData.setRouteExport(routeExport);
bgpData.setImportLimit(importLimit);
bgpData.setTableLink(tableLink);
bgpDateList.add(bgpData);
}
} catch (IOException | JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("lang", lang);
outMap.put("bgpDataList", bgpDateList);
outMap.put("lgSearchData", new LgSearchData());
return new ModelAndView("/site/lookingglass/bgp", outMap);
}
/**
*
* #param lang
* #param protocol
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/bgpdetails/{protocol}")
public ModelAndView bgp_details(#PathVariable String lang, #PathVariable String protocol) {
BGPDetailData bgpDetalisData = new BGPDetailData();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(BGP_DETAILS_URL + protocol), Charset.forName("UTF-8")));
JSONObject protocolJs = json.getJSONObject("protocol");
String bird_protocol = protocolJs.getString("bird_protocol");
String state = protocolJs.getString("state");
String state_changed = protocolJs.getString("state_changed");
String connection = protocolJs.getString("connection");
String description = protocolJs.getString("description");
Integer preference = protocolJs.getInt("preference");
String input_filter = protocolJs.getString("input_filter");
String output_filter = protocolJs.getString("output_filter");
Integer import_limit = protocolJs.getInt("import_limit");
String limit_action = protocolJs.getString("limit_action");
JSONObject routesAsJSONObject = getRoutesAsJSONObject(protocolJs);
Integer routes_imported = routesAsJSONObject.getInt("imported");
Integer routes_exported = routesAsJSONObject.getInt("exported");
Integer routes_preferred = routesAsJSONObject.getInt("preferred");
JSONObject jsO = protocolJs.getJSONObject("route_changes").getJSONObject("import_updates");
String route_change_import_updates = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("import_withdraws");
String route_change_import_withdraws = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("export_updates");
String route_change_export_updates = getRouteChange(jsO);
jsO = protocolJs.getJSONObject("route_changes").getJSONObject("export_withdraws");
String route_change_export_withdraws = getRouteChange(jsO);
String bgp_state = protocolJs.getString("bgp_state");
String neighbor_address = protocolJs.getString("neighbor_address");
Integer neighbor_as = protocolJs.getInt("neighbor_as");
String neighbor_id = "";
try {
neighbor_id = protocolJs.getString("neighbor_id");
} catch (JSONException ex) {
}
String neighbor_capabilities = "";
try {
JSONArray ar = protocolJs.getJSONArray("neighbor_capabilities");
for (Object aspo : ar) {
neighbor_capabilities += (String) aspo + " ";
}
} catch (JSONException ex) {
neighbor_capabilities = "n/a";
}
String session = "";
try {
JSONArray ar = protocolJs.getJSONArray("bgp_session");
for (Object aspo : ar) {
session += (String) aspo + " ";
}
} catch (JSONException ex) {
session = "n/a";
}
String source_address = "";
try {
source_address = protocolJs.getString("source_address");
} catch (JSONException ex) {
session = "n/a";
}
Integer hold_timer = null;
try {
hold_timer = protocolJs.getInt("hold_timer");
} catch (JSONException ex) {
session = "n/a";
}
Integer route_limit_at = null;
try {
route_limit_at = protocolJs.getInt("route_limit_at");
} catch (JSONException ex) {
session = "n/a";
}
Integer keepalive = null;
try {
keepalive = protocolJs.getInt("keepalive");
} catch (JSONException ex) {
session = "n/a";
}
bgpDetalisData.setProtocol(protocol);
bgpDetalisData.setBird_protocol(bird_protocol);
bgpDetalisData.setState(state);
bgpDetalisData.setState_changed(state_changed);
bgpDetalisData.setConnection(connection);
bgpDetalisData.setDescription(description);
bgpDetalisData.setPreference(preference);
bgpDetalisData.setInput_filter(input_filter);
bgpDetalisData.setOutput_filter(output_filter);
bgpDetalisData.setImport_limit(import_limit);
bgpDetalisData.setLimit_action(limit_action);
bgpDetalisData.setRoutes_imported(routes_imported);
bgpDetalisData.setRoutes_exported(routes_exported);
bgpDetalisData.setRoutes_preferred(routes_preferred);
bgpDetalisData.setRoute_change_import_updates(route_change_import_updates);
bgpDetalisData.setRoute_change_import_withdraws(route_change_import_withdraws);
bgpDetalisData.setRoute_change_export_updates(route_change_export_updates);
bgpDetalisData.setRoute_change_export_withdraws(route_change_export_withdraws);
bgpDetalisData.setBgp_state(bgp_state);
bgpDetalisData.setNeighbor_address(neighbor_address);
bgpDetalisData.setNeighbor_as(neighbor_as);
bgpDetalisData.setNeighbor_id(neighbor_id);
bgpDetalisData.setNeighbor_capabilities(neighbor_capabilities);
bgpDetalisData.setBgp_session(session);
bgpDetalisData.setSource_address(source_address);
bgpDetalisData.setHold_timer(hold_timer);
bgpDetalisData.setRoute_limit_at(route_limit_at);
bgpDetalisData.setKeepalive(keepalive);
} catch (IOException | JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("lang", lang);
outMap.put("bgpDetails", bgpDetalisData);
return new ModelAndView("/site/lookingglass/bgp_details", outMap);
}
/**
*
* #param jsO
* #return
*/
private String getRouteChange(JSONObject jsO) {
String out = "";
try {
Integer received = jsO.getInt("received");
out += "recived: " + received + ", ";
} catch (JSONException ex) {
}
try {
Integer rejected = jsO.getInt("rejected");
out += "rejected: " + rejected + ", ";
} catch (JSONException ex) {
}
try {
Integer filtered = jsO.getInt("filtered");
out += "filtered: " + filtered + ", ";
} catch (JSONException ex) {
}
try {
Integer ignored = jsO.getInt("ignored");
out += "ignored: " + ignored + ", ";
} catch (JSONException ex) {
}
try {
Integer accepted = jsO.getInt("accepted");
out += "accepted: " + accepted + ", ";
} catch (JSONException ex) {
}
return out.substring(0, out.length() - 2);
}
/**
*
* #param lang
* #param name
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/table/{name}")
public ModelAndView table(#PathVariable String lang, #PathVariable String name) {
List<TableData> tableDateList = new ArrayList<>();
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(TABLE_URL + name), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
routes.forEach(action -> {
JSONObject rout = (JSONObject) action;
String network = rout.getString("network");
String gateway = rout.getString("gateway");
Integer metric = rout.getInt("metric");
Boolean primary = rout.getBoolean("primary");
Integer communities = 0;
String aspath = "";
JSONArray ar = rout.getJSONObject("bgp").getJSONArray("as_path");
for (Object aspo : ar) {
aspath += (String) aspo + " ";
}
try {
JSONArray ar1 = rout.getJSONObject("bgp").getJSONArray("communities");
communities = ar1.length();
} catch (JSONException ex) {
}
String networkLink = "/" + lang + "/lookingglass/route/" + network;
TableData tableData = new TableData();
tableData.setNetwork(network);
tableData.setNetworkLink(networkLink);
tableData.setGateway(gateway);
tableData.setMetric(metric);
tableData.setCommunities(communities);
tableData.setAspath(aspath);
tableData.setPrimary(primary);
tableDateList.add(tableData);
});
} catch (IOException ex) {
name = "UNKNOWN";
} catch (JSONException ex) {
}
Map<String, Object> outMap = new HashMap();
outMap.put("tableDataList", tableDateList);
outMap.put("tableName", name);
return new ModelAndView("/site/lookingglass/table", outMap);
}
/**
*
* #param lang
* #param ip
* #param mask
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/route/{ip}/{mask}")
public ModelAndView rout(#PathVariable String lang, #PathVariable String ip, #PathVariable String mask) {
String net;
List<TableData> tableDateList = new ArrayList<>();
try {
net = ip + "/" + mask;
String url = ROUT_URL + URLEncoder.encode(net, "UTF-8");
JSONObject json = new JSONObject(IOUtils.toString(new URL(url), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
routes.forEach(action -> {
JSONObject rout = (JSONObject) action;
String network = rout.getString("network");
String gateway = rout.getString("gateway");
Integer metric = rout.getInt("metric");
Boolean primary = rout.getBoolean("primary");
String inter_face = rout.getString("interface");
String age = rout.getString("age");
String from_protocol = rout.getString("from_protocol");
String origin = rout.getJSONObject("bgp").getString("origin");
Integer med = null;
try {
med = rout.getJSONObject("bgp").getInt("med");
} catch (JSONException ex) {
}
String localPref = rout.getJSONObject("bgp").getString("local_pref");
String aspath = "";
JSONArray ar = rout.getJSONObject("bgp").getJSONArray("as_path");
for (Object aspo : ar) {
aspath += (String) aspo + " ";
}
String type = "";
JSONArray ar1 = rout.getJSONArray("type");
for (Object t : ar1) {
type += (String) t + " ";
}
String communitiesList = "";
try {
JSONArray ar2 = rout.getJSONObject("bgp").getJSONArray("communities");
for (Object o : ar2) {
JSONArray ar3 = (JSONArray) o;
communitiesList += "(";
int index = 0;
for (Object o1 : ar3) {
if (index > 0) {
communitiesList += ", ";
}
communitiesList += (Integer) o1;
index++;
}
communitiesList += ") ";
}
} catch (JSONException ex) {
}
if (communitiesList.isEmpty()) {
communitiesList = null;
}
TableData tableData = new TableData();
tableData.setNetwork(network);
tableData.setGateway(gateway);
tableData.setMetric(metric);
tableData.setAspath(aspath);
tableData.setInter_face(inter_face);
tableData.setAge(age);
tableData.setFromProtocol(from_protocol);
tableData.setType(type);
tableData.setOrigin(origin);
tableData.setLocalPref(localPref);
tableData.setCommunitiesList(communitiesList);
tableData.setMed(med);
tableData.setPrimary(primary);
tableDateList.add(tableData);
});
} catch (IOException | JSONException ex) {
net = "UNKNOWN";
}
Map<String, Object> outMap = new HashMap();
outMap.put("tableDataList", tableDateList);
outMap.put("net", net);
return new ModelAndView("/site/lookingglass/route", outMap);
}
/**
*
* #param lang
* #param lgSearchData
* #param result
* #param model
* #return
*/
#RequestMapping("/{lang:ru|kk|en}/lookingglass/search")
public ModelAndView search(#PathVariable String lang,
#Valid #ModelAttribute("lgSearchData") LgSearchData lgSearchData,
BindingResult result,
ModelMap model) {
String ip = lgSearchData.getIp();
if (ip == null || ip.isEmpty()) {
return new ModelAndView("redirect:/" + lang + "/lookingglass/bgp");
}
try {
JSONObject json = new JSONObject(IOUtils.toString(new URL(ROUT_URL + URLEncoder.encode(ip, "UTF-8")), Charset.forName("UTF-8")));
JSONArray routes = json.getJSONArray("routes");
JSONObject rout = routes.getJSONObject(0);
if (rout != null) {
String network = rout.getString("network");
return new ModelAndView("redirect:/" + lang + "/lookingglass/route/" + network);
}
} catch (IOException | JSONException ex) {
}
return new ModelAndView("/site/lookingglass/bgp");
}
private JSONObject getRoutesAsJSONObject(JSONObject jsonObject) {
if (jsonObject.has("routes")) {
try {
return jsonObject.getJSONObject("routes");
} catch (JSONException exception) {
exception.printStackTrace();
}
}
JSONObject routesJSON = new JSONObject();
try {
routesJSON.put("imported", 0);
routesJSON.put("exported", 0);
routesJSON.put("preferred", 0);
} catch (JSONException e) {
e.printStackTrace();
}
return routesJSON;
}
}
Special characters such as (“ ”,') gets converted into ? while applying
interceptor in retrofit2.While getting response from retrofit2 , i am getting special characters but the interceptor changes the special character to ? and displays ? instead of special characters
Adding retrofit in Interceptor:
CustomRequestInterceptor requestInterceptor = newCustomRequestInterceptor();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY :
HttpLoggingInterceptor.Level.NONE);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(requestInterceptor);
httpClient.addInterceptor(logging);
Interceptor class(CustomRequestInterceptor.java) for retrofit2:
public class CustomRequestInterceptor implements Interceptor {
private static String newToken;
private String bodyString;
private final String TAG = getClass().getSimpleName();
#Override
public Response intercept(Chain chain) throws IOException {
String token = "";
Request request = chain.request();
RequestBody oldBody = request.body();
Buffer buffer = new Buffer();
oldBody.writeTo(buffer);
String strOldBody = buffer.readUtf8();
Log.i(TAG, "original req " + strOldBody);
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
JSONObject jsonObject = new JSONObject();
String decodedStr = decoder(strOldBody.replace("data=", ""));
try {
if (decodedStr != null && decodedStr.equalsIgnoreCase("")) {
token = getRandomNumber();
jsonObject.put("auth_token", token);
} else {
jsonObject = new JSONObject(decodedStr);
token = getRandomNumber();
jsonObject.put("auth_token", token);
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
Log.i(AppConstants.TAG, "Request JSONObject " + jsonObject.toString());
String strNewBody = "data=" + URLEncoder.encode(Encryption.encryptString(jsonObject.toString()));
Log.i(TAG, "strNewBody " + strNewBody);
RequestBody body = RequestBody.create(mediaType, strNewBody);
Log.i(TAG, "content type is " + body.contentType().toString());
Log.i(TAG, "content length is " + String.valueOf(body.contentLength()));
Log.i(TAG, "method is " + request.method());
request = request.newBuilder().header("Content-Type", body.contentType().toString())
.header("Content-Length", String.valueOf(body.contentLength()))
.method(request.method(), body).build();
Response response = chain.proceed(request);
String responseString = new String(response.body().bytes());
Log.i(TAG, "Response: " + responseString);
String newResponseString = Encryption.decryptString(responseString);
Log.i(TAG, "Response edited: " + URLDecoder.decode(newResponseString));
JSONObject res_JsonObject = new JSONObject();
if (newResponseString.startsWith("{")) {
try {
res_JsonObject = new JSONObject(newResponseString);
String response_token = res_JsonObject.getString("auth_token");
if (response_token.equalsIgnoreCase("" + token)) {
} else {
res_JsonObject.put("status", false);
res_JsonObject.put("message", "Authentication Failed");
Toast.makeText(new AppController().getApplicationContext(), "Authentication Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
}
byte[] ptext = res_JsonObject.toString().getBytes(ISO_8859_1);
String value = new String(ptext, UTF_16);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), value))
.build();
}
public String decoder(String encodedStr) {
try {
return URLDecoder.decode(encodedStr);
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
return encodedStr;
}
}
}
Expected output:
{
"comment": "“hello”"
}
Actual output:
{
"comment": "?hello?"
}
The problem is in the return statement of intercept method,
when we call ResponseBody.create(), the responsebody class converts data to UTF-8 format and UTF-8 does not support characters like (“,”) so it gives us "?" sign because we have given response.body().contentType(), so it converts to UTF-8 which is default.
The solution is to not to pass response.body().contentType() to create() and give our own contentType.
Here is the updated class.
public class CustomRequestInterceptor implements Interceptor {
private static String newToken;
private String bodyString;
private final String TAG = getClass().getSimpleName();
#Override
public Response intercept(Chain chain) throws IOException {
String token = "";
Request request = chain.request();
RequestBody oldBody = request.body();
Buffer buffer = new Buffer();
oldBody.writeTo(buffer);
String strOldBody = buffer.readUtf8();
Log.i(TAG, "original req " + strOldBody);
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
JSONObject jsonObject = new JSONObject();
String decodedStr = decoder(strOldBody.replace("data=", ""));
try {
if (decodedStr != null && decodedStr.equalsIgnoreCase("")) {
token = getRandomNumber();
jsonObject.put("auth_token", token);
} else {
jsonObject = new JSONObject(decodedStr);
token = getRandomNumber();
jsonObject.put("auth_token", token);
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
Log.i(AppConstants.TAG, "Request JSONObject " + jsonObject.toString());
String strNewBody = "data=" + URLEncoder.encode(Encryption.encryptString(jsonObject.toString()));
Log.i(TAG, "strNewBody " + strNewBody);
RequestBody body = RequestBody.create(mediaType, strNewBody);
Log.i(TAG, "content type is " + body.contentType().toString());
Log.i(TAG, "content length is " + String.valueOf(body.contentLength()));
Log.i(TAG, "method is " + request.method());
request = request.newBuilder().header("Content-Type", body.contentType().toString())
.header("Content-Length", String.valueOf(body.contentLength()))
.method(request.method(), body).build();
Response response = chain.proceed(request);
String responseString = new String(response.body().bytes());
Log.i(TAG, "Response: " + responseString);
String newResponseString = Encryption.decryptString(responseString);
JSONObject res_JsonObject = new JSONObject();
if (newResponseString.startsWith("{")) {
try {
res_JsonObject = new JSONObject(newResponseString);
String response_token = res_JsonObject.getString("auth_token");
if (response_token.equalsIgnoreCase("" + token)) {
} else {
res_JsonObject.put("status", false);
res_JsonObject.put("message", "Authentication Failed");
Toast.makeText(new AppController().getApplicationContext(), "Authentication Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
}
}
MediaType contentType = MediaType.parse(response.body().contentType() + "; charset=utf-32");
return response.newBuilder()
.body(ResponseBody.create(contentType, newResponseString.getBytes()))
.build();
}
public String decoder(String encodedStr) {
try {
return URLDecoder.decode(encodedStr);
} catch (Exception e) {
Log.e(AppConstants.TAG, "Exception", e);
return encodedStr;
}
}
}
org.json.JSONException: No value for status
Here is my java code method for json parse
java
public void performSearch() {
String url= "http://192.168.0.136/fyp/stitle1.php";
RequestQueue requestQueue = Volley.newRequestQueue(Stitle.this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
//converting the string to json array object
JSONObject array = new JSONObject();
//Log.i("test", " value : " + array.getString("status"));
Log.i("test", " value : " + response.getString("status"));
if (array.getString("status").equals("true")) {
JSONArray jsonArray = array.getJSONArray("search");
Log.i("test", " value : " + array);
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject product = jsonArray.getJSONObject(i);
//adding the product to product list
boolean add = productList.add(new list(
product.getLong("isbn"),
product.getString("title"),
product.getString("authors"),
product.getInt("accession"),
product.getString("publisher"),
product.getInt("pubyear"),
product.getInt("pages"),
product.getInt("rak"),
product.getInt("hr"),
product.getInt("vr"),
product.getLong("barcode")
));
}
} else {
Log.i("test", "else error");
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("test", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Title", searchtitle.getText().toString());
return params;
}
};
requestQueue = Volley.newRequestQueue(Stitle.this);
requestQueue.add(jsObjRequest);
}
Php file to pass parameter to android jsonobject
stitle1.php
php
<?php
// array for JSON response
$response = array();
//set values just in case any thing goes wrong
$response["status"] = 0;
$response["message"] = "Error before start";
// check for post data with isset
if (isset($_POST["Title"])) {
$title = $_POST["Title"];
// You were not using PDO so I dumped your connection and require you to provide...
//...a configuration file for ...
require_once 'connection.php';
// ...these variables
$host = 'localhost';
$db = 'fyp';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try{
// connecting to db with PDO
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT isbn, title, authors, accession, publisher, pubyear, pages, rak, hr, vr, barcode
FROM books
WHERE title LIKE :titleParam';
$titleParam = "%".$title."%";
$stmt = $pdo->prepare($sql);
// Bind the parameter
$stmt->bindParam(':titleParam', $titleParam, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
// success
$response["status"] = 1;
// connection node
$response["books"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data = array();
$data["isbn"] = $row["isbn"];
$data["title"] = $row["title"];
$data["authors"] = $row["authors"];
$data["accession"] = $row["accession"];
$data["publisher"] = $row["publisher"];
$data["pubyear"] = $row["pubyear"];
$data["pages"] = $row["pages"];
$data["rak"] = $row["rak"];
$data["hr"] = $row["hr"];
$data["vr"] = $row["vr"];
$data["barcode"] = $row["barcode"];
array_push($response["books"], $data);
}
}
else {
// required field is missing
$response["status"] = 2;
$response["message"] = "No data returned";
}
}
catch (Exception $e){
$response["status"] = 3;
$response["message"] = "Error occurred." . $e->getMessage();
}
}
else {
$response["status"] = 4;
$response["message"] = "Post parameters are not correct";
}
// echoing JSON response
echo json_encode($response);
?>
When I run my application these lines appear on logcat panel
I/test: value : 4
I/test: org.json.JSONException: No value for status
These are two lines appear on logcat which indicate error about that the parameter was not sent properly
We will take this step for step. Lets start with response.
Your PHP code is returning a status value =4 which indicates that you are not getting the parameters sent to the PHP code properly. It is possible that getParams() is not even being called.
Change the getParams() method to look like this:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
try{
String s = searchtitle.getText().toString();
Log.e("Volley request", "getParams called : " + s);
params.put("Title", s);
}
catch(Exception ex){
Log.e("Volley request ERROR", ex.getMessage());
}
return params;
}
For the second part, lets try to deal with the parsing code. Change the code to look like this:
Now regardless of how your php code responds, you will be getting a well formed JSONObject as a response which you can parse and react to it appropriately.
Change the onResponse() part of the code to look like this:
#Override
public void onResponse(JSONObject response) {
// Log.d("Response", response.toString());
try {
//converting the string to json array object
if(response != null){
if(!response.has("status"){
Log.e(TAG, "Something went wrong -- no status key!");
return;
}
else{
int status = response.optInt("status", -1);
if(status == 1){
//There could be quite a few books in this response...
//...you might want to parse in an AsyncTask instead
parseJsonObject(response);
}
else{
String message = response.optString("message", "uups");
Log.e(TAG, "error message = " + message);
return;
}
}
}
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}
And now to parse the JSONObject:
Map<String, String> booksMap = new HashMap<>();
private void parseJsonObject(JSONObject jsonObject){
try{
if(jsonObject == null) return;
//Not Available!
String na = "NA"
Log.i("test", " value : " + jsonObject.toString());
if(jsonObject.has("books")){
JSONArray array = jsonObject.getJSONArray("books");
for(int i = 0; array.length(); i++){
JSONObject book = array.getJSONObject(i);
Iterator<String> it = book.keys();
while(it.hasNext()){
String key = it.next();
String value = book.optString(key, na);
booksMap.put(key, value);
}
}
}
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}
I'm implementing facebook login on my webapp.
I receive the access token, I know the email and everything is fine.
But I can't register the user on Parse database.
I made a java bean which has userId, userName, userEmail and token.
I put these in a form, that should be sent to Parse.
/*--------------------------FORM FACEBOOK ----------------------------*/
final TextField<String> userId = new TextField<>("userId");
final TextField<String> userName = new TextField<>("userName");
final TextField<String> userEmail = new TextField<>("userEmail");
final TextField<String> token = new TextField<>("token");
model = new CompoundPropertyModel<>(new FacebookLoginForm());
form = new Form<FacebookLoginForm>("tokenForm", model)
{
#Override
protected void onSubmit()
{
ParseUser pu = new ParseUser();
pu.setUsername(model.getObject().getUserName());
pu.setEmail(model.getObject().getUserEmail());
/*METHOD FOR PARSE*/
curlParse(model.getObject().getToken(), model.getObject().getUserId());
}
};
add(form);
form.add(userId);
form.add(token);
form.add(userName);
form.add(userEmail);
Parse curlParse():
public void curlParse(String token, String id)
{
try
{ Date exp = new Date();
exp.setTime(exp.getTime()+7200000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd'T'HH:MM:ss.SSS'Z'"); /*2012-02-28T23:49:36.353Z Data format*/
String sExp = sdf.format(exp);
Request.Post("https://api.parse.com/1/users")
.addHeader("X-Custom-header", "stuff")
.bodyString(
"{"
+ " \"authData\": { "
+ " \"facebook\": {"
+ " \"id\": \""+ id +"\","
+ "\"access_token\": \""+ token +"\","
+ " \"expiration_date\": \""+sExp+"\""
+ " }"
+ "}"
+ "}", ContentType.APPLICATION_JSON
)
.execute().returnContent().asString();
} catch (IOException ex)
{
Logger.getLogger(Login2.class.getName()).log(Level.SEVERE, null, ex);
}
}
Since I need an absolute path to login user via facebook, I cannot use debug and there aren't any exceptions in the log(Tomcat) file.
I tried to translate from the cURL to java, but it doesn't seem to work.
Where is my mistake?
Thank you.
On html
<form id="tokenForm" wicket:id="tokenForm" >
<input type="text" id="token" wicket:id="token" name="token"/>
<input type="text" id="userId" wicket:id="userId" name="userId"/>
<input type="text" id="userName" wicket:id="userName"
<input type="text" id="userEmail" wicket:id="userEmail" name="userEmail"/>
<input type="submit"id="facebookSubmit" wicket:id="facebookSubmit" name="facebookSubmit">
</form>
On js:
function login() {
openFB.login(
function (response) {
if (response.status === 'connected') {
getInfo();
document.getElementById("token").value = response.authResponse.token;
} else {
alert('Facebook login failed: ' + response.error);
}
}, {scope: 'email'});
}
function getInfo() {
openFB.api({
path: '/me',
success: function (data) {
console.log(JSON.stringify(data));
document.getElementById("userId").value = data.id;
document.getElementById("userEmail").value = data.email;
document.getElementById("userName").value = data.first_name;
document.getElementById("userSurname").value = data.last_name;
document.getElementById("facebookSubmit").click();
},
error: errorHandler});
}
on java:
public void curlParse(String token, String id)
{
try
{
Date exp = new Date();
exp.setTime(exp.getTime() + 7200000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); /*2012-02-28T23:49:36.353Z */
String sExp = sdf.format(exp);
String resp = Request.Post("https://api.parse.com/1/users")
.addHeader("X-Parse-Application-Id", CWSApplication.getParseDotComApplicationID())
.addHeader("X-Parse-REST-API-Key", CWSApplication.getParseDotComApplicationKey())
.addHeader("Content-Type", "application/json")
.bodyString(
"{"
+ " \"authData\": { "
+ " \"facebook\": {"
+ " \"id\": \"" + id + "\","
+ "\"access_token\": \"" + token + "\","
+ " \"expiration_date\": \"" + sExp + "\""
+ " }"
+ "}"
+ "}", ContentType.APPLICATION_JSON
)
.execute().returnContent().asString();
/*System.out.println(ResponseParse);*/
CWSSession session = (CWSSession) getSession();
ParseUser loggedUser = new ParseUser();
/*questo con la libreriagson ci legge il JSON che ha i dati che ci servono da mettere su Parse*/
try
{
JsonReader reader = new JsonReader(new StringReader(resp));
reader.beginObject();
while (reader.hasNext())
{
String name = reader.nextName();
if (name.equals("objectId"))
{
loggedUser.setObjectId(reader.nextString());
} else if (name.equals("sessionToken"))
{
loggedUser.setSessionToken(reader.nextString());
} else
{
reader.skipValue(); //avoid some unhandle events
}
}
reader.endObject();
reader.close();
} catch (IOException e)
{
e.printStackTrace();
}
}