blackberry sax XML parsing - blackberry

i am very new in blackberry, now i am trying to do XML programming, using defaulthandler in sax parser blackberry.
any sample code, url or any advice highly appreciated.
thanks
Regards..

Find the sample code here. Cheers. ;-)
// IBMRssXMLHandler.java
//
// MSI Services, Inc.
// Frank Ableson
// 973.448.0070
// fableson#msiservices.com
// code free to use for any purpose, commercial or otherwise
package com.msi.ibm.rssreader;
import org.xml.sax.helpers.*;
import org.xml.sax.*;
import java.lang.StringBuffer;
import com.msi.ibm.rssreader.IBMRssStorage.*;
/**
*
*/
class IBMRssXMLHandler extends DefaultHandler {
StringBuffer sb = null;
IBMRssFeed _feed = null;
IBMRssItem item = null;
boolean bStarted = false;
IBMRssStorage rssStore = null;
IBMRssXMLHandler(IBMRssFeed feed) {
_feed = feed;
rssStore = new IBMRssStorage();
}
public void warning(SAXParseException e) {
System.err.println("warning: " + e.getMessage());
bStarted = false;
}
public void error(SAXParseException e) {
System.err.println("error: " + e.getMessage());
}
public void fatalError(SAXParseException e) {
System.err.println("fatalError: " + e.getMessage());
bStarted = false;
}
public void startDocument() throws SAXException {
System.out.println("startDocument");
}
public void endDocument() throws SAXException {
System.out.println("endDocument");
// we've concluded this document, safe to create the feed.
rssStore.closeStore();
}
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
System.out.println("startElement [" + localName + "]");// Attributes
// [" + atts.toString() + "]");
sb = new StringBuffer("");
if (localName.equals("item")) {
bStarted = true;
// new item, let's set up!
item = rssStore.createItem();
}
}
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
System.out.println("endElement [" + localName + "] value = ["
+ sb.toString() + "]");
if (bStarted == false)
return;
if (localName.equals("item")) {
// store this item!
item.setName(_feed.getName());
System.out.println("Storing item! [" + item.toString());
rssStore.addRecord(item);
}
if (localName.equals("title")) {
item.setTitle(sb.toString());
}
if (localName.equals("link")) {
item.setLink(sb.toString());
}
if (localName.equals("description")) {
item.setDescription(sb.toString());
}
if (localName.equals("category")) {
item.setCategory(sb.toString());
}
if (localName.equals("pubDate")) {
item.setPubDate(sb.toString());
}
sb = new StringBuffer("");
}
public void characters(char ch[], int start, int length) {
String theString = new String(ch, start, length);
System.out.println("characters [" + theString + "]");
sb.append(theString);
}
}

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 read json string from an URL

