BlackBerry HttpCOnnection - blackberry

/* Hi Iam developing an application where the BB app needs to post data to server. The Http connection works fine on Blackberry emulator, but when i try to test it on a real device the application cannot post data to server. the following is my code:
*/
package com.sims.datahandler;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import com.sims.commonmethods.CommonMethods;
import com.sims.screens.MenuScreen;
/**
*
* #author SaiKrishnaPawar
*
*/
public class GPRSHandler extends Thread {
private String data;
private String url;
private String msgKey;
private String mobileNumber;
public String sendGPRSRequest() {
HttpConnection httpConn = null;
DataOutputStream oStrm = null;
DataInputStream is = null;
byte[] resp = null;
String responseData;
try {
// Creating httpconnection object to handle GPRS request
httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Confirguration/CLDC-1.0");
httpConn.setRequestProperty("Accept_Language", "en-US");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
oStrm = httpConn.openDataOutputStream();
byte dataArray[] = (mobileNumber + "&" + msgKey + data).getBytes();
// byte dataArray[] = (msgKey + data).getBytes();
CommonMethods.getSystemOutput("msg key and data:::"+mobileNumber + msgKey + data);
for (int i = 0; i < dataArray.length; i++) {
oStrm.writeByte(dataArray[i]);
}
DataInputStream din = httpConn.openDataInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch;
while ((ch = din.read()) != -1) {
baos.write(ch);
}
resp = baos.toByteArray();
responseData = new String(resp);
baos.close();
din.close();
httpConn.close();
return responseData.trim();
} catch (IOException ex) {
CommonMethods.getSystemOutput("IO Exception in run method of gprs handler::" + ex.getMessage());
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
int choice = Dialog.ask(Dialog.D_OK, "No Connectivity");
exitApp(choice);
}
});
} catch (NullPointerException nex) {
CommonMethods.getSystemOutput("NullPointerException:" + nex.getMessage());
} catch (SecurityException e) {
CommonMethods.getSystemOutput("SecurityException:" + e.getMessage());
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.ask(Dialog.OK, "Security Exception");
UiApplication.getUiApplication().pushScreen(new MenuScreen());
}
});
} finally {
try {
if (is != null) {
is.close();
}
if (oStrm != null) {
oStrm.close();
}
if (httpConn != null) {
httpConn.close();
}
} catch (Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.ask(Dialog.OK, "ERROR in While Connecting GPRS Connection");
UiApplication.getUiApplication().pushScreen(new MenuScreen());
}
});
}
}
return null;
}
public void setData(String data) {
this.data = data;
}
public void setMsgKey(String msgKey) {
this.msgKey = msgKey;
}
public void setUrl(String url) {
this.url = url + ";deviceside=false";
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
private void exitApp(int choice) {
System.exit(0);
}
}

httpConn = (HttpConnection) Connector.open(url);
instead of this you can write//
url = url + ";deviceside=false";
httpConn = (HttpConnection) Connector.open(url);

Please add network extension in this line
httpConn = (HttpConnection) Connector.open(url);
at the end of the url please check did you add url extension
for suppose you are using wifi then you have to add
httpConn = (HttpConnection) Connector.open(url+";interface=wifi");
this is working for interface if you want to other types of networks then just refer my answer here
"Tunnel Failed" exception in BlackBerry Curve 8520

Related

Blackberry java show recieved push message

