Getting started with blackberry 7 development? - blackberry

Can someone please point me to the right direction on learning how to develop for blackberry 7?
Actually what i need is just to implement push notifications and open a web URL nothing more.
I see that there are different frameworks for this platform like webWorks etc etc.
I am a bit confused though.. I do not want to write Javascript or HTML or CSS.
I want to write native code that enables push and loads me an external URL which i already have.
Any tutorial on that or a bit of info would be great :)

Try this -
Client side code -
// Main Class-
class App extends UiApplication {
private static App theApp;
public App() {
pushScreen(new register());
}
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("BB_push") ){
theApp = new App();
theApp.enterEventDispatcher();
}
else {
BackgroundApplication backApp=new BackgroundApplication();
backApp.setupBackgroundApplication();
backApp.enterEventDispatcher();
}
}
}
//Register Class-
public class register extends MainScreen{
public register(){
final ButtonField btn=new ButtonField("Register");
add(btn);
FieldChangeListener listener=new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(field==btn){
registerBpas();
}
}};
btn.setChangeListener(listener);
}
}
public static void registerBpas() {
new Thread() {
public void run() {
try {
final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null) + ";deviceside=false;ConnectionType=mds-public";
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);
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);
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);
nextHttpConnection.close();
if (REGISTER_SUCCESSFUL.equals(response) || USER_ALREADY_SUBSCRIBED.equals(response)) {
Dialog.alert("msg Registered successfully for BIS push");
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();
}
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();
}
}
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) {
}
}
}
//Background listener class
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://:" + Port;
url += ";deviceside=false;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);
}
}
}
//push message reader class -
// 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";
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];
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());
}
String 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);
PushMessage message = new PushMessage(msgId, System.currentTimeMillis(), binaryData, true, true );
String text = new String( message.getData(), "UTF-8" );
try{
final Dialog screen = new Dialog(Dialog.D_OK_CANCEL, " "+text,
Dialog.OK,
//mImageGreen.getBitmap(),
null, Manager.VERTICAL_SCROLL);
final UiEngine ui = Ui.getUiEngine();
Application.getApplication().invokeAndWait(new Runnable() {
public void run() {
NotificationsManager.triggerImmediateEvent(0x749cb23a76c66e2dL, 0, null, null);
ui.pushGlobalScreen(screen, 0, UiEngine.GLOBAL_QUEUE);
}
});
screen.setDialogClosedListener(new MyDialogClosedListener());
}
catch (Exception e) {
// TODO: handle exception
}
// 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);
}
}
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;
}
public class PushMessage{
private String id;
private long timestamp;
private byte[] data;
private boolean textMesasge;
private boolean unread;
public PushMessage( String id, long timestamp, byte[] data, boolean textMesasge, boolean unread ) {
super();
this.id = id;
this.timestamp = timestamp;
this.data = data;
this.textMesasge = textMesasge;
this.unread = unread;
}
public String getId() {
return id;
}
public long getTimestamp() {
return timestamp;
}
public byte[] getData() {
return data;
}
public boolean isTextMesasge() {
return textMesasge;
}
public boolean isUnread() {
return unread;
}
public void setUnread( boolean unread ) {
this.unread = unread;
}
}
public class MyDialogClosedListener implements DialogClosedListener
{
public void dialogClosed(Dialog dialog, int choice)
{
if(dialog.equals(dialog))
{
if(choice == -1)
{
//Your code for Press OK
}
if(choice == 1)
{
//Your code for Press Cancel
}
}
}
}
Server sode PHP code is given Below -
ini_set('display_errors','1');
error_reporting(E_ALL);
// APP ID provided by RIM
$appid = 'app id';
// Password provided by RIM
$password = 'password';
//Deliver before timestamp
$deliverbefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+time minutes'));
//An array of address must be in PIN format or "push_all"
$addresstosendto[] = 'your pin';
$addresses = '';
foreach ($addresstosendto as $value) {
$addresses .= '
';
}
// create a new cURL resource
$err = false;
$ch = curl_init();
$messageid = microtime(true);
$data = '--mPsbVQo0a68eIL3OAxnm'. "\r\n" .
'Content-Type: application/xml; charset=UTF-8' . "\r\n\r\n" .
'
'
. $addresses .
'
' . "\r\n" .
'--mPsbVQo0a68eIL3OAxnm' . "\r\n" .
'Content-Type: text/plain' . "\r\n" .
'Push-Message-ID: ' . $messageid . "\r\n\r\n" .
stripslashes('r') . "\r\n" .
'--mPsbVQo0a68eIL3OAxnm--' . "\n\r";
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://pushapi.eval.blackberry.com/mss/PD_pushRequest");//"https://cp2991.pushapi.eval.blackberry.com/mss/PD_pushRequest"
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT, "Hallgren Networks BB Push Server/1.0");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $appid . ':' . $password);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/related; boundary=mPsbVQo0a68eIL3OAxnm; type=application/xml", "Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", "Connection: keep-alive"));
// grab URL and pass it to the browser
echo $xmldata = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
//Start parsing response into XML data that we can read and output
$p = xml_parser_create();
xml_parse_into_struct($p, $xmldata, $vals);
$errorcode = xml_get_error_code($p);
if ($errorcode > 0) {
echo xml_error_string($errorcode);
$err = true;
}
xml_parser_free($p);
echo 'Our PUSH-ID: ' . $messageid . "
\n";
if (!$err && $vals[1]['tag'] == 'PUSH-RESPONSE') {
echo 'PUSH-ID: ' . $vals[1]['attributes']['PUSH-ID'] . "
\n";
echo 'REPLY-TIME: ' . $vals[1]['attributes']['REPLY-TIME'] . "
\n";
echo 'Response CODE: ' . $vals[2]['attributes']['CODE'] . "
\n";
echo 'Response DESC: ' . $vals[2]['attributes']['DESC'] . "
\n";
} else {
echo 'An error has occured
' . "\n";
echo 'Error CODE: ' . $vals[1]['attributes']['CODE'] . "
\n";
echo 'Error DESC: ' . $vals[1]['attributes']['DESC'] . "
\n";
}
?>

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.