I tried to read a json string loading from an URL, but I could not find complete code sample. Can any one provide or point me to a complete client code. I'm newer to BB development.
this is what I have done but still can't get it work please help me.
Thanks!
To read and parse data from an URL you need to implement two routines. First one of them will handle reading data from the specified URL over HTTP connection, and the second one will parse the data.
Check the following application HttpUrlReaderDemoApp, which will first read the data from specified URL and then parse the retrieved data.
URL used to retrieve data: http://codeincloud.tk/json_android_example.php
Sample data format: {"name":"Froyo", "version":"Android 2.2"}
Classes:
HttpUrlReaderDemoApp - UiApplication instance
HttpResponseListener - Interface used to notify other classes about HTTP request status
HttpUrlReader - Reads the data from given url
AppMainScreen - MainScreen instance
DataParser - Parse data
DataModel - Data definition
Screenshots:
Request for data
When data retrieved successfully
Parsed data
Implementation:
HttpUrlReaderDemoApp
public class HttpUrlReaderDemoApp extends UiApplication {
public static void main(String[] args) {
HttpUrlReaderDemoApp theApp = new HttpUrlReaderDemoApp();
theApp.enterEventDispatcher();
}
public HttpUrlReaderDemoApp() {
pushScreen(new AppMainScreen("HTTP Url Reader Demo Application"));
}
}
HttpResponseListener
public interface HttpResponseListener {
public void onHttpResponseFail(String message, String url);
public void onHttpResponseSuccess(byte bytes[], String url);
}
HttpUrlReader
public class HttpUrlReader implements Runnable {
private String url;
private HttpResponseListener listener;
public HttpUrlReader(String url, HttpResponseListener listener) {
this.url = url;
this.listener = listener;
}
private String getConncetionDependentUrlSuffix() {
// Not implemented
return "";
}
private void notifySuccess(byte bytes[], String url) {
if (listener != null) {
listener.onHttpResponseSuccess(bytes, url);
}
}
private void notifyFailure(String message, String url) {
if (listener != null) {
listener.onHttpResponseFail(message, url);
}
}
private boolean isValidUrl(String url) {
return (url != null && url.length() > 0);
}
public void run() {
if (!isValidUrl(url) || listener == null) {
String message = "Invalid parameters.";
message += !isValidUrl(url) ? " Invalid url." : "";
message += (listener == null) ? " Invalid HttpResponseListerner instance."
: "";
notifyFailure(message, url);
return;
}
// update URL depending on connection type
url += DeviceInfo.isSimulator() ? ";deviceside=true"
: getConncetionDependentUrlSuffix();
// Open the connection and retrieve the data
try {
HttpConnection httpConn = (HttpConnection) Connector.open(url);
int status = httpConn.getResponseCode();
if (status == HttpConnection.HTTP_OK) {
InputStream input = httpConn.openInputStream();
byte[] bytes = IOUtilities.streamToBytes(input);
input.close();
notifySuccess(bytes, url);
} else {
notifyFailure("Failed to retrieve data, HTTP response code: "
+ status, url);
return;
}
httpConn.close();
} catch (Exception e) {
notifyFailure("Failed to retrieve data, Exception: ", e.toString());
return;
}
}
}
AppMainScreen
public class AppMainScreen extends MainScreen implements HttpResponseListener {
private final String URL = "http://codeincloud.tk/json_android_example.php";
public AppMainScreen(String title) {
setTitle(title);
}
private MenuItem miReadData = new MenuItem("Read data", 0, 0) {
public void run() {
requestData();
}
};
protected void makeMenu(Menu menu, int instance) {
menu.add(miReadData);
super.makeMenu(menu, instance);
}
public void close() {
super.close();
}
public void showDialog(final String message) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(message);
}
});
}
private void requestData() {
Thread urlReader = new Thread(new HttpUrlReader(URL, this));
urlReader.start();
showDialog("Request for data from\n \"" + URL + "\"\n started.");
}
public void onHttpResponseFail(String message, String url) {
showDialog("Failure Mesage:\n" + message + "\n\nUrl:\n" + url);
}
public void onHttpResponseSuccess(byte bytes[], String url) {
showDialog("Data retrived from:\n" + url + "\n\nData:\n"
+ new String(bytes));
// now parse response
DataModel dataModel = DataParser.getData(bytes);
if (dataModel == null) {
showDialog("Failed to parse data: " + new String(bytes));
} else {
showDialog("Parsed Data:\nName: " + dataModel.getName()
+ "\nVersion: " + dataModel.getVersion());
}
}
}
DataParser
public class DataParser {
private static final String NAME = "name";
private static final String VERSION = "version";
public static DataModel getData(byte data[]) {
String rawData = new String(data);
DataModel dataModel = new DataModel();
try {
JSONObject jsonObj = new JSONObject(rawData);
if (jsonObj.has(NAME)) {
dataModel.setName(jsonObj.getString(NAME));
}
if (jsonObj.has(VERSION)) {
dataModel.setVersion(jsonObj.getString(VERSION));
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return dataModel;
}
}
DataModel
public class DataModel {
private String name;
private String version;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String model) {
this.version = model;
}
}

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

SAX parser in BlackBerry

My XML is in following format
<users>
<user uid="1" dispname ="Yogesh C" statid="1" statmsg = "Busy">Yogesh Chaudhari</user>
<user uid="2" dispname ="Sameer S" statid="2" statmsg = "Available">Yogesh Chaudhari</user>
</users>
In my BlackBerry app, I want to change the value of a particualar attribute, such as statmsg for uid 2. Is it possible to do this using a SAX parser? My aim is to update the XML and restore it.
I used the following code for parsing my XML using SAX:
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
public class SaxParseUrl extends UiApplication {
public SaxParseUrl() {
pushScreen(new Pars());
}
public static void main(String[] args) {
SaxParseUrl app = new SaxParseUrl();
app.enterEventDispatcher();
}
}
class Pars extends MainScreen implements ContentHandler
{
boolean name;
Pars() {
try {
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(this);
FileConnection conn = (FileConnection)Connector.open("file:///store/home/user/employee.xml");
InputStream is = conn.openDataInputStream();
InputSource iss = new InputSource(is);
parser.parse(iss);
} catch (Exception e) {
debug("file:///store/home/user/SAXParser.txt","Exception in pars() :"+e);
}
}
public void startElement(String nsURI, String strippedName, String tagName,
Attributes attributes) throws SAXException {
try {
debug("file:///store/home/user/SAXParser.txt","startElement");
if (tagName.equalsIgnoreCase("user"))
{
debug("file:///store/home/user/SAXParser.txt","Inside startElement");
name = true;
String uid = attributes.getValue("uid");
String dispname = attributes.getValue("dispname");
String statid = attributes.getValue("statid");
String statmsg = attributes.getValue("statmsg");
attributes.
//LabelField lb = new LabelField(uid+"==>"+dispname+"==>"+statid+"==>"+statmsg);
LabelField lb = new LabelField("uid ==>"+uid+"\ndispname==>"+dispname+"\nstatid==>"+statid+"\nstatmsg==>"+statmsg);
add(lb);
}
} catch (Exception e) {
System.out.println(e);
}
}
public void characters(char[] ch, int start, int length) {
debug("file:///store/home/user/SAXParser.txt","characters");
if (name) {
try {
System.out.println("Title: " + new String(ch, start, length));
LabelField lb=new LabelField(""+ new String(ch, start, length));
HorizontalFieldManager sr=new HorizontalFieldManager();
sr.add(lb);
add(sr);
//v_cid.addElement(new String(ch, start, length));
//System.out.println("the elements of vector: " + v_cid);
// name = false;
//Enumeration e = v_cid.elements();
//System.out.println("The elements of vector: " + v_cid);
//while (e.hasMoreElements()) {
//System.out.println("The elements are: " + e.nextElement());
//}*/
} catch (Exception e) {
System.out.println(e);
}
}
}
public void endDocument() throws SAXException {
debug("file:///store/home/user/SAXParser.txt","endDocument");
}
public void endElement(String uri, String localName, String tagName)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","endElement");
}
public void endPrefixMapping(String prefix) throws SAXException {
debug("file:///store/home/user/SAXParser.txt","endPrefixMapping");
}
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","ignorableWhitespace");
}
public void processingInstruction(String target, String data)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","processingInstruction");
}
public void setDocumentLocator(Locator locator) {
debug("file:///store/home/user/SAXParser.txt","setDocumentLocator");
}
public void skippedEntity(String name) throws SAXException {
}
public void startDocument() throws SAXException {
debug("file:///store/home/user/SAXParser.txt","startDocument");
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","startPrefixMapping");
}
public static void debug(String strFileName,String strData)
{
FileConnection fc = null;
StringBuffer strbufData = null;
OutputStream ops = null;
try
{
fc = (FileConnection)Connector.open(strFileName,Connector. READ_WRITE);
//create the file if it doesnt exist
if(!fc.exists())
{
fc.create();
}
InputStream is = fc.openDataInputStream();
strbufData = new StringBuffer();
int intCh;
while((intCh = is.read())!= -1)
{
strbufData.append((char)intCh);
}
strbufData.append("\n\n"+strData);
String strFileContent = new String(strbufData.toString());
byte byteData[] = strFileContent.getBytes();
ops = fc.openOutputStream();
ops.write(byteData);
}
catch(Exception e)
{
Dialog.alert("Exception in writing logs :"+e);
}
finally
{
if(ops != null)
{
try
{
ops.close();
}catch(Exception e)
{
}
}
if(fc != null)
{
try
{
fc.close();
}catch(Exception e)
{
}
}
}
}
}