After referring tons of tutorials finally somehow I managed to develop java push client for Blackberry OS 7.0 (registering in RIM and server side are completely ok, this is the server script). Now the program running on the device and when new push massage revived there is a little arrow blinking on right up corner of the device, but I haven't that much knowledge to show that message in a label field or any other UI component. Please tell me how to show the revived push message in a screen. I'm beginner in programming so I haven't that much of knowledge need your help. Here I post all the codes that I have used.
Here is the application class
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
/**
* This class extends the UiApplication class, providing a
* graphical user interface.
*/
public class MyApp extends UiApplication
{
public static void main(String[] args)
{
//every time we start the application we register to BIS for push
if (args.length > 0 && args[0].equals("BlackBerryCity")) {
System.out.println("!!!!!!!!!!!!!!I am inside if");
//registering for push
Push_main.registerBpas();
MyApp app = new MyApp();
app.enterEventDispatcher();
}
//every time we restart the phone , we call this background process that is responsible for listening for push
else {
System.out.println("!!!!!!!!!!!!!!I am inside else");
//should put the background classes for listening to pushed msgs :D
BackgroundApplication backApp=new BackgroundApplication();
backApp.setupBackgroundApplication();
backApp.enterEventDispatcher();
}
}
public MyApp(){
pushScreen(new MyAppScreen());
}
}
class MyAppScreen extends MainScreen
{
public MyAppScreen()
{
// What to add here no idea :(
}
}
Push_main class
public class Push_main {
private static final String REGISTER_SUCCESSFUL = "rc=200";
private static final String DEREGISTER_SUCCESSFUL = REGISTER_SUCCESSFUL;
private static final String USER_ALREADY_SUBSCRIBED = "rc=10003";
private static final String ALREADY_UNSUSCRIBED_BY_USER = "rc=10004";
private static final String ALREADY_UNSUSCRIBED_BY_PROVIDER = "rc=10005";
private static final String PUSH_PORT = ""+"XXXXXX"; //push port
private static final String BPAS_URL = "http://cpXXXX.pushapi.eval.blackberry.com";
private static final String APP_ID = ""+ "XXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXX"; // add application id
private static String URL = "http://:"+ "XXXXXX"; // add your push port.
private static final int CHUNK_SIZE = 256;
public static ListeningThread _listeningThread;
public static StreamConnectionNotifier _notify;
private static final long ID = 0x954a603c0dee81e0L;
public Push_main(){
if(_listeningThread==null)
{
System.out.println("msg on listening thread 1");
_listeningThread = new ListeningThread();
System.out.println("msg on listening thread 2");
_listeningThread.start();
System.out.println("msg on listhning thread 3 ");
}
}
public static class ListeningThread extends Thread
{
private boolean _stop = false;
/**
* Stops the thread from listening.
*/
private synchronized void stop()
{
_stop = true;
try
{
// Close the connection so the thread will return.
_notify.close();
}
catch (Exception e)
{
}
}
/**
* Listen for data from the HTTP url. After the data has been read,
* render the data onto the screen.
* #see java.lang.Runnable#run()
*/
public void run()
{
StreamConnection stream = null;
InputStream input = null;
MDSPushInputStream pushInputStream=null;
while (!_stop)
{
try
{
// Synchronize here so that we don't end up creating a connection that is never closed.
synchronized(this)
{
// Open the connection once (or re-open after an IOException), so we don't end up
// in a race condition, where a push is lost if it comes in before the connection
// is open again. We open the url with a parameter that indicates that we should
// always use MDS when attempting to connect.
System.out.println("\n\n msg connection 1");
_notify = (StreamConnectionNotifier)Connector.open(URL);
System.out.println("\n\n msg connection 2");
}
while (!_stop)
{
// NOTE: the following will block until data is received.
System.out.println("\n\n msg notify 1");
stream = _notify.acceptAndOpen();
System.out.println("\n\n msg 1 ");
try
{
System.out.println("\n\n msg 2");
input = stream.openInputStream();
System.out.println("\n\n msg 3 ");
pushInputStream= new MDSPushInputStream((HttpServerConnection)stream, input);
System.out.println("\n\n msg 4");
// Extract the data from the input stream.
DataBuffer db = new DataBuffer();
byte[] data = new byte[CHUNK_SIZE];
int chunk = 0;
while ( -1 != (chunk = input.read(data)) )
{
db.write(data, 0, chunk);
}
updateMessage(data);
// This method is called to accept the push.
pushInputStream.accept();
data = db.getArray();
}
catch (IOException e1)
{
// A problem occurred with the input stream , however, the original
// StreamConnectionNotifier is still valid.
// errorDialog(e1.toString());
}
finally
{
if ( input != null )
{
try
{
input.close();
}
catch (IOException e2)
{
}
}
if ( stream != null )
{
try
{
stream.close();
}
catch (IOException e2)
{
}
}
}
}
}
catch (IOException ioe)
{
// Likely the stream was closed. Catches the exception thrown by
// _notify.acceptAndOpen() when this program exits.
errorDialog(ioe.toString());
}
finally
{
/*
if ( _notify != null )
{
try
{
_notify.close();
_notify = null;
}
catch ( IOException e )
{
}
}
*/
}
}
}
}
private static void updateMessage(final byte[] data)
{
System.out.println("\n\n msg 6");
Application.getApplication().invokeLater(new Runnable()
{
public void run()
{
// Query the user to load the received message.
// Dialog.alert( new String(data));
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run()
{
NotificationsManager.triggerImmediateEvent(ID, 0, null, null);
Dialog d = new Dialog( Dialog.D_OK, new String(data) ,0, null, Screen.DEFAULT_CLOSE);
// _dialogShowing = true;
UiApplication.getUiApplication().pushGlobalScreen( d, 10, UiApplication.GLOBAL_MODAL );
// Dialog is closed at this point, so we cancel the event.
}
} );
}
});
}
public static void registerBpas() {
/**
* As the connection suffix is fixed I just use a Thread to call the connection code
*
**/
new Thread() {
public void run() {
try {
String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null) + ";deviceside=false;ConnectionType=mds-public";
//Dialog.alert(registerUrl);
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo
.areWAFsSupported(RadioInfo.WAF_WLAN)) {
registerUrl += ";interface=wifi";
}
System.out.println("\n\n\n !!msg registerBPAS URL is: "+ registerUrl + "\n\n");
HttpConnection httpConnection = (HttpConnection) Connector.open(registerUrl);
InputStream is = httpConnection.openInputStream();
System.out.println("\n\n\n !!!!!!!!!!!I am here ");
String response = new String(IOUtilities.streamToBytes(is));
System.out.println("\n\n\n\n\n\n msg RESPOSE CODE : " + response);
System.out.println("\n\n\n !!!!!!!!!!!I am here2 ");
httpConnection.close();
String nextUrl = formRegisterRequest(BPAS_URL, APP_ID, response) + ";deviceside=false;ConnectionType=mds-public";
System.out.println("\n\n\n\n\n\n msg nextUrl : " + nextUrl);
System.out.println("\n\n\n !!!!!!!!!!!I am here 3");
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo
.areWAFsSupported(RadioInfo.WAF_WLAN)) {
nextUrl += ";interface=wifi";
System.out.println("\n\n\n !!!!!!!!!!!I am here 4");
}
HttpConnection nextHttpConnection = (HttpConnection) Connector.open(nextUrl);
InputStream nextInputStream = nextHttpConnection.openInputStream();
response = new String(IOUtilities.streamToBytes(nextInputStream));
System.out.println("\n\n\n !!!!!!!!!!!I am here 5");
System.out.println("\n\n\n\n\n\n msg RESPOSE CODE 1: " + response);
nextHttpConnection.close();
if (REGISTER_SUCCESSFUL.equals(response) || USER_ALREADY_SUBSCRIBED.equals(response)) {
Dialog.alert("msg Registered successfully for BIS push");
System.out.println("\n\n\n !!!!!!!!!!!I am here 6");
System.out.println("msg Registered successfully for BIS push");
} else {
Dialog.alert("msg BPAS rejected registration");
System.out.println("msg BPAS rejected registration");
}
} catch (final IOException e) {
Dialog.alert("msg IOException on register() " + e + " " + e.getMessage());
System.out.println("msg IOException on register() " + e + " " + e.getMessage());
}
}
}.start();
}
public static void close(Connection conn, InputStream is, OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
public static void errorDialog(final String message)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(message);
}
});
}
private static String formRegisterRequest(String bpasUrl, String appId, String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subReg?");
sb.append("serviceid=").append(appId);
sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
sb.append("&model=").append(DeviceInfo.getDeviceName());
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}
}
Push Message Reader
public final class PushMessageReader {
//added by me
static String msgId;
// HTTP header property that carries unique push message ID
private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
// content type constant for text messages
private static final String MESSAGE_TYPE_TEXT = "text";
// content type constant for image messages
private static final String MESSAGE_TYPE_IMAGE = "image";
private static final int MESSAGE_ID_HISTORY_LENGTH = 10;
private static String[] messageIdHistory = new String[MESSAGE_ID_HISTORY_LENGTH];
private static byte historyIndex;
private static byte[] buffer = new byte[15 * 1024];
private static byte[] imageBuffer = new byte[10 * 1024];
/**
* Utility classes should have a private constructor.
*/
public PushMessageReader() {
}
/**
* Reads the incoming push message from the given streams in the current thread and notifies controller to display the information.
*
* #param pis
* the pis
* #param conn
* the conn
*/
public static void process(PushInputStream pis, Connection conn) {
System.out.println("Reading incoming push message ...");
try {
HttpServerConnection httpConn;
if (conn instanceof HttpServerConnection) {
httpConn = (HttpServerConnection) conn;
} else {
throw new IllegalArgumentException("Can not process non-http pushes, expected HttpServerConnection but have "
+ conn.getClass().getName());
}
//changed here
msgId = httpConn.getHeaderField(MESSAGE_ID_HEADER);
String msgType = httpConn.getType();
String encoding = httpConn.getEncoding();
System.out.println("Message props: ID=" + msgId + ", Type=" + msgType + ", Encoding=" + encoding);
boolean accept = true;
if (!alreadyReceived(msgId)) {
byte[] binaryData;
if (msgId == null) {
msgId = String.valueOf(System.currentTimeMillis());
}
if (msgType == null) {
System.out.println("Message content type is NULL");
accept = false;
} else if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
// a string
int size = pis.read(buffer);
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
// TODO report message
} else if (msgType.indexOf(MESSAGE_TYPE_IMAGE) >= 0) {
// an image in binary or Base64 encoding
int size = pis.read(buffer);
if (encoding != null && encoding.equalsIgnoreCase("base64")) {
// image is in Base64 encoding, decode it
Base64InputStream bis = new Base64InputStream(new ByteArrayInputStream(buffer, 0, size));
size = bis.read(imageBuffer);
}
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
// TODO report message
} else {
System.out.println("Unknown message type " + msgType);
accept = false;
}
} else {
System.out.println("Received duplicate message with ID " + msgId);
}
pis.accept();
} catch (Exception e) {
System.out.println("Failed to process push message: " + e);
} finally {
Push_main.close(conn, pis, null);
}
}
/**
* Check whether the message with this ID has been already received.
*
* #param id
* the id
* #return true, if successful
*/
private static boolean alreadyReceived(String id) {
if (id == null) {
return false;
}
if (Arrays.contains(messageIdHistory, id)) {
return true;
}
// new ID, append to the history (oldest element will be eliminated)
messageIdHistory[historyIndex++] = id;
if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
historyIndex = 0;
}
return false;
}
}
BackGroundApplication
public class BackgroundApplication extends Application {
public BackgroundApplication() {
// TODO Auto-generated constructor stub
}
public void setupBackgroundApplication(){
MessageReadingThread messageReadingThread = new MessageReadingThread();
messageReadingThread.start();
}
private static class MessageReadingThread extends Thread {
private boolean running;
private ServerSocketConnection socket;
private HttpServerConnection conn;
private InputStream inputStream;
private PushInputStream pushInputStream;
public MessageReadingThread() {
this.running = true;
}
public void run() {
String url = "http://:" + "XXXXXX" ;//here after the + add your port number
url += ";deviceside=true;ConnectionType=mds-public";
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) && RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
url += ";interface=wifi";
}
try {
socket = (ServerSocketConnection) Connector.open( url );
} catch( IOException ex ) {
// can't open the port, probably taken by another application
onListenError( ex );
}
while( running ) {
try {
Object o = socket.acceptAndOpen();
conn = (HttpServerConnection) o;
inputStream = conn.openInputStream();
pushInputStream = new MDSPushInputStream( conn, inputStream );
PushMessageReader.process( pushInputStream, conn );
} catch( Exception e ) {
if( running ) {
// Logger.warn( "Failed to read push message, caused by " + e.getMessage() );
running = false;
}
} finally {
// PushUtils.close( conn, pushInputStream, null );
}
}
// Logger.log( "Stopped listening for push messages" );
}
public void stopRunning() {
running = false;
//PushUtils.close( socket, null, null );
}
private void onListenError( final Exception ex ) {
// Logger.warn( "Failed to open port, caused by " + ex );
System.out.println(ex);
}
}
}
What I have to add for the main screen to show in coming message ??
Thank you in advance.