BlackBerry Push Notifications , OS < 7.X

I am working on developing a BB OS<7.X application, that implements push notifications. I finally ended up with some working code that is able to receive push.
However, the push notifications DONT work the first time i deploy the application on the phone. If i try to send a push on the device, after i just deployed it, when i send the push from my server, i can see on the right up corner of my device a little arrow loading , but no push message is displayed on the screen.
If i restart the device, the push notifications work properly!! Now whenever i send a push, i see the little arrow again on up right screen and the push message displayed corrected.
The code looks like this(the parts i consider important):
MyApp.java
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()
{
//some stuff here..
}
}
push_main.java
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 = ""+"33387"; //push port
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = ""+ "3592-M4587f9s9k836r930kO2395i32i66y10a34"; // add application id
private static String URL = "http://:"+ "33397"; // 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();
}
}
BackGroundApplication.java
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import net.rim.device.api.io.http.HttpServerConnection;
import net.rim.device.api.io.http.MDSPushInputStream;
import net.rim.device.api.io.http.PushInputStream;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.system.WLANInfo;
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://:" + "33387" ;//here after the + add your port number
url += ";deviceside=false;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);
}
}
On the main class , MyApp.java , as you can see everytime the application is launched, i register for push. Every time the device restarts, i start a background process to listen for push. Or at least, this is what i believe i am doing here.
Why should i do that?
I thought that by registering for push, the background listener would somehow start too... But i guess it doesn't.. That's why probably when i restart the phone, this code is executed and the push starts coming in.
How could i fix this problem so that i could start the background listener:
the first time the app is deployed
every time i restart the device
but NOT on every launch of the app.

BlackBerry - Dialog.cancel() on the login page

