Blackberry HttpConnection Timing Out - blackberry

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.

Related

Deferring persistence as device is being used in BlackBerry when listening file change

I tried to listen file change event in BlackBerry base on FileExplorer example, but whenever I added or deleted file, it always showed "Deferring persistence as device is being used" and I can't catch anything .Here is my code:
public class FileChangeListenner implements FileSystemJournalListener{
private long _lastUSN; // = 0;
public void fileJournalChanged() {
long nextUSN = FileSystemJournal.getNextUSN();
String msg = null;
for (long lookUSN = nextUSN - 1; lookUSN >= _lastUSN && msg == null; --lookUSN)
{
FileSystemJournalEntry entry = FileSystemJournal.getEntry(lookUSN);
// We didn't find an entry
if (entry == null)
{
break;
}
// Check if this entry was added or deleted
String path = entry.getPath();
if (path != null)
{
switch (entry.getEvent())
{
case FileSystemJournalEntry.FILE_ADDED:
msg = "File was added.";
break;
case FileSystemJournalEntry.FILE_DELETED:
msg = "File was deleted.";
break;
}
}
}
_lastUSN = nextUSN;
if ( msg != null )
{
System.out.println(msg);
}
}
}
Here is the caller:
Thread t = new Thread(new Runnable() {
public void run() {
new FileChangeListenner();
try {
Thread.sleep(5000);
createFile();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
Create file method worked fine:
private void createFile() {
try {
FileConnection fc = (FileConnection) Connector
.open("file:///SDCard/newfile.txt");
// If no exception is thrown, then the URI is valid, but the file
// may or may not exist.
if (!fc.exists()) {
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
outStream.write("test content".getBytes());
outStream.close();
fc.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
and output:
0:00:44.475: Deferring persistence as device is being used.
0:00:46.475: AG,+CPT
0:00:46.477: AG,-CPT
0:00:54.476: VM:+GC(f)w=11
0:00:54.551: VM:-GCt=9,b=1,r=0,g=f,w=11,m=0
0:00:54.553: VM:QUOT t=1
0:00:54.554: VM:+CR
0:00:54.596: VM:-CR t=5
0:00:55.476: AM: Exit net_rim_bb_datatags(291)
0:00:55.478: Process net_rim_bb_datatags(291) cleanup started
0:00:55.479: VM:EVTOv=7680,w=20
0:00:55.480: Process net_rim_bb_datatags(291) cleanup done
0:00:55.481: 06/25 03:40:41.165 BBM FutureTask Execute: net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
0:00:55.487: 06/25 03:40:41.171 BBM FutureTask Finish : net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
I also tried to remove the thread or create or delete file in simulator 's sdcard directly but it doesn't help. Please tell me where is my problem. Thanks
You instantiate the FileChangeListenner, but you never register it, and also don't keep it as a variable anywhere. You probably need to add this call
FileChangeListenner listener = new FileChangeListenner();
UiApplication.getUiApplication().addFileSystemJournalListener(listener);
You also might need to keep a reference (listener) around for as long as you want to receive events. But maybe not (the addFileSystemJournalListener() call might do that). But, you at least need that call to addFileSystemJournalListener(), or you'll never get fileJournalChanged() called back.

blackberry unable to send url request to server continuously

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();

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.

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.

Problems opening http connection from blackberry simulator

I'm having trouble when opening a simple HttpConnection from the simulator, I've have appended the deviceside=true suffix to my url, however it's still not working, I'm receiving an empty httpconnection with response code of 0. This is the code that's giving me problems:
public void readUrl(){
HttpConnection conn=null;
try {
conn = (HttpConnection) Connector.open("http://www.google.com;deviceside=true");
conn.setRequestMethod("GET");
if(conn.getResponseCode()==HttpConnection.HTTP_OK){
System.out.println("Create connection sucessfully");
}
} catch (ConnectionNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
DataInputStream din=null;
ByteVector responseBytes=null;
try {
din = conn.openDataInputStream();
responseBytes = new ByteVector();
int i = din.read();
while (-1 != i) {
responseBytes.addElement((byte) i);
i = din.read();
}
} catch (IOException e) {
//TODO: HANDLE EXCEPTIONS
e.printStackTrace();
}
responseBytes.toArray();
I have no idea what's going on. It supposed that by appending the deviceside=true it should connect directly. Anyway I tried too installing the MDS server and setting my url to deviceside=false, but the result was the same.
Now I tested the same code using a local url like http://localhost:8080/resources/mypage.html, and It worked as expected, so I was wondering if this could be a simulator configuration issue. How can I solve it?
Thanks a lot.
In my experience, you need to append ;deviceside=true when using the MDS simulator. There's a great post on the blackberry.com forums that shows you how to determine what connection suffix you should be using, as well as some general good advice on using connections in BlackBerry.
For something to help make it easier to get the content of your request, you can use the IOUtilities class:
InputStream stream = conn.openInputStream();
String contents = new String(IOUtilities.streamToBytes(stream));
";deviceside=true" is for DIRECT TCP transport. To use MDS transport you need to append with ";deviceside=false".
When you run on the device simulator you can use DIRECT TCP transport without the need of starting the MDS simulator. However if you want to test MDS transport, then you need to start MDS simulator before you start the device simulator.
In the Simulator setup tabs "General" do you have the "Launch MDS-CS with simulator" checked?
If so, you do not need to append any suffix at all...
Yes you're right, with deviceside=true the internet connection was used, however it seemed like it was a problem whit the HttpConnection class, when I used this code instead:
public StreamConnection openConnection(){
StreamConnection conn=null;
try {
conn = (StreamConnection) Connector.open(url+";deviceside=true");
//conn.setRequestMethod(httpMethod);
} catch (ConnectionNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return conn;
}
It worked correctly, so I was wondering something...when opening a connection in blackberry where I should put my code for checking the response code. After creating the connection? like the code above or after opening a dataStream like:
din = conn.openDataInputStream();
responseBytes = new ByteVector();
int i = din.read();
while (-1 != i) {
responseBytes.addElement((byte) i);
i = din.read();
}
Thanks.

Resources