issue with parsing JSON Data in Blackberry

I am new in BB trying to parse Json file and just want to print the Json responce in a Dialog. But it raises an error regarding No Application Instance and is also getting IllegalStateException. I use GET url method for it.
I Have also add permission in UiApplication like ..
UIApplicationScreen
public static void main(String[] args) {
ApplicationPermissions permRequest = ApplicationPermissionsManager.getInstance().getApplicationPermissions();
permRequest = new ApplicationPermissions();
permRequest.addPermission( ApplicationPermissions.PERMISSION_INTERNET );
ApplicationPermissionsManager.getInstance().invokePermissionsRequest( permRequest );
UiFunApplication app = new UiFunApplication();
app.enterEventDispatcher();
Here is MainScreen Code....
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONArray;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONObject;
public class UiMainscreen extends MainScreen {
public UiMainscreen() {
Dialog.alert("asdasd");
HttpConnection conn = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try {
// String url = "http://api.twitter.com/1/users/show.json?screen_name=Kaka";
String url = "http://docs.blackberry.com/sampledata.json";
conn = (HttpConnection) Connector.open(url, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
int code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer);
}
out.flush();
String response = new String(out.toByteArray());
Dialog.alert("response is ::"+response);
} catch (Exception e) {
Dialog.alert(e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
}
}
}
Update::
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONArray;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONObject;
public class UiMainscreen extends MainScreen implements FieldChangeListener {
public UiMainscreen() {
ButtonField loginButton;
loginButton = new ButtonField("Go", ButtonField.CONSUME_CLICK);
loginButton.setChangeListener(this);
add(loginButton);
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if (field instanceof ButtonField) {
Dialog.alert("Message");
HttpConnection conn = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try {
// String url =
// "http://api.twitter.com/1/users/show.json?screen_name=Kaka";
String url = "http://docs.blackberry.com/sampledata.json";
conn = (HttpConnection) Connector.open(url, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
int code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer);
}
out.flush();
String response = new String(out.toByteArray());
Dialog.alert("response is ::" + response);
/*
* JSONObject resObject = new JSONObject(response); String
* key = resObject.getString("vehicleType");
*
* Vector resultsVector = new Vector(); JSONArray jsonArray
* = resObject.getJSONArray("name"); if (jsonArray.length()
* > 0) { for (int i = 0; i < jsonArray.length();i++) {
* Vector elementsVector = new Vector(); JSONObject jsonObj
* = jsonArray.getJSONObject(i);
* elementsVector.addElement(jsonObj
* .getString("experiencePoints"));
* elementsVector.addElement
* (jsonObj.getString("Insert Json Array Element Key2"));
* resultsVector.addElement(elementsVector); } }
*/
}
} catch (Exception e) {
Dialog.alert(e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
}
}
}
}
Try this code -
final ButtonField b=new ButtonField("JSON");
add(b);
FieldChangeListener listener=new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(field==b){
try {
String httpURL = "http://docs.blackberry.com/sampledata.json";
HttpConnection httpConn;
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
String responce = res.trim();
Dialog.alert(responce);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
b.setChangeListener(listener);

Blackberry Push Integration Client Sample Code

I need a sample application code for push integration in my blackberry application. I have registered my application for the push credentials and have received them.
please help,
Kind Regards,
Rupesh
This is fully working push application code it may be help you for implement push notification.
public class push_Main {
/**
* Entry point for this application
* #param args Command line arguments (not used)
*/
private static final String REGISTER_SUCCESSFUL = "rc=200";
private static final String DEREGISTER_SUCCESSFUL = REGISTER_SUCCESSFUL;
private static final String USER_ALREADY_SUBSCRIBED = "rc=10003";
private static final String ALREADY_UNSUSCRIBED_BY_USER = "rc=10004";
private static final String ALREADY_UNSUSCRIBED_BY_PROVIDER = "rc=10005";
private static final String PUSH_PORT = ""; //push port
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = ""; // add application id
// private static final String CONNECTION_SUFFIX = ";deviceside=false;ConnectionType=seekrit string";
private static String URL = "http://:100"; // PORT 100 add your posh port.
private static final int CHUNK_SIZE = 256;
public static ListeningThread _listeningThread;
public static StreamConnectionNotifier _notify;
private static final long ID = 0x954a603c0dee81e0L;
public push_Main() {
// TODO Auto-generated constructor stub
NotificationsManager.registerSource(ID, theSource, NotificationsConstants.IMPORTANT);
if(_listeningThread==null)
{
System.out.println("msg on listening thread 1");
_listeningThread = new ListeningThread();
System.out.println("msg on listening thread 2");
_listeningThread.start();
System.out.println("msg on listhning thread 3 ");
}
}
public static class ListeningThread extends Thread
{
private boolean _stop = false;
/**
* Stops the thread from listening.
*/
private synchronized void stop()
{
_stop = true;
try
{
// Close the connection so the thread will return.
_notify.close();
}
catch (Exception e)
{
}
}
/**
* Listen for data from the HTTP url. After the data has been read,
* render the data onto the screen.
* #see java.lang.Runnable#run()
*/
public void run()
{
StreamConnection stream = null;
InputStream input = null;
MDSPushInputStream pushInputStream=null;
while (!_stop)
{
try
{
// Synchronize here so that we don't end up creating a connection that is never closed.
synchronized(this)
{
// Open the connection once (or re-open after an IOException), so we don't end up
// in a race condition, where a push is lost if it comes in before the connection
// is open again. We open the url with a parameter that indicates that we should
// always use MDS when attempting to connect.
System.out.println("\n\n msg connection 1");
_notify = (StreamConnectionNotifier)Connector.open(URL);
System.out.println("\n\n msg connection 2");
}
while (!_stop)
{
// NOTE: the following will block until data is received.
System.out.println("\n\n msg notify 1");
stream = _notify.acceptAndOpen();
System.out.println("\n\n msg 1 ");
try
{
System.out.println("\n\n msg 2");
input = stream.openInputStream();
System.out.println("\n\n msg 3 ");
pushInputStream= new MDSPushInputStream((HttpServerConnection)stream, input);
System.out.println("\n\n msg 4");
// Extract the data from the input stream.
DataBuffer db = new DataBuffer();
byte[] data = new byte[CHUNK_SIZE];
int chunk = 0;
while ( -1 != (chunk = input.read(data)) )
{
db.write(data, 0, chunk);
}
updateMessage(data);
// This method is called to accept the push.
pushInputStream.accept();
data = db.getArray();
}
catch (IOException e1)
{
// A problem occurred with the input stream , however, the original
// StreamConnectionNotifier is still valid.
// errorDialog(e1.toString());
}
finally
{
if ( input != null )
{
try
{
input.close();
}
catch (IOException e2)
{
}
}
if ( stream != null )
{
try
{
stream.close();
}
catch (IOException e2)
{
}
}
}
}
}
catch (IOException ioe)
{
// Likely the stream was closed. Catches the exception thrown by
// _notify.acceptAndOpen() when this program exits.
errorDialog(ioe.toString());
}
finally
{
/*
if ( _notify != null )
{
try
{
_notify.close();
_notify = null;
}
catch ( IOException e )
{
}
}
*/
}
}
}
}
private static void updateMessage(final byte[] data)
{
System.out.println("\n\n msg 6");
Application.getApplication().invokeLater(new Runnable()
{
public void run()
{
// Query the user to load the received message.
// Dialog.alert( new String(data));
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run()
{
NotificationsManager.triggerImmediateEvent(ID, 0, null, null);
Dialog d = new Dialog( Dialog.D_OK, new String(data) ,0, null, Screen.DEFAULT_CLOSE);
// _dialogShowing = true;
UiApplication.getUiApplication().pushGlobalScreen( d, 10, UiApplication.GLOBAL_MODAL );
// Dialog is closed at this point, so we cancel the event.
}
} );
}
});
}
public static void registerBpas() {
/**
* As the connection suffix is fixed I just use a Thread to call the connection code
*
**/
new Thread() {
public void run() {
try {
final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null) + Conn.getConnectionParameters();
System.out.println("\n\n\n msg registerBPAS URL is: "+ registerUrl);
HttpConnection httpConnection = (HttpConnection) Connector.open(registerUrl);
InputStream is = httpConnection.openInputStream();
String response = new String(IOUtilities.streamToBytes(is));
System.out.println("\n\n\n\n\n\n msg RESPOSE CODE : " + response);
close(httpConnection, is, null);
String nextUrl = formRegisterRequest(BPAS_URL, APP_ID, response) + Conn.getConnectionParameters();
System.out.println("\n\n\n\n\n\n msg nextUrl : " + nextUrl);
HttpConnection nextHttpConnection = (HttpConnection) Connector.open(nextUrl);
InputStream nextInputStream = nextHttpConnection.openInputStream();
response = new String(IOUtilities.streamToBytes(nextInputStream));
System.out.println("\n\n\n\n\n\n msg RESPOSE CODE 1: " + response);
close(nextHttpConnection, is, null);
if (REGISTER_SUCCESSFUL.equals(response) || USER_ALREADY_SUBSCRIBED.equals(response)) {
System.out.println("msg Registered successfully for BIS push");
} else {
System.out.println("msg BPAS rejected registration");
}
} catch (final IOException e) {
System.out.println("msg IOException on register() " + e + " " + e.getMessage());
}
}
}.start();
}
public static void close(Connection conn, InputStream is, OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
public static void errorDialog(final String message)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(message);
}
});
}
private static String formRegisterRequest(String bpasUrl, String appId, String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subReg?");
sb.append("serviceid=").append(appId);
sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
sb.append("&model=").append(DeviceInfo.getDeviceName());
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}
}