I have a login page that accepts username & password. When the user clicks "Login" a loading screen "Signing in.." is shown with the background thread calling a doLogin() method that calls a web service and load the appropriate page.
The problem I am facing is to "Cancel" signing in from Dialog.cancel() after login has been clicked. It cancels the loading screen but the background thread is still processing and even after clicking "cancel", the new page is loaded. How can I cancel the background thread?
Thread backgroundWorker = new Thread(new Runnable() {
public void run() {
doLogin(uname, pwd);
}
});
Dialog busyDialog = new Dialog("Signing in...",
new String [] { "Cancel" },
new int [] { Dialog.CANCEL},
Dialog.CANCEL,
Bitmap.getPredefinedBitmap(Bitmap.HOURGLASS))
{
public void fieldChanged(Field field1, int context1)
{
//Something to stop the login and close the loading screen
}
};
busyDialog.setEscapeEnabled(false);
busyDialog.show();
backgroundWorker.start();
And the method which it is calling that pushes the new screen is doLogin():
private String doLogin(String user_id, String password)
{
SoapObject resultRequestSOAP = null;
HttpConnection httpConn = null;
HttpTransport httpt;
SoapPrimitive response = null;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("username", user_id);
request.addProperty("password", password);
System.out.println("The request is=======" + request.toString());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
httpt = new HttpTransport(URL+C0NNECTION_EXTENSION);
httpt.debug = true;
try
{
httpt.call(SOAP_ACTION, envelope);
response = (SoapPrimitive) envelope.getResponse();
String result = response.toString();
resultRequestSOAP = (SoapObject) envelope.bodyIn;
String[] listResult = split(result, sep);
strResult = listResult[0].toString();
if(strResult.equals("credentialdenied"))
{
Dialog.alert("Invalid login details.");
}
else
{
strsessionFirstName = listResult[1].toString();
strsessionLastName = listResult[2].toString();
strsessionPictureUrl = MAINURL + listResult[3].substring(2);
strsessionStatusId = listResult[4].toString();
strsessionStatusMessage = listResult[5].toString();
strsessionLastUpdateTst = listResult[6].toString();
}
if(strResult.equals("credentialaccepted"))
{
if(checkBox1.getChecked() == true)
{
persistentHashtable.put("username", user_id);
persistentHashtable.put("password", password);
}
Bitmap bitmap = getLiveImage(strsessionPictureUrl, 140, 140);
nextScreen.getUsername(user_id);
nextScreen.getPassword(password);
nextScreen.setPictureUrl(bitmap);
nextScreen.setImage(strsessionPictureUrl);
nextScreen.setFirstName(strsessionFirstName, strsessionLastName, strsessionLastUpdateTst, strsessionStatusMessage);
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen(nextScreen);
}
} );
}
} catch (IOException e) {
System.out.println("The exception is IO==" + e.getMessage());
} catch (XmlPullParserException e) {
System.out.println("The exception xml parser example==="
+ e.getMessage());
}
System.out.println( resultRequestSOAP);
return response + "";
}
You might need to add a boolean member variable to your class, that you check at multiple steps, within your doLogin() method:
private boolean stopRequested = false;
private synchronized void requestStop() {
stopRequested = true;
}
private synchronized boolean isStopRequested() {
return stopRequested;
}
private String doLogin(String user_id, String password)
{
SoapObject resultRequestSOAP = null;
HttpConnection httpConn = null;
HttpTransport httpt;
SoapPrimitive response = null;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("username", user_id);
request.addProperty("password", password);
System.out.println("The request is=======" + request.toString());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
httpt = new HttpTransport(URL+C0NNECTION_EXTENSION);
httpt.debug = true;
if (isStopRequested()) return null;
try
{
httpt.call(SOAP_ACTION, envelope);
response = (SoapPrimitive) envelope.getResponse();
String result = response.toString();
resultRequestSOAP = (SoapObject) envelope.bodyIn;
String[] listResult = split(result, sep);
strResult = listResult[0].toString();
if(strResult.equals("credentialdenied"))
{
Dialog.alert("Invalid login details.");
}
else
{
strsessionFirstName = listResult[1].toString();
strsessionLastName = listResult[2].toString();
strsessionPictureUrl = MAINURL + listResult[3].substring(2);
strsessionStatusId = listResult[4].toString();
strsessionStatusMessage = listResult[5].toString();
strsessionLastUpdateTst = listResult[6].toString();
}
if (isStopRequested()) return null;
if(strResult.equals("credentialaccepted"))
{
if(checkBox1.getChecked() == true)
{
persistentHashtable.put("username", user_id);
persistentHashtable.put("password", password);
}
Bitmap bitmap = getLiveImage(strsessionPictureUrl, 140, 140);
nextScreen.getUsername(user_id);
nextScreen.getPassword(password);
nextScreen.setPictureUrl(bitmap);
nextScreen.setImage(strsessionPictureUrl);
nextScreen.setFirstName(strsessionFirstName, strsessionLastName, strsessionLastUpdateTst, strsessionStatusMessage);
if (isStopRequested()) return null;
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen(nextScreen);
}
} );
}
} catch (IOException e) {
System.out.println("The exception is IO==" + e.getMessage());
} catch (XmlPullParserException e) {
System.out.println("The exception xml parser example==="
+ e.getMessage());
}
System.out.println( resultRequestSOAP);
return response + "";
}
Then, stop the thread like this:
Dialog busyDialog = new Dialog("Signing in...",
new String [] { "Cancel" },
new int [] { Dialog.CANCEL},
Dialog.CANCEL,
Bitmap.getPredefinedBitmap(Bitmap.HOURGLASS))
{
public void fieldChanged(Field field1, int context1)
{
requestStop();
}
};

IMAP Response limited size

