Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Contributor
Posts: 13
Registered: ‎11-21-2012
My Device: 8530
My Carrier: 07066868124

Consuming Web Service in Blackberry Plugin for Eclipse Indigo

I am having problem consuming a web service written in asp.net/vb.net hosted at http://www.transmodallimited.com. After writting the code i discovered that the app wasn't really hitting the web service. So, in order to be sure, I went testing with the httpconnection demo and discover that even the httpconnection demo is not working. I tried switching the MDS on, tried adding ';deviceside=true' to my link and it still not working.


The code of the Project is found below:

 

package mypackage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class ConnectionThread extends Thread {

    private boolean start = false;

    private boolean stop = false;

    private String url;

    private String data;

    public boolean sendResult = false;

    public boolean sending = false;
  
    private String requestMode = HttpConnection.POST;
  
    public String responseContent;

    public void run() {
        while (true) {
            if (start == false && stop == false) {
                try {
                    sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else if (stop) {
                return;
            } else if (start) {
                http();
            }
        }
    }
  
    private void getResponseContent( HttpConnection conn ) throws IOException {
        InputStream is = null;
        is = conn.openInputStream();

            // Get the length and process the data
            int len = (int) conn.getLength();
            if ( len > 0 ) {
                int actual = 0;
                int bytesread = 0;
                byte[] data = new byte[len];
                while ( ( bytesread != len ) && ( actual != -1 ) ) {
                    actual = is.read( data, bytesread, len - bytesread );
                    bytesread += actual;
                }
                responseContent = new String (data);
            } else {
                int ch;
                while ( ( ch = is.read() ) != -1 ) {

                }
            }
          
        
 
    }
  
    private void http() {
        System.out.println( url );
        HttpConnection conn = null;
        OutputStream out = null;
        int responseCode;

        try {
            conn = (HttpConnection) Connector.open(url);
            conn.setRequestMethod(requestMode);
            out = conn.openOutputStream();
            out.write(data.getBytes());
            out.flush();
            responseCode = conn.getResponseCode();

            if (responseCode != HttpConnection.HTTP_OK) {
                sendResult = false;
                responseContent = null;
            } else {
                sendResult = true;
                getResponseContent( conn );
            }
            start = false;
            sending = false;

        } catch (IOException e) {
            start = false;
            sendResult = false;
            sending = false;
        }

    }

    public void get(String url) {
        this.url = url;
        this.data = "";
        requestMode = HttpConnection.GET;
        sendResult = false;
        sending = true;
        start = true;
    }
  
    public void post(String url, String data) {
        this.url = url;
        this.data = data;
        requestMode = HttpConnection.POST;
        sendResult = false;
        sending = true;
        start = true;
    }

    public void stop() {
        stop = true;
    }

}


package mypackage;

import net.rim.device.api.ui.UiApplication;

/**
 * This class extends the UiApplication class, providing a
 * graphical user interface.
 */
public class MyApp extends UiApplication
{
    /**
     * Entry point for application
     * @param args Command line arguments (not used)
     */
 private ConnectionThread connThread = new ConnectionThread();
    public static void main(String[] args)
    {
        // Create a new instance of the application and make the currently
        // running thread the application's event dispatch thread.
        MyApp theApp = new MyApp();     
        theApp.enterEventDispatcher();
    }
 

    /**
     * Creates a new MyApp object
     */
    public MyApp()
    {      
        // Push a screen onto the UI stack for rendering.
   
     connThread.start();  
        pushScreen(new MyScreen(connThread));
    }  
}


package mypackage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;

import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.xml.jaxp.SAXParserImpl;
import java.io.ByteArrayInputStream;


public class MyScreen extends MainScreen {

    protected boolean sending = false;
 
    private ConnectionThread connThread;

    private BasicEditField username = new BasicEditField("Username:  ", "");
    private BasicEditField password = new BasicEditField("Password:  ", "");
  
    private BasicEditField response = new BasicEditField("Response:  ", "");
  
    private BasicEditField xmlResponse = new BasicEditField("xml:  ", "");

    private ButtonField sendButton = new ButtonField("Login");

    public MyScreen(ConnectionThread connThread) {
        this.connThread = connThread;
        setTitle("Web Service yahoo");
        FieldListener sendListener = new FieldListener();
        sendButton.setChangeListener(sendListener);
        response.setEditable( false );
        xmlResponse.setEditable( false );
        add(username);      
        add(password);      
        add(new SeparatorField());      
        add(sendButton);
        add(new SeparatorField());
        add(response);
        add(new SeparatorField());
        add(xmlResponse);
    }

    public boolean onClose() {
        connThread.stop();
        close();
        return true;
    }

    private String getFieldData() {
        StringBuffer sb = new StringBuffer();
        sb.append("Login?username=");
        sb.append(username.getText());
        sb.append("&password=");
        sb.append(password.getText());
        return sb.toString();
      
      
      
    }
  
    private void parseResults( String xml ){
        SAXParserImpl saxparser = new SAXParserImpl();
        ResponseHandler handler = new ResponseHandler();
        ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
        try {
            saxparser.parse( stream, handler );
        } catch ( Exception e ) {
            response.setText( "Unable to parse response.");
        }    
        response.setText( handler.response );
    }

    class FieldListener implements FieldChangeListener {
        public void fieldChanged(Field field, int context) {
            StringBuffer sb = new StringBuffer("Sending...");
            connThread.get("http://www.transmodallimited.com/Service.asmx/" + getFieldData());
            while (connThread.sending) {
                try {
                    Status.show( sb.append(".").toString() );
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (connThread.sendResult) {
                Status.show("Transmission Successful");
                xmlResponse.setText( connThread.responseContent );
                parseResults( connThread.responseContent );
            } else {
                Status.show("Transmission Failed");
            }

        }
    }
}

 

package mypackage;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;


/**
 *
 */
public class ResponseHandler extends DefaultHandler {
  
    public String response;
  
    private String element;
  
    public void startElement(String uri, String localName, String qName, Attributes attributes){
        element = localName;
    }
  
    public void characters(char[] ch, int start, int length) {
        if ( element.equals( "string" ) ){
            response = new String( ch, start, length );
        }
    }
  
}

Developer
Posts: 19,631
Registered: ‎07-14-2008
My Device: Not Specified

Re: Consuming Web Service in Blackberry Plugin for Eclipse Indigo

Can I suggest that you review the supplied httpDemo code and the way it works, get it going and then come back to this code.

 

There are some potential complication with attempting to start a Thread before your application is even running correctly.  So can I ask that you move your Thread starting logic to a different place, so that it is not executed by main(), but is instead executed by the Event Thread of your Application, once you have a real application.

 

The simplest way to do this is create the Thread in My|Screen, rather than pass it in, and then in the Constructor, put the start inside an invoke later, i.e.

UiApplication.getUiApplication.invokeLater(new Runnable() {

public void run() {

connThread.start();

}

});

 

Your connection thread code looks dodgy too.  When is data String actually created?  If it is not created, won't this statement fail with a Null Pointer Exception?

out.write(data.getBytes());

 

Also for an HTTP GET, you should not send data.  And for a POST, then you normally need to send a content length header.  So perhaps you need to review this processing to make sure you understand what you need to do?

 

One other area that will cause you grief is the Event Thread.  You need to update the UI on the Event Thread.  So when you get your data, you will have to swap to the Event Thread before updating any Fields.  Review the httpDemo for this.  Also see this:

http://supportforums.blackberry.com/t5/Java-Development/What-is-the-Event-Thread/ta-p/446865

 

There are other bits of code that look a little odd. For example, I would recommend that you look at ConnectionFactory and IOUtilities as two classes that will probably help make your code more robust or faster. 

 

Good luck.

Contributor
Posts: 13
Registered: ‎11-21-2012
My Device: 8530
My Carrier: 07066868124

Re: Consuming Web Service in Blackberry Plugin for Eclipse Indigo

Thanks peter.

 

When i got stuck, I tried the httpconnection demo and it is giving me 'java.io.interruptedIOException: Local connection timed out after ~ 120000' with the MDS simulator turned on.

 

I have also did what you instructed (Without a Thread) and i am getting 'java.io.interruptedIOException: Local connection timed out after ~ 120000'.

Developer
Posts: 19,631
Registered: ‎07-14-2008
My Device: Not Specified

Re: Consuming Web Service in Blackberry Plugin for Eclipse Indigo

|s this using the httpDemo code?

 

Try the same URL with that code.