How to parse xml document in Blackberry?

How can I parse a xml file in Blackberry? Can I have a link or sample code or tutorial?
I've used SAX to process XML responses from a web api and it worked well for me. Check out: http://developerlife.com/tutorials/?p=28
What exactly are you trying to accomplish with XML?
You should have a interface to implement the listener in order to notify your UI thread once parsing is over.
import java.util.Vector;
public interface MediaFeedListner {
public void mediaItemParsed(Vector mObject);
public void exception(java.io.IOException ioe);
}
implement your class with MediaFeedListner and then override the mediaItemParsed(Vector mObject) and exception(java.io.IOException ioe) methoods.
mediaItemParsed() method will have the logic for notifying the UI thread and perform required operations.
Here is the XML parser code.
package com.test.net;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Vector;
import net.rim.device.api.xml.parsers.ParserConfigurationException;
import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.span.data.MediaObject;
import com.span.utils.FileManager;
public class MediaHandler extends DefaultHandler {
protected static final String TAG_FEED = "feed";
protected static final String TAG_ENTRY = "entry";
protected static final String TAG_TITLE = "title";
protected static final String TAG_MEDIA_GROUP = "group";
protected static final String TAG_MEDIA_CATEGORY = "category";
protected static final String TAG_MEDIA_CONTENT = "content";
protected static final String TAG_MEDIA_DESCRIPTION = "description";
protected static final String TAG_MEDIA_THUMBNAIL = "thumbnail";
protected static final String ATTR_MEDIA_CONTENT= "url";
protected static final String ATTR_MEDIA_THUMBNAIL = "url";
boolean isEntry = false;
boolean isTitle = false;
boolean isCategory = false;
boolean isDescription = false;
boolean isThumbUrl = false;
boolean isMediaUrl = false;
boolean isMediaGroup = false;
String valueTitle = "";
String valueCategory = "";
String valueDescription = "";
String valueThumbnailUrl = "";
String valueMediaUrl = "";
public static Vector mediaObjects = null;
MediaObject _dataObject = null;
MediaFeedListner listner = null;
public MediaHandler(MediaFeedListner listner) {
this.listner = listner;
mediaObjects = new Vector();
}
public void parseXMLString(String xmlString) {
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new ByteArrayInputStream(xmlString.getBytes()), this);
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
if(localName.equalsIgnoreCase(TAG_FEED)) {
//return;
}
if(localName.equals(TAG_ENTRY))
{
_dataObject = new MediaObject();
isEntry = true;
}
if(isEntry) {
if(localName.equalsIgnoreCase(TAG_TITLE)) {
isTitle = true;
}
if(localName.equals(TAG_MEDIA_GROUP))
isMediaGroup = true;
if(isMediaGroup) {
if(localName.equalsIgnoreCase(TAG_MEDIA_CONTENT)) {
valueMediaUrl = attributes.getValue(ATTR_MEDIA_CONTENT);
if(valueMediaUrl != null) {
_dataObject.setMediaUrl(valueMediaUrl);
valueMediaUrl = "";
}
}
if(localName.equalsIgnoreCase(TAG_MEDIA_THUMBNAIL)) {
valueThumbnailUrl = attributes.getValue(ATTR_MEDIA_THUMBNAIL);
if(valueThumbnailUrl != null) {
_dataObject.setMediaThumb(valueThumbnailUrl);
valueThumbnailUrl = "";
}
}
if(localName.equalsIgnoreCase(TAG_MEDIA_DESCRIPTION)) {
isDescription = true;
}
if(localName.equalsIgnoreCase(TAG_MEDIA_CATEGORY)) {
isCategory = true;
}
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if(isTitle){
valueTitle = new String(ch, start, length);
_dataObject.setMediaTitle(valueTitle);
System.out.println("Title value " + valueTitle);
valueTitle = "";
}
if(isCategory){
valueCategory = new String(ch, start, length);
_dataObject.setMediaCategory(valueCategory);
System.out.println("category value " + valueCategory);
valueCategory = "";
}
if(isDescription){
valueDescription = new String(ch, start, length);
_dataObject.setMediaDesc(valueDescription);
System.out.println("category value " + valueDescription);
valueDescription = "";
}
}
public void endElement(String uri, String localName, String name) throws SAXException {
if(localName.equalsIgnoreCase(TAG_FEED)) {
listner.mediaItemParsed(mediaObjects);
printMediaInfo(mediaObjects);
}
if(localName.equalsIgnoreCase(TAG_ENTRY)) {
isEntry = false;
isTitle = false;
isCategory = false;
isDescription = false;
mediaObjects.addElement(_dataObject);
}
}
public static void printMediaInfo(Vector v){
int length = v.size();
for(int i = 0 ; i <length ; i++){
MediaObject mediaObj = (MediaObject) v.elementAt(i);
FileManager.getInstance().writeLog("Title: " + mediaObj.getMediaTitle());
FileManager.getInstance().writeLog("Category: " + mediaObj.getMediaCategory());
FileManager.getInstance().writeLog("Desc: " + mediaObj.getMediaDesc());
FileManager.getInstance().writeLog("URL: " + mediaObj.getMediaUrl());
FileManager.getInstance().writeLog("Thumb: " + mediaObj.getMediaThumb());
FileManager.getInstance().writeLog("Fav count: " + mediaObj.getMediaFavCount());
FileManager.getInstance().writeLog("View Count: " + mediaObj.getMediaViewCount());
FileManager.getInstance().writeLog("Ratings: " + mediaObj.getMediaRating());
FileManager.getInstance().writeLog("============================================");
}
}
}
Its done.

Resources