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;
}
}
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'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
I'm working to make client rest service with jasperserver to generate reports. I'm using the following code to make that:
I have problem in setting server url and report path,
for server url I put http://localhost:8081/jasperserver/
and as shown in next image I put report path rest/report/mytest/my_report but I get 404 not found error in line
File remoteFile = resource.get(File.class);
So how can I get the proper report path from jasperserver?
public class App2 {
private final static String serverUrl = "http://localhost:8081
/jasperserver/";
private final static String serverUser = "jasperadmin";
private final static String serverPassword = "jasperadmin";
public static void main(String arg[]) throws Exception {
Report reporte = new Report();
reporte.setFormat("pdf");
reporte.setOutputFolder("/home/ali/images");
ClientConfig clientConfig;
Map<String, String> resourceCache=new HashMap<String, String>();
clientConfig = new DefaultApacheHttpClientConfig();
clientConfig.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
clientConfig.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true);
ApacheHttpClient client = ApacheHttpClient.create(clientConfig);
client.addFilter(new HTTPBasicAuthFilter(serverUser, serverPassword));
String describeResourcePath = "/rest/resource" + "/mytest/my_report/";
String generateReportPath = "/rest/report" + "/mytest/my_report/" + "?RUN_OUTPUT_FORMAT=" + reporte.getFormat();
WebResource resource = null;
String resourceResponse = null;
if (resourceCache.containsKey(describeResourcePath)) {
resourceResponse = resourceCache.get(describeResourcePath);
} else {
resource = client.resource(serverUrl);
resource.accept(MediaType.APPLICATION_XML);
resourceResponse = resource.path(describeResourcePath).get(String.class);
resourceCache.put(describeResourcePath, resourceResponse);
}
Document resourceXML = parseResource(resourceResponse);
resourceXML = addParametersToResource(resourceXML, reporte);
resource = client.resource(serverUrl + generateReportPath);
resource.accept(MediaType.TEXT_XML);
System.out.println(resource);
String reportResponse = resource.put(String.class, serializetoXML(resourceXML));
String urlReport = parseReport(reportResponse);
resource = client.resource(urlReport);
System.out.println(resource);
File destFile = null;
try {
File remoteFile = resource.get(File.class);
File parentDir = new File(reporte.getOutputFolder());
destFile = File.createTempFile("report_", "." + getExtension(reporte.getFormat()), parentDir);
FileUtils.copyFile(remoteFile, destFile);
} catch (IOException e) {
throw e;
}
}
/**
*
* #return
* #throws DocumentException
*/
private static Document parseResource(String resourceAsText) throws Exception {
// LOGGER.debug("parseResource:\n" + resourceAsText);
Document document;
try {
document = DocumentHelper.parseText(resourceAsText);
} catch (DocumentException e) {
throw e;
}
return document;
}
/**
*
*/
private static String parseReport(String reportResponse) throws Exception {
String urlReport = null;
try {
Document document = DocumentHelper.parseText(reportResponse);
Node node = document.selectSingleNode("/report/uuid");
String uuid = node.getText();
node = document.selectSingleNode("/report/totalPages");
Integer totalPages = Integer.parseInt(node.getText());
if (totalPages == 0) {
throw new Exception("Error generando reporte");
}
urlReport = serverUrl + "/report/" + uuid + "?file=report";
} catch (DocumentException e) {
throw e;
}
return urlReport;
}
/**
*
* #param resource
* #param reporte
* #return
*/
private static Document addParametersToResource(Document resource, Report reporte) {
// LOGGER.debug("addParametersToResource");
Element root = resource.getRootElement();
Map<String, String> params = reporte.getParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null) {
root.addElement("parameter").addAttribute("name", key).addText(value);
}
}
// LOGGER.debug("resource:" + resource.asXML());
return resource;
}
/**
*
* #param aEncodingScheme
* #throws IOException
* #throws Exception
*/
private static String serializetoXML(Document resource) throws Exception {
OutputFormat outformat = OutputFormat.createCompactFormat();
ByteArrayOutputStream out = new ByteArrayOutputStream();
outformat.setEncoding("ISO-8859-1");
try {
XMLWriter writer = new XMLWriter(out, outformat);
writer.write(resource);
writer.flush();
} catch (IOException e) {
throw e;
}
return out.toString();
}
/**
*
* #param format
* #return
*/
private static String getExtension(String format) {
String ext = null;
if (format.equals(Report.FORMAT_PDF)) {
ext = "pdf";
} else if (format.equals(Report.FORMAT_EXCEL)) {
ext = "xls";
}
return ext;
}
}
I have fixed it,I need to change path
urlReport = serverUrl + "/report/" + uuid + "?file=report";
to
urlReport = serverUrl + "/rest/report/" + uuid + "?file=report";
in parseReport method
private static String parseReport(String reportResponse) throws Exception {
String urlReport = null;
try {
Document document = DocumentHelper.parseText(reportResponse);
Node node = document.selectSingleNode("/report/uuid");
String uuid = node.getText();
node = document.selectSingleNode("/report/totalPages");
Integer totalPages = Integer.parseInt(node.getText());
if (totalPages == 0) {
throw new Exception("Error generando reporte");
}
urlReport = serverUrl + "/report/" + uuid + "?file=report";
} catch (DocumentException e) {
throw e;
}
return urlReport;
}
I can return a single object into json format from the returnMachineTable method. But when i try to return all the objects from the Manufacturer table. i cannot return it as json format. Any suggestions?
#Path("/test")
public class testWS {
// private static final String api_version = "00.01.00";
#GET
#Path("/database")
// #Produces(MediaType.TEXT_PLAIN)
#Produces(MediaType.APPLICATION_JSON)
public Machine returnMachineTable() throws Exception {
// public String returnDatabaseStatus() throws Exception{
PreparedStatement query = null;
String myString = "";
String returnString = null;
Connection conn = null;
Machine u = null;
// returnString = "<p>data base context: "+"shit ass"+"</p>";
try {
conn = db.DBConn().getConnection();
query = conn.prepareStatement("SELECT * FROM MACHINE");
ResultSet rs = query.executeQuery();
while (rs.next()) {
myString = myString + rs.getString("LOCATION") + "!!!!!"
+ rs.getInt("MACHINEID") + "!!!!!"
+ rs.getInt("MACHINEID");
Long maintainenceDate = rs.getDate("MAINTDATE").getTime();
Long dateInstalled = rs.getDate("DATEINSTALLED").getTime();
u = new Machine();
u.setMachineId(rs.getInt("MACHINEID"));
u.setLocation(rs.getString("LOCATION"));
u.setMaintainenceDate(maintainenceDate);
u.setDateInstalled(dateInstalled);
u.setInstaller(rs.getString("INSTALLER"));
u.setMachineCode(rs.getString("MACHINECODE"));
u.setModel(rs.getString("MODEL"));
u.setManufacturerID(rs.getString("MANUFACTURERID"));
u.setName(rs.getString("NAME"));
u.setSoftware(rs.getString("SOFTWARE"));
myString = u.toString();
}
returnString = "---" + myString + "---\n";
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
// return returnString;
return u;
}
#GET
#Path("/ManufacturerTable")
#Produces(MediaType.APPLICATION_JSON)
public List<Manufacturer> returnManufacturerTable() throws Exception {
PreparedStatement query = null;
String myString = "";
String returnString = null;
Connection conn = null;
Manufacturer u = null;
List<Manufacturer> ulist = null;
int i = 0;
String uList = "";
try {
conn = db.DBConn().getConnection();
query = conn.prepareStatement("SELECT * FROM MANUFACTURER");
ResultSet rs = query.executeQuery();
JSONArray jsonArray = new JSONArray();
while (rs.next()) {
myString = myString + rs.getString("MANUFACTURERNAME")
+ "!!!!!" + rs.getInt("MANUFACTURERID");
u = new Manufacturer();
u.setManufacturerName(rs.getString("MANUFACTURERNAME"));
u.setManufacturerId(rs.getInt("MANUFACTURERID"));
ulist.add(i, u);
i++;
myString = myString+"\n"+u.toString();
}
returnString = "---" + myString + "---\n";
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
// return returnString;
/* Gson gson = new Gson();
return gson.toJson(ulist);*/
return ulist;
}
}
I think you should clean your code first.
IE: you are declaring this variable and never using it.
JSONArray jsonArray = new JSONArray();
Secondly, why you put all the object properties to a big string? Why not just add all objects to an array and then convert it to json array?
I want to get google contacts in my Blackberry Application. Is there any public libraries availabile for blackberry to do this?
I try to use Oauth-SignPost. But the libraies used in it not supported by blackberry.Then I try the following code
public static String requestToken(){
String url = C.REQUEST_URL;
String header = oauth_header(url, HttpProtocolConstants.HTTP_METHOD_GET);
String requestTokenUrl = concatURL(url, header);
HttpConnection httpConn = null;
InputStream input = null;
try{
HttpConnectionFactory factory = new HttpConnectionFactory( requestTokenUrl,
HttpConnectionFactory.TRANSPORT_WIFI |
HttpConnectionFactory.TRANSPORT_WAP2 |
HttpConnectionFactory.TRANSPORT_BIS |
HttpConnectionFactory.TRANSPORT_BES |
HttpConnectionFactory.TRANSPORT_DIRECT_TCP);
httpConn = factory.getNextConnection();
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
input = httpConn.openDataInputStream();
int resp = httpConn.getResponseCode();
if (resp == HttpConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
int ch;
while ( (ch = input.read()) != -1){
buffer.append( (char) ch);
}
String content = buffer.toString();
System.out.println("Response"+content);
}
return "";
} catch (IOException e) {
return "exception";
} catch (NoMoreTransportsException nc) {
return "noConnection";
} finally {
try {
httpConn.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The oauth_header() which create the appending parameters
public static String oauth_header(String url, String method) {
String nonce = nonce();
long timestamp = timestamp();
Hashtable pairs = new Hashtable();
pairs.put(C.OAUTH_CONSUMER_KEY, C.CONSUMER_KEY);
pairs.put(C.OAUTH_NONCE, nonce);
pairs.put(C.OAUTH_SIGNATURE_METHOD, C.SIGNATURE_METHOD);
pairs.put(C.OAUTH_TIMESTAMP, Long.toString(timestamp));
pairs.put(C.OAUTH_SCOPE,C.SCOPE);
pairs.put(C.OAUTH_VERSION, "1.0");
String sig = signature(method, url, pairs);
StringBuffer header_sb = new StringBuffer();
header_sb.append(C.OAUTH_CONSUMER_KEY).append("=").append(C.CONSUMER_KEY).append(",");
header_sb.append(C.OAUTH_NONCE).append("=").append(nonce).append(",");
header_sb.append(C.OAUTH_SIGNATURE).append("=").append(URLUTF8Encoder.encode(sig)).append(",");
header_sb.append(C.OAUTH_SIGNATURE_METHOD).append("=").append(C.SIGNATURE_METHOD).append(",");
header_sb.append(C.OAUTH_TIMESTAMP).append("=").append(Long.toString(timestamp)).append(",");
header_sb.append(C.OAUTH_SCOPE).append("=").append(C.SCOPE);
header_sb.append(C.OAUTH_VERSION).append("=").append("1.0");
return header_sb.toString();
}
Signature() and concatUrl() here
private static String signature(String method, String requestURL, Hashtable pairs) {
StringBuffer sb = new StringBuffer();
String[] keys = new String[pairs.size()];
Enumeration e = pairs.keys();
int i = 0;
while(e.hasMoreElements()) {
String k = (String)e.nextElement();
keys[i++] = k + "=" + URLUTF8Encoder.encode((String)pairs.get(k));
}
Arrays.sort(keys, new Comparator() {
public int compare(Object arg0, Object arg1) {
return ((String)arg0).compareTo((String)arg1);
}
});
for(i = 0; i < keys.length; i++) {
sb.append(keys[i]).append('&');
}
sb.deleteCharAt(sb.length()-1);
String msg = method.toUpperCase() +"&" + URLUTF8Encoder.encode(requestURL) + "&" + URLUTF8Encoder.encode(sb.toString());
System.out.println(msg);
StringBuffer key = new StringBuffer();
if(C.CONSUMER_SECRET != null) key.append(URLUTF8Encoder.encode(C.CONSUMER_SECRET));
key.append('&');
/* if(Const.tokenSecret != null){
key.append(URLUTF8Encoder.encode(Const.tokenSecret));
}*/
try {
return hmacsha1(key.toString(), msg);
} catch (Exception ex) {
return null;
}
}
private static String hmacsha1(String key, String message)
throws CryptoTokenException, CryptoUnsupportedOperationException, IOException {
HMACKey k = new HMACKey(key.getBytes());
HMAC hmac = new HMAC(k, new SHA1Digest());
hmac.update(message.getBytes());
byte[] mac = hmac.getMAC();
return Base64OutputStream.encodeAsString(mac, 0, mac.length, false, false);
}
public static String concatURL(String url, String header){
String newurl=url;
header = header.replace(',', '&');
newurl = newurl+"?"+header;
return newurl;
}
Then I get the signature_invalid Message. please Help me to find out the error.