I am working on an email client that will connect to Gmail mailbox and retrieve a specific email.
Now i can connect to my mailbox and can retrieve part of the emails not all of it and no matter how large is my buffer still i get only 1400 char from my email and then Null for the rest of the mail body.
You can find a screen shot for the email body in this link
http://www.elzouhery.com/Mail%20Snapshot.png
Thanks in Advance
EDIT
See below the Full Code
static void Main(string[] args)
{
TcpIMAP imap = ConnectToEmail();
Console.WriteLine("Total Messages " + imap.MailCount());
Console.WriteLine("Total Unread Messages " + imap.MailUnreadCount());
Console.WriteLine("******************************************************");
imap.SelectInbox();
StreamWriter writer = null;
int mailCount = imap.MailCount();
var mailSize = string.Empty;
var content = string.Empty;
var subject = string.Empty;
for (int i = 1; i < mailCount; i++)
{
try
{
writer = new StreamWriter(#"c:\Mails\" + i + ".txt", true);
content = imap.GetMessage(i).ToString();
writer.Write(content);
writer.Close();
}
catch(Exception ex)
{
writer.Write(content);
Console.Write(ex.Message);
writer.Close();
}
}
}
private static TcpIMAP ConnectToEmail()
{
string host = "imap.gmail.com";
string username = "************";
string password = "************";
TcpIMAP imap = new TcpIMAP();
imap.Connect(host, 993);
imap.AuthenticateUser(username, password);
return imap;
}
public static string GetMailSubject(string Header)
{
var headerLines = Header.Split(Environment.NewLine.ToCharArray());
foreach (var line in headerLines)
{
if (line.IndexOf("Subject") > -1)
{
return line.Replace("Subject: ", "");
}
}
return "";
}
/***************************************************/
class TcpIMAP
{
private TcpClient _imapClient;
private Stream _imapNs;
private StreamWriter _imapSw;
private StreamReader _imapSr;
public TcpIMAP()
{
}
public TcpIMAP(string hostname, int port)
{
InitializeConnection(hostname, port);
}
public void Connect(string hostname, int port)
{
InitializeConnection(hostname, port);
}
private void InitializeConnection(string hostname, int port)
{
try
{
_imapClient = new TcpClient(hostname, port);
System.Net.Security.SslStream sslstream = new System.Net.Security.SslStream(_imapClient.GetStream());
sslstream.AuthenticateAsClient("imap.gmail.com");
_imapNs = sslstream;
_imapSw = new StreamWriter(_imapNs);
_imapSr = new StreamReader(_imapNs);
Console.WriteLine("*** Connected ***");
Response();
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
}
public void AuthenticateUser(string username, string password)
{
_imapSw.WriteLine("$ LOGIN " + username + " " + password);
_imapSw.Flush();
Response();
}
public int MailCount()
{
_imapSw.WriteLine("$ STATUS INBOX (messages)");
_imapSw.Flush();
string res = Response();
Match m = Regex.Match(res, "[0-9]*[0-9]");
return Convert.ToInt32(m.ToString());
}
public int MailUnreadCount()
{
_imapSw.WriteLine("$ STATUS INBOX (unseen)");
_imapSw.Flush();
string res = Response();
Match m = Regex.Match(res, "[0-9]*[0-9]");
return Convert.ToInt32(m.ToString());
}
public string SelectInbox()
{
_imapSw.WriteLine("$ SELECT INBOX");
_imapSw.Flush();
return Response();
}
public object GetMessageHeaders(int index)
{
_imapSw.WriteLine("$ FETCH " + index + " (body[header.fields (from subject date)])");
_imapSw.Flush();
return Response();
}
public object GetMessage(int index)
{
_imapSw.WriteLine("$ FETCH " + index + " BODY.PEEK[]");
_imapSw.Flush();
return Response();
}
private string Response()
{
byte[] data = new byte[_imapClient.ReceiveBufferSize];
int ret = _imapNs.Read(data, 0, data.Length);
string output = Encoding.ASCII.GetString(data).TrimEnd().Replace("\0", "");
return output;
}
public void Disconnect()
{
_imapSw.WriteLine("$ LOGOUT");
_imapSw.Flush();
_imapClient.Close();
}
public string SendCommand(string command)
{
_imapSw.WriteLine("$ " + command);
_imapSw.Flush();
return Response();
}
It looks like you are using code from here, or similar:
http://www.codeproject.com/Articles/29594/How-to-Access-Emails-Using-the-IMAP-Protocol
That code as written is wrong and won't work for larger messages. The Response() call needs to loop over calls to .Read(), appending the results until the method returns 0 (which indicates there is no more data available.) Look at the documentation for NetworkStream.Read.
Also, you'd be much better off using an IMAP library (see Accessing Imap in C#).
You Just Have To Change Your Receive Buffer Size

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

Resources