Json parsing in Blackberry 5.0

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

blackberry GET request with Java Me

i am trying to get data sending GET request to a php service, but unfortunately i am not getting any result, i am using Blackberry Simulator 9800, here is my code,
HttpConnection conn = null;
InputStream in = null;
StringBuffer buff = new StringBuffer();
String result = "";
String url = "http://www.devbrats.com/testing/ActorRated/Service/cities.php";
try{
conn = (HttpConnection) Connector.open(url,Connector.READ_WRITE, true);
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if(conn.getResponseCode() == HttpConnection.HTTP_OK){
in = conn.openInputStream();
//parser.parse(in, handler);
buff.append(IOUtilities.streamToBytes(in));
result = buff.toString();
}
else{
result = "Error in connection";
}
} catch(Exception ex){
ex.printStackTrace();
} finally{
try {
if(in != null){
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Please tell me what is the problem with it,
You will have to use this : http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/io/transport/ConnectionFactory.html
To properly create a network connection with the right parameter.
If you are not using OS5+ use this : http://www.versatilemonkey.com/HttpConnectionFactory.java
package mypackage;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen {
private LabelField lbl;
/**
* Creates a new MyScreen object
*/
public MyScreen() {
setTitle("MyTitle");
new Thread(new ConnectThread(this)).start();
lbl = new LabelField();
this.add(lbl);
}
public void update(Object object) {
synchronized (UiApplication.getEventLock()){
lbl.setText((String)object);
}
}
private class ConnectThread implements Runnable {
private MainScreen screen;
public ConnectThread(MainScreen screen) {
this.screen = screen;
}
public void run() {
HttpConnection conn = null;
InputStream in = null;
StringBuffer buff = new StringBuffer();
String result = "";
String url = "http://www.devbrats.com/testing/ActorRated/Service/cities.php";
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
buff.append(IOUtilities.streamToBytes(in));
result = buff.toString();
} else {
result = "Error in connection" + conn.getResponseCode();
}
((MyScreen)screen).update(result);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Resources