blackberry unable to send url request to server continuously - url

this is the code i wrote to send the url request using a thread:
while(true)
{
String url="http://192.168.1.7:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.23&lon=21.998;interface=wifi";
try{
StreamConnection conn = (StreamConnection)Connector.open(url, Connector.READ_WRITE);
conn.openInputStream();
Thread.sleep(30*1000);
conn.close();
}catch(Exception e)
{
e.printStackTrace();
}
try {
Thread.sleep(30*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the code i used to this thread:
Calendar cal=Calendar.getInstance();
long time=cal.get(Calendar.HOUR);
add(new RichTextField(String.valueOf(time)));
(new test()).start();
by using this code i am able to send one request successfully but after that server is not receiving other request. please provide me a solution.

Firstly, when you're using a while loop like this, you shouldn't put the sleep within the try method.
while(true)
{
try{
String url="http://192.19.18.10:8084/SFTS/updateLocation.jsp?empid=12304&lat="+lan+".23&lon=21.998;interface=wifi";
StreamConnection conn = (StreamConnection)Connector.open(url, Connector.READ_WRITE);
conn.openInputStream();;
}catch(Exception e)
{
e.printStackTrace();
}
try {
Thread.sleep(30*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Secondly, you're constantly trying to create a new stream without first closing the previous connection. Either read up on how StreamConnection works effectively, or simply use ConnectionFactory and not StreamConnection.
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null) {
try {
HttpConnection httpConn;
httpConn = (HttpConnection) connDesc.getConnection();
httpConn.close();
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
The above is for OS 5 and above, in your case... as the connection seems to work the first time, in your existing code I would try simply closing the connection using:
conn.close();

Related

Mqtt: Persist message on server side

We decided to use mqtt protocol for chat module in our mobile application. I want to save messages of topic in server side also. But i saw,mqtt client is global here,so one way is i have to subscribe single instance of mqtt client to all topics and save messages in database. but is it right approach to do it. i am just worring about it.
private void buildClient(){
log.debug("Connecting... "+CLIENT_ID);
try {
mqttClient = new MqttClient(envConfiguration.getBrokerUrl(), CLIENT_ID);
} catch (MqttException e) {
log.debug("build client stopped due to "+e.getCause());
}
chatCallback = new ChatCallback();
mqttClient.setCallback(chatCallback);
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(false);
}
#Override
public void connect() {
if(mqttClient == null || !mqttClient.getClientId().equals(CLIENT_ID)){
buildClient();
}
boolean tryConnecting = true;
while(tryConnecting){
try {
mqttClient.connect(mqttConnectOptions);
} catch (Exception e) {
log.debug("connection attempt failed "+ e.getCause() + " trying...");
}
if(mqttClient.isConnected()){
tryConnecting = false;
}else{
pause();
}
}
}
#Override
public void publish() {
boolean publishCallCompletedErrorFree = false;
while (!publishCallCompletedErrorFree) {
try {
mqttClient.publish(TOPIC, "hello".getBytes(), 1, true);
publishCallCompletedErrorFree = true;
} catch (Exception e) {
log.debug("error occured while publishing "+e.getCause());
}finally{
pause();
}
}
}
#Override
public void subscribe() {
if(mqttClient != null && mqttClient.isConnected()){
try {
mqttClient.subscribe(TOPIC, 2);
} catch (MqttException e) {
log.debug("subscribing error.."+e.getCause());
}
}
}
#Override
public void disconnect() {
System.out.println(this.mqttClient.isConnected());
try {
mqttClient.disconnect();
log.debug("disconnected..");
} catch (MqttException e) {
log.debug("erro occured while disconneting.."+e.getCause());
}
}
There are two possibilities how to solve this issue:
Write a MQTT client that subscribes to all topics using a wildcard (# in MQTT)
Write a broker plugin that does the job for you, depending on the broker implementation you're using
There is a good description of how to implement both options at the HiveMQ website, also describing limitations of the first option.

Critical Tunnel failure exception. How to solve this

I wrote the below code to send location coordinates to server:
setTitle("version 5.0");
Criteria criteria = new Criteria();
criteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
// bc.setFailoverMode(GPSInfo.GPS_MODE_ssCDMA_MS_ASSIST, 2, 100);
try {
LocationProvider lp=LocationProvider.getInstance(criteria);
if(lp !=null)
{
Location loc=null;
// while(loc==null)
// {
loc=lp.getLocation(-1);
// }
if(loc!=null){
add(new EditField(loc.getQualifiedCoordinates().getLatitude()+"\n"+loc.getQualifiedCoordinates().getLongitude(),""));
}
else
add(new EditField("unable to find the location provider", ""));
}
else
{
add(new EditField("unable to find the location provider", ""));
}
} catch (LocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ButtonField b = new ButtonField("Send");
add(b);
b.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
try{
String url="http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true";
Dialog.alert(url);
ConnectionFactory factory = new ConnectionFactory();
// use the factory to get a connection
ConnectionDescriptor conDescriptor = factory.getConnection(url, TransportInfo.TRANSPORT_TCP_CELLULAR,null);
if ( conDescriptor != null ) {
HttpConnection conn = (HttpConnection) conDescriptor.getConnection();
Dialog.alert("http");
//conn.setRequestMethod(HttpConnection.GET);
Dialog.alert("conn.setre");
int responseCode = conn.getResponseCode();
Dialog.alert(Integer.toString(responseCode));
if(responseCode == HttpConnection.HTTP_OK)
{
Dialog.alert("OK");
InputStream data = conn.openInputStream();
StringBuffer raw = new StringBuffer();
byte[] buf = new byte[4096];
int nRead = data.read(buf);
while(nRead > 0)
{
raw.append(new String(buf, 0, nRead));
nRead = data.read(buf);
}
}
}
}catch(Exception e){
Dialog.alert(e.getMessage());
}
}
});
I am getting an exception Critical tunnel failure. But i am able to retrieve the location coordinates correctly. I am using blackberry 8520 with airtel sim which is enabled with data services. Actually this app worked well in the mobile with version 5.0. But it's not working in the mobile which i've upgraded from 4.6.1.3 to 5.0.0 what might be the problem? Please provide me a solution. thank you
I also tried the below url's:
http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true;apn=null
http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true;apn=airtelgprs.com
I also enabled apn settings in my mobile
It is because you haven't set up the apn correctly. As you are using direct tcp, the apn has to be set in order to connect to the network.
Also , network connections should be done on a separate thread.

None of code can establish http connection over BIS

I am new in developing Blackberry Application.
In these three days, I already searched and learned in both forum and tutorial from the RIM itself. But none of them can solve my problem. >.<
So. I already tried some different methods to establish http connection over BIS in 4.6.
These are the following codes:
1.
HttpConnection httpConnection;
String url = "myURL;deviceside=true";
try{
httpConnection = (HttpConnection) Connector.open(url);
Dialog.inform(">.<");
}
catch(Exception e)
{
Dialog.inform(e.getMessage());
}
From the code #1 above, none of the dialogs are displayed.
String url = "myURL";
try {
StreamConnection s = (StreamConnection)Connector.open(url);
InputStream input = s.openInputStream();
Dialog.inform("sblm byte");
byte[] data = new byte[256];
int len = 0;
StringBuffer raw = new StringBuffer();
Dialog.inform("stlh buat byte");
while( -1 != (len = input.read(data))) {
raw.append(new String(data, 0, len));
}
Dialog.inform("stlh while");
response = raw.toString();
Dialog.inform(response);
input.close();
s.close();
}
catch(Exception e) { }
As well as code #1, this code above also doesnt pop up any dialog.
I am desperately need the right guide for establishing simple http connection. Is there any technique that I missed? Do I need any signature for this? Do I need extra setting in both my Blackberry device (BB 8900 with OS 5.00) or in my compiler, Eclipse?
Thank you.
Try this code.
try {
HttpConnection httpConnection=(HttpConnection)Connector.open(url);
httpConnection.setRequestMethod(HttpConnection.GET);
if(httpConnection.getResponseCode()==HttpConnection.HTTP_OK)
{
InputStream is=httpConnection.openInputStream();
int ch;
StringBuffer buffer=new StringBuffer();
while((ch=is.read())!=-1)
{
buffer.append((char)ch);
}
}
} catch (IOException e) {
System.out.println("Exception From Thread"+e);
e.printStackTrace();
}
}

Blackberry InputStream Closes Prematurely

The following code is used to get an XML file from a web server, and today, for the last few runs, this throws an exception with an error message "stream close." I have not modified this code since yesterday, nor have I modified any methods that handle the parsing.
The idea is this builds a list of item from the XML file pulled from the fullurl. There should 20 items in the list (based on the XML file I am using right now). In the last few runs, the parsing operation has thrown the exception mentioned above, and only stores 5 items. The method public void endDocument() never gets called.
Any thoughts would be helpful, since this will have to be moved to a background task, and I would like to have solved before I do that.
public void getAndParseXML() {
HttpConnection xmlcon = null;
InputStream xmlinput = null;
SAXParserFactory spf = null;
String fullurl = this.getNewsUrl() + NewsListBuilderTask.CONNECTION_STRING; // URL of XML file along specification for connection type
if ( (TransportInfo.isTransportTypeAvailable(TransportInfo.TRANSPORT_TCP_WIFI)) && (TransportInfo.hasSufficientCoverage(TransportInfo.TRANSPORT_TCP_WIFI)) )
fullurl += NewsListBuilderTask.WIFI_STRING;
try {
xmlcon = (HttpConnection)Connector.open( fullurl, Connector.READ, false ); // open connection to XML source
spf = SAXParserFactory.newInstance(); // set up xml parsers
xmlinput = xmlcon.openInputStream(); // set up input stream
SAXParser saxparser = spf.newSAXParser(); // create a new parser object
saxparser.parse( xmlinput, this ); // parse operations start here
}
catch( IOException ex ) {
System.out.println( "IOException Caught:\t" + ex.getMessage() ); // set a default item if any exception occurs with retreiving or parsing XML file
this.createDefaultItem();
}
catch (SAXException ex) {
System.out.println( "SAXException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
catch ( IllegalArgumentException ex ) {
System.out.println( "IllegalArgumentException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
catch (ParserConfigurationException ex) {
System.out.println( "ParserConfigurationException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
finally {
if ( xmlinput != null) {
try {
xmlinput.close(); // attempt to close all connections
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if ( xmlcon != null ) {
try {
xmlcon.close();
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
}
NOTE: The fullurl used ends up bieng "http://somexmlfile.com?type=photo;deviceside=true" with ";interface=wifi" appended if available.

Blackberry HttpConnection Timing Out

I am trying to grab an XML file for parsing with the following:
private void getAndParseXML( String _xmlurl ) {
HttpConnection xmlcon = null;
InputStream input = null;
SAXParserFactory spf = null;
try {
xmlcon = (HttpConnection)Connector.open( _xmlurl, Connector.READ ); // open connection to XML source
spf = SAXParserFactory.newInstance(); // set up xml parsers
input = xmlcon.openInputStream(); // set up input stream
SAXParser saxparser = spf.newSAXParser(); // create a new parser object
saxparser.parse( input, this ); // parse operations start here
}
catch( IOException ex ) {
System.out.println( "IOException Caught:\t" + ex.getMessage() ); // set a default item if any exception occurs with retreiving or parsing XML file
}
catch (SAXException ex) {
System.out.println( "SAXException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
}
catch ( IllegalArgumentException ex ) {
System.out.println( "IllegalArgumentException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
}
catch (ParserConfigurationException ex) {
System.out.println( "ParserConfigurationException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
}
finally {
if ( input != null) {
try {
input.close(); // attempt to close all connections
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if ( xmlcon != null ) {
try {
xmlcon.close();
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
} // END ----------------------------------------------------------------------------
But the I get an exception thrown saying the connection timed out after 12 seconds. This after the line input = xmlcon.openInputStream(); is executed.
If this is relevant, it is the IOException that gets caught, and determining if there is an active network connection is done before this method is called. Did I miss something?
EDIT: Just for clarification, this would be the first instance of a network connection in the application. Before this block of code, a simple test:
private boolean isConnectedToNetwork() {
boolean isConnected = false;
if ( (TransportInfo.isTransportTypeAvailable(TransportInfo.TRANSPORT_TCP_CELLULAR)) || (TransportInfo.isTransportTypeAvailable(TransportInfo.TRANSPORT_TCP_WIFI)) )
if ( (TransportInfo.hasSufficientCoverage(TransportInfo.TRANSPORT_TCP_CELLULAR)) || (TransportInfo.hasSufficientCoverage(TransportInfo.TRANSPORT_TCP_WIFI)) )
isConnected = true;
return isConnected;
}
to make sure a connection would be possible, before attempting to retrieve an XML file.
Mike, everything looks OK.
However here are some ideas to think of:
Can you open the URL from your browser?
What BB Transport do you use to open the connection (for instance, maybe it fails on BES, but will work Ok on Direct TCP or Wi-Fi)?
By the moment of this call, have the code that "determins if there is an active network connection" closed all connections it might have opened (if any) during detection?
Found the issue. The url, in this case _xmlurl, needed to be appended with ";deviceside=true" to ensure a direct TCP/IP connection was established. This makes sure an HttpConnection is made through the cellular network. In other words, to make sure the connection was not made through the Blackberry MDS.
Also, a check was needed:
if ( (TransportInfo.isTransportTypeAvailable(TransportInfo.TRANSPORT_TCP_WIFI)) && (TransportInfo.hasSufficientCoverage(TransportInfo.TRANSPORT_TCP_WIFI)) )
the wi-fi antenna was on. If the above ervaluated to true, the url (again _xmlurl) needed to be further appended with ";interface=wifi" to avoid the cellular network , but still open a direct TCP/IP connection.

Resources