Blackberry InputStream Closes Prematurely - blackberry

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.

Related

SQL Try..Catch..Finally Errors Not Displaying

How can I get the SQLException error messages below to display?
I have a site where users upload a data file. I have intentionally added incorrect data (text to a field that only allows integers) as a test of my error handling. Nothing is rendering in the view. I am sure that an exception is being thrown, as none of the data is in the database. If I remove the incorrect field, everything uploads fine. I have also tried both ex.toString() and ex.message with no success.
In my view, I have:
#ViewBag.ErrorMessage
Controller:
using (SqlCommand command = new SqlCommand(sql2, con))
{
try
{
// long SQL statement
con.Open();
command.ExecuteNonQuery();
TempData["shortMessage"] = "Dataset Uploaded Successfully.";
}
catch (SqlException ex)
{
ViewBag.ErrorMessage = ex.ToString();
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.ToString();
}
finally
{
con.Close();
}
}

I am not able to parse IOS driver page source

I got Page source using
String pageSource = driver.getPageSource();
Now i need to save this xml file to local in cache. So i need to get element attributes like x and y attribute value rather than every time get using element.getAttribute("x");. But I am not able to parse pageSource xml file to some special character. I cannot remove this character because at if i need element value/text it shows different text if i will remove special character. Appium is use same way to do this.
I was also facing same issue and i got resolution using below code which i have written and it works fine
public static void removeEscapeCharacter(File xmlFile) {
String pattern = "(\\\"([^=])*\\\")";
String contentBuilder = null;
try {
contentBuilder = Files.toString(xmlFile, Charsets.UTF_8);
} catch (IOException e1) {
e1.printStackTrace();
}
if (contentBuilder == null)
return;
Pattern pattern2 = Pattern.compile(pattern);
Matcher matcher = pattern2.matcher(contentBuilder);
StrBuilder sb = new StrBuilder(contentBuilder);
while (matcher.find()) {
String str = matcher.group(1).substring(1, matcher.group(1).length() - 1);
try {
sb = sb.replaceFirst(StrMatcher.stringMatcher(str),
StringEscapeUtils.escapeXml(str));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Writer output = null;
output = new BufferedWriter(new FileWriter(xmlFile, false));
output.write(sb.toString());
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if you will get that kind of problem then catch it with remove special character and parse again.
try {
doc = db.parse(fileContent);
} catch (Exception e) {
removeEscapeCharacter(file);
doc = db.parse(file);
}
It might works for you.
I can able to do same using SAXParser and add handler to do for this.
Refer SAX Parser

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 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