{
"buildingNumber": 123,
"apatmentNumber": "4567",
"apartments": "123",
"isActive": true,
"possibleActions": [
"ENTER",
"EXIT"
],
"enterVia": {
"J1-B1": [
"DEFAULT_ROUTE"
],
"A1-D1": [
"DEFAULT_ROUTE"
]
},
"SectionMap": {},
"route": "abc|def (via xyz)"
}
I have above sample JSON. Whole content inside "enterVia" is dynamic.
I have to read this nested Json (shown below) from a response and send it in another request.
{
"J1-B1": [
"DEFAULT_ROUTE"
],
"A1-D1": [
"DEFAULT_ROUTE"
]
}
Please suggest a way if it is possible using Gson, ObjectMapper.
I found a solution using ObjectMapper. Below is the code:
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonParseTest {
public static void main(String[] args) {
String json = "{\r\n\t\"J1-B1\": [\r\n\t\t\"DEFAULT_ROUTE\"\r\n\t],\r\n\t\"A1-D1\": [\r\n\t\t\"DEFAULT_ROUTE\"\r\n\t]\r\n}";
ObjectMapper objectMapper = new ObjectMapper();
Map<String, List<String>> routesMap = null;
try {
routesMap = objectMapper.readValue(json, new TypeReference<Map<String, List<String>>>(){});
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("read response output: " +routesMap);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
String jsonRequest = null;
try {
jsonRequest = objectMapper.writeValueAsString(routesMap);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("next request output: " +jsonRequest);
}
}
Output of the program:
read response output: {J1-B1=[DEFAULT_ROUTE], A1-D1=[DEFAULT_ROUTE]}
next request output: {"J1-B1":["DEFAULT_ROUTE"],"A1-D1":["DEFAULT_ROUTE"]}
Related
I am using HikariCP-3.1.0.jar for managing the connection pool. But When I request to my Database, it generates new more connection in every request. Every request generates a double connection or more in my database session.
Here is the configuration of my HikariCP connection to oracle database...
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JDBConnection {
public static Connection getConnection() {
Connection con = null;
try {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:oracle:thin:#localhsot:1521/mydb");
config.setUsername("dbuser");
config.setPassword("dppass");
config.setMaximumPoolSize(2000);
config.setAutoCommit(false);
config.setMinimumIdle(10);
config.setConnectionTimeout(30000);//second
config.setIdleTimeout(2 * 60 * 1000);//2 minutes
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.setDriverClassName("oracle.jdbc.OracleDriver");
HikariDataSource dataSource = new HikariDataSource(config);
con = dataSource.getConnection();
} catch (SQLException ex) {
Logger.getLogger(JDBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
public static void releaseConnection(Connection con) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(DBConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Calling like below:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Calling {
public void getMessages() {
String sql = "mysql";
Connection con = JDBConnection.getConnection();
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String title = rs.getString("title");
}
} catch (SQLException ex) {
Logger.getLogger(Calling.class.getName()).log(Level.SEVERE, null, ex);
} finally {
JDBConnection.releaseConnection(con);
}
}
}
Is there any wrong with the configuration in HikariCP? Please help me
If I am using QOS type 1 means the broker will continue to send the message to the subscriber until it gets an acknowledgment. How can i set or return ack ? Please anyone shed some light on this.
This is my source code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import java.util.Vector;
import org.fusesource.hawtbuf.Buffer;
import org.fusesource.hawtbuf.UTF8Buffer;
import org.fusesource.mqtt.client.Callback;
import org.fusesource.mqtt.client.CallbackConnection;
import org.fusesource.mqtt.client.Listener;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;
import com.adventnet.management.log.Log;
import com.adventnet.nms.util.NmsLogMgr;
public class DefaultMqttListener implements IMqttListener,Runnable{
long count = 0;
long start = System.currentTimeMillis();
private HashMap serverDetailsHash;
public DefaultMqttListener(HashMap serverProp)
{
this.serverDetailsHash = serverProp;
}
CallbackConnection myconnection;
#Override
public void init() {
MQTT mqtt = new MQTT();
String user = env("APOLLO_USER", (String)serverDetailsHash.get("userName")); //No I18N
String password = env("APOLLO_PASSWORD", (String)serverDetailsHash.get("password")); //No I18N
String host = env("APOLLO_HOST", (String)serverDetailsHash.get("hostName")); //No I18N
int port = Integer.parseInt(env("APOLLO_PORT", (String)serverDetailsHash.get("port")));
try {
mqtt.setHost(host, port);
mqtt.setUserName(user);
mqtt.setPassword(password);
final CallbackConnection connection = mqtt.callbackConnection();
myconnection = connection;
connection.listener(new org.fusesource.mqtt.client.Listener() {
public void onConnected() {
}
public void onDisconnected() {
}
public void onFailure(Throwable value) {
value.printStackTrace();
System.exit(-2);
}
public void onPublish(UTF8Buffer topic, Buffer msg, Runnable ack) {
long time = System.currentTimeMillis();
callback( topic, msg, ack,connection,time);
}
});
connection.connect(new Callback<Void>() {
#Override
public void onSuccess(Void value) {
NmsLogMgr.M2MERR.log("MQTT Listener connected in ::::", Log.SUMMARY);
ArrayList getTopics = (ArrayList)serverDetailsHash.get("Topics");
for(int i=0;i<getTopics.size();i++)
{
HashMap getTopic = (HashMap)getTopics.get(i);
String topicName = (String) getTopic.get("topicName");
String qosType = (String) getTopic.get("qosType");
Topic[] topic = {new Topic(topicName, getQosType(qosType))};
connection.subscribe(topic, new Callback<byte[]>() {
public void onSuccess(byte[] qoses) {
}
public void onFailure(Throwable value) {
value.printStackTrace();
System.exit(-2);
}
});
}
//Topic[] topics = {new Topic("adminTest", QoS.AT_LEAST_ONCE),new Topic("adminTest1", QoS.AT_LEAST_ONCE)};
}
#Override
public void onFailure(Throwable value) {
value.printStackTrace();
System.exit(-2);
}
});
// Wait forever..
synchronized (Listener.class) {
while(true){
Listener.class.wait();}
}
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String env(String key, String defaultValue) {
String rc = System.getenv(key);
if( rc== null ){
return defaultValue;}
return rc;
}
#Override
public void callback(UTF8Buffer topic, Buffer msg, Runnable ack, CallbackConnection connection, long time) {
// TODO Auto-generated method stub
try {
String Message = msg.utf8().toString();
MQTTMessage mqttMsg = new MQTTMessage();
mqttMsg.setMQTTMessage(Message);
mqttMsg.setTime(time);
mqttMsg.setTopic(topic);
mqttMsg.sethostName((String) serverDetailsHash.get("hostName"));
MQTTCacheManager.mgr.addToCache(mqttMsg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void close() {
// TODO Auto-generated method stub
NmsLogMgr.M2MERR.log("myconnection closed", Log.SUMMARY);
myconnection.disconnect(new Callback<Void>() {
#Override
public void onSuccess(Void value) {
System.exit(0);
}
#Override
public void onFailure(Throwable value) {
value.printStackTrace();
System.exit(-2);
}
});
}
#Override
public void run() {
this.init();
// TODO Auto-generated method stub
}
public QoS getQosType(String name)
{
Properties qosContainer = new Properties();
qosContainer.put("0", QoS.AT_MOST_ONCE);
qosContainer.put("1", QoS.AT_LEAST_ONCE);
qosContainer.put("2", QoS.EXACTLY_ONCE);
QoS qosName = (QoS) qosContainer.get(name);
return qosName;
}
}
You don't send the acknowledgement in your code at all, it should all be handled by the MQTT library you are using.
The QOS ack's packets are between the publisher and the broker and then separately between the broker and any subscribers.
I didn't use the Java library but you need to subscribe to the topic specifying the QoS level 1 (to have at least one delivery) or QoS level 2 (to have exactly once delivery). In these cases, the underlying library sends the ACK packets to the broker.
i am trying to create account using Google Provisioning API from reseller account. Let we say the reseller account is : reseller#reseller.com . Before that i already subscribe domain "domain.com" from Google Reseller API.
Based this link (https://developers.google.com/google-apps/provisioning/#creating_a_user_for_a_domain) i create script like this :
package gapps;
import com.google.gdata.data.*;
import com.google.gdata.client.*;
import com.google.gdata.data.appsforyourdomain.AppsForYourDomainException;
import com.google.gdata.data.appsforyourdomain.generic.GenericEntry;
import com.google.gdata.util.*;
import java.net.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level`enter code here`;
import java.util.logging.Logger;
import sample.appsforyourdomain.labs.provisioning.ProvisioningApiMultiDomainSampleClient;
import sample.appsforyourdomain.labs.provisioning.ProvisioningApiMultiDomainSampleClient.UserProperty;
public class Gapps {
public static void main(String[] args) {
try {
Map<UserProperty, String> map = new HashMap<UserProperty, String>() ;
map.put(ProvisioningApiMultiDomainSampleClient.UserProperty.ADMIN ,"isAdmin");
GenericEntry genericEntry = new GenericEntry();
ProvisioningApiMultiDomainSampleClient provisioningApiMultiDomainSampleClient = new ProvisioningApiMultiDomainSampleClient("reseller#reseller.com", "*******", "domain.com", "sample-api");
genericEntry = provisioningApiMultiDomainSampleClient.createUser("user", "*******", "fname", "lname", map);
System.out.println(genericEntry.toString());
} catch (AppsForYourDomainException ex) {
Logger.getLogger(Gapps.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(Gapps.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Gapps.class.getName()).log(Level.SEVERE, null, ex);
} catch (ServiceException ex) {
Logger.getLogger(Gapps.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
but after try to compile it's always return
You are not authorized to access this API.
I am stuck here. Is there something that i am missed ..?
Is API access enabled for your reseller domain?
http://support.google.com/a/bin/answer.py?hl=en&answer=60757
package com.google.serviceacc;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.JSONException;
import org.json.JSONObject;
public class GoogleServiceAccount<E> {
static String keyAlias = "privatekey";
public static byte[] signData(byte[] data, PrivateKey privateKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException
{
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(data);
return signature.sign();
}
/*public static String encodeBase64(byte[] rawData)
{
byte[] data = Base64.encodeBase64(rawData);
return data.toString();
}*/
private static PrivateKey getPrivateKey(String keyFile, String password)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException
{
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(keyFile), password.toCharArray());
PrivateKey privateKey = (PrivateKey) keystore.getKey(keyAlias, password.toCharArray());
return privateKey;
}
public static void main(String[] args) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, IOException {
String keystoreLoc = "C:/Users/xyz/Downloads/b5b400df17628d8.p12";
String password = "notasecret";
String jwtStr=null;
String jwtClaimStr=null;
PrivateKey privateKey=null;
JSONObject jwtHeader=new JSONObject();
try {
jwtHeader.put("alg","RS256");
jwtHeader.put("typ","JWT");
jwtStr= jwtHeader.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encodedHeader = Base64.encodeBase64(jwtStr.getBytes("UTF-8"));
System.out.println("Original HEaderString: " + jwtStr );
System.out.println("Base64 Encoded HeaderString : " + new String(encodedHeader));
JSONObject jwtClaimSet= new JSONObject();
try {
jwtClaimSet.put("iss", "client_id_email#developer.gserviceaccount.com");
jwtClaimSet.put("scope", "https://www.googleapis.com/auth/devstorage.readonly");
jwtClaimSet.put("aud", "https://accounts.google.com/o/oauth2/token");
jwtClaimSet.put("exp", "1328554385");
jwtClaimSet.put("iat", "1328550785");
jwtClaimStr=jwtClaimSet.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encodedClaimSet=Base64.encodeBase64(jwtClaimStr.getBytes("UTF-8"));
System.out.println("Original ClaimSet String:"+jwtClaimStr);
System.out.println("Base64 Encoded ClaimSet:"+ new String(encodedClaimSet) );
StringBuffer token = new StringBuffer();
token.append(Base64.encodeBase64(jwtStr.getBytes("UTF-8")));
token.append(".");
token.append(Base64.encodeBase64(jwtClaimStr.getBytes("UTF-8")));
privateKey= getPrivateKey(keystoreLoc, password);
byte[] sig = signData(token.toString().getBytes("UTF-8"), privateKey);
byte[] signedPayload =Base64.encodeBase64(sig);
token.append(".");
token.append(signedPayload);
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("https://accounts.google.com/o/oauth2/token");
method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
method.addParameter("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer");
System.out.println("printing Token.toString():"+token.toString());
method.addParameter("assertion",token.toString());
System.out.println("Printing QuerString:"+method.getQueryString());
System.out.println("Printing request char set:"+method.getRequestCharSet());
try {
int responseCode=client.executeMethod(method);
System.out.println(responseCode);
System.out.println(method.getResponseBodyAsString());
System.out.println(method.getURI());
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If i try to execute the above code i' am getting
{
"error" : "invalid_grant"
}
I created a service account and was able to download private key through the above code.But when i try to exute the request to retrieve the accesstoken iam getting invalid grant error
Do I need to add something?
I Finally got the output!!!!
Updated code is:
package com.voxmobili.sng.cnx.gmail.sync;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.JSONException;
import org.json.JSONObject;
public class GoogleServiceAccount<E> {
static String keyAlias = "privatekey";
public static byte[] signData(byte[] data, PrivateKey privateKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException
{
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(data);
return signature.sign();
}
public static String encodeBase64(byte[] rawData)
{
byte[] data = Base64.encodeBase64(rawData);
return data.toString();
}
private static PrivateKey getPrivateKey(String keyFile, String password)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException
{
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(keyFile), password.toCharArray());
PrivateKey privateKey = (PrivateKey) keystore.getKey(keyAlias, password.toCharArray());
return privateKey;
}
public static void main(String[] args) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, IOException {
String keystoreLoc = "C:/Users/xyz/Downloads/b5b400df17628d8.p12";
String password = "notasecret";
String jwtHeaderStr=null;
String jwtClaimStr=null;
PrivateKey privateKey=null;
//JWT HEADER
JSONObject jwtHeader=new JSONObject();
try {
jwtHeader.put("alg","RS256");
jwtHeader.put("typ","JWT");
jwtHeaderStr= jwtHeader.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encodedHeader = Base64.encodeBase64(jwtHeaderStr.getBytes("UTF-8"));
System.out.println("Original HEaderString: " + jwtHeaderStr );
System.out.println("Base64 Encoded HeaderString : " + new String(encodedHeader));
//JWT CLAIMSET
JSONObject jwtClaimSet= new JSONObject();
long iat = (System.currentTimeMillis()/1000)-60;
long exp = iat + 3600;
try {
jwtClaimSet.put("iss", "4459#developer.gserviceaccount.com");
jwtClaimSet.put("scope", "https://www.googleapis.com/auth/calendar.readonly");
jwtClaimSet.put("aud", "https://accounts.google.com/o/oauth2/token");
jwtClaimSet.put("exp", +exp);
jwtClaimSet.put("iat",+iat);
jwtClaimStr=jwtClaimSet.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encodedClaimSet=Base64.encodeBase64(jwtClaimStr.getBytes("UTF-8"));
System.out.println("Original ClaimSet String:"+jwtClaimStr);
System.out.println("Base64 Encoded ClaimSet:"+ new String(encodedClaimSet) );
StringBuffer token = new StringBuffer();
token.append(new String(encodedHeader));
token.append(".");
token.append(new String(encodedClaimSet));
//JWT SIGNATURE
privateKey= getPrivateKey(keystoreLoc, password);
byte[] sig = signData(token.toString().getBytes("UTF-8"), privateKey);
byte[] encodedSig=Base64.encodeBase64(sig);
System.out.println("Signature before encoding:"+ new String(encodedSig));
String signedPayload =encodeBase64(sig);
//System.out.println("Signature before encoding:"+signedPayload);
token.append(".");
//token.append(signedPayload);
token.append(new String(encodedSig));
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("https://accounts.google.com/o/oauth2/token");
method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
method.addParameter("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer");
System.out.println("printing Token.toString():"+token.toString());
method.addParameter("assertion",token.toString());
try {
int responseCode=client.executeMethod(method);
System.out.println(responseCode);
System.out.println(method.getResponseBodyAsString());
System.out.println(method.getURI());
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
i am developing app in blackberry version 5.0, and i had import all library which require for json in 5.0.
i had download library from this url
http://supportforums.blackberry.com/t5/Java-Development/JSON-library/td-p/573687
even i not getting response, what i had miss in this code please help me.
Below is my code For json parsing.
package mypackage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import JSON_ME_Library.src.org.json.me.JSONArray;
import JSON_ME_Library.src.org.json.me.JSONException;
import JSON_ME_Library.src.org.json.me.JSONObject;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public final class MyScreen extends MainScreen
{
String url="http://www.appymail.com/iphone-messenger/456842/";
public MyScreen()
{
setTitle("Json Parsing Sample");
String aa=jsonresponse(url);
if(aa.equalsIgnoreCase(""))
{
add(new LabelField("NO res"));
}
else
{
parseJSONResponceInBB(aa);
}
}
void parseJSONResponceInBB(String jsonInStrFormat)
{
try {
JSONObject json = new JSONObject(jsonInStrFormat);
JSONArray jArray= json.getJSONArray("messages");
//JSONArray arr=jArray.getJSONArray(0);
for(int i=0;i<jArray.length();i++)
{
JSONObject j = jArray.getJSONObject(i);
String from = j.getString("id");
add(new LabelField("id=="+from));
String to =j.getString("title");
add(new LabelField("title=="+to));
String message=j.getString("body");
add(new LabelField("Body=="+message));
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
public static String jsonresponse (String url)
{
String response = null;
HttpConnection httpConnection = null;
InputStream inStream = null;
int code;
StringBuffer stringBuffer = new StringBuffer();
try {
httpConnection = (HttpConnection) Connector.open(url, Connector.READ);
httpConnection.setRequestMethod(HttpConnection.GET);
code = httpConnection.getResponseCode();
if(code == HttpConnection.HTTP_OK)
{
inStream=httpConnection.openInputStream();
int c;
while((c=inStream.read())!=-1)
{
stringBuffer.append((char)c);
}
response=stringBuffer.toString();
System.out.println("Response Getting from Server is ================" + response);
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.inform("Connection error");
}
});
}
}
catch (Exception e)
{
System.out.println("caught exception in jsonResponse method"+e.getMessage());
}
finally
{
// if (outputStream != null)
// {
// outputStream.close();
// }
if (inStream != null)
{
try {
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (httpConnection != null )
{
try {
httpConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
}
Hello dear you need to use url extension for blackberry
so please try to change this line
String aa=jsonresponse(url);
as
String aa=jsonresponse(url+";interface=wifi");
After successfully completed download data from url then once check String aa getting any value or not? if it get data then follow
try this if it is working fine then go through this following link
Guide for URL extensions
Enter Url in
String url="Your url";
String request=jsonresponse(url+";interface=wifi");
String response = parseJSONResponceInBB(request);
if(response .equalsIgnoreCase(""))
{
add(new LabelField("NO res"));
}
else
{
add(new LabelField(response ));
}