Related
Am using primefaces 5.3. I am generating a primefaces menu dynamically. I want to set the id on the menu elements so that I can display a tooltip based on that id.
My code is:
DefaultMenuModel menuModel = new DefaultMenuModel();
DefaultMenuItem homeMenuItem = new DefaultMenuItem( "Hello");
homeMenuItem.setIcon("fa fa-home");
homeMenuItem.setTitle("halloo");
//Setting the id here
homeMenuItem.setId("homeId");
menuModel.addElement(homeMenuItem);
However when I view the page source or inspect the element there is no id set on that menu item. Is there some other way to set the id on a menu element?
This doesn't work in PrimeFaces. I already opened an issue ticket but it isn't solved yet. If you check the sourcecode you will see, that it sets your chosen id first, but then it overrides it again in the backend. So there is no chance to set an id programatically at the moment.
You can get elements by style class via javascript if that solves your problem.
Here you can see a similar question with the ticket number:
Id of menuitem is not rendered
I did a workaround which worked for me so far.
Maybe ist helps you too:
You have to override the Primefaces classes with Custom Classes of your own.
Here is my example:
Add this to faces-config.xml
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.PanelMenuRenderer</renderer-type>
<renderer-class>mypath.CustomPanelMenuRenderer</renderer-class>
</renderer></render-kit>
then I added the two overwritten classes:
CustomPanelMenuRenderer:
public class CustomPanelMenuRenderer extends CustomBaseMenuRenderer {
#Override
protected void encodeScript(FacesContext context, AbstractMenu abstractMenu) throws IOException {
PanelMenu menu = (PanelMenu) abstractMenu;
String clientId = menu.getClientId(context);
WidgetBuilder wb = getWidgetBuilder(context);
wb.initWithDomReady("PanelMenu", menu.resolveWidgetVar(), clientId)
.attr("stateful", menu.isStateful());
wb.finish();
}
#Override
protected void encodeMarkup(FacesContext context, AbstractMenu abstractMenu) throws IOException {
ResponseWriter writer = context.getResponseWriter();
PanelMenu menu = (PanelMenu) abstractMenu;
String clientId = menu.getClientId(context);
String style = menu.getStyle();
String styleClass = menu.getStyleClass();
styleClass = styleClass == null ? PanelMenu.CONTAINER_CLASS : PanelMenu.CONTAINER_CLASS + " " + styleClass;
writer.startElement("div", menu);
writer.writeAttribute("id", clientId, "id");
writer.writeAttribute("class", styleClass, "styleClass");
if (style != null) {
writer.writeAttribute("style", style, "style");
}
writer.writeAttribute("role", "menu", null);
if (menu.getElementsCount() > 0) {
List<MenuElement> elements = menu.getElements();
for (MenuElement element : elements) {
if (element.isRendered() && element instanceof Submenu) {
encodeRootSubmenu(context, menu, (Submenu) element);
}
}
}
writer.endElement("div");
}
protected void encodeRootSubmenu(FacesContext context, PanelMenu menu, Submenu submenu) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String style = submenu.getStyle();
String styleClass = submenu.getStyleClass();
styleClass = styleClass == null ? PanelMenu.PANEL_CLASS : PanelMenu.PANEL_CLASS + " " + styleClass;
boolean expanded = submenu.isExpanded();
String headerClass = expanded ? PanelMenu.ACTIVE_HEADER_CLASS : PanelMenu.INACTIVE_HEADER_CLASS;
String headerIconClass = expanded ? PanelMenu.ACTIVE_TAB_HEADER_ICON_CLASS : PanelMenu.INACTIVE_TAB_HEADER_ICON_CLASS;
String contentClass = expanded ? PanelMenu.ACTIVE_ROOT_SUBMENU_CONTENT : PanelMenu.INACTIVE_ROOT_SUBMENU_CONTENT;
//wrapper
writer.startElement("div", null);
writer.writeAttribute("class", styleClass, null);
if (style != null) {
writer.writeAttribute("style", style, null);
}
if (submenu.getClientId() != null) {
writer.writeAttribute("id", submenu.getClientId(), null);
}
//header
writer.startElement("h3", null);
writer.writeAttribute("class", headerClass, null);
writer.writeAttribute("role", "tab", null);
writer.writeAttribute("tabindex", "0", null);
//icon
writer.startElement("span", null);
writer.writeAttribute("class", headerIconClass, null);
writer.endElement("span");
writer.startElement("a", null);
writer.writeAttribute("href", "#", null);
writer.writeAttribute("tabindex", "-1", null);
writer.writeText(submenu.getLabel(), null);
writer.endElement("a");
writer.endElement("h3");
//content
writer.startElement("div", null);
writer.writeAttribute("class", contentClass, null);
writer.writeAttribute("role", "tabpanel", null);
writer.writeAttribute("id", menu.getClientId(context) + "_" + submenu.getId(), null);
writer.writeAttribute("tabindex", "0", null);
if (submenu.getElementsCount() > 0) {
List<MenuElement> elements = submenu.getElements();
writer.startElement("ul", null);
writer.writeAttribute("class", PanelMenu.LIST_CLASS, null);
for (MenuElement element : elements) {
if (element.isRendered()) {
if (element instanceof MenuItem) {
MenuItem menuItem = (MenuItem) element;
String containerStyle = menuItem.getContainerStyle();
String containerStyleClass = menuItem.getContainerStyleClass();
containerStyleClass = (containerStyleClass == null) ? Menu.MENUITEM_CLASS : Menu.MENUITEM_CLASS + " " + containerStyleClass;
writer.startElement("li", null);
writer.writeAttribute("class", containerStyleClass, null);
if (element.getId() != null) {
writer.writeAttribute("id", element.getId(), null);
}
if (containerStyle != null) {
writer.writeAttribute("style", containerStyle, null);
}
encodeMenuItem(context, menu, menuItem);
writer.endElement("li");
}
else if (element instanceof Submenu) {
encodeDescendantSubmenu(context, menu, (Submenu) element);
}
}
}
writer.endElement("ul");
}
writer.endElement("div"); //content
writer.endElement("div"); //wrapper
}
protected void encodeDescendantSubmenu(FacesContext context, PanelMenu menu, Submenu submenu) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String icon = submenu.getIcon();
String style = submenu.getStyle();
String styleClass = submenu.getStyleClass();
styleClass = styleClass == null ? PanelMenu.DESCENDANT_SUBMENU_CLASS : PanelMenu.DESCENDANT_SUBMENU_CLASS + " " + styleClass;
boolean expanded = submenu.isExpanded();
String toggleIconClass = expanded ? PanelMenu.DESCENDANT_SUBMENU_EXPANDED_ICON_CLASS : PanelMenu.DESCENDANT_SUBMENU_COLLAPSED_ICON_CLASS;
String listClass = expanded ? PanelMenu.DESCENDANT_SUBMENU_EXPANDED_LIST_CLASS : PanelMenu.DESCENDANT_SUBMENU_COLLAPSED_LIST_CLASS;
boolean hasIcon = (icon != null);
String linkClass = (hasIcon) ? PanelMenu.MENUITEM_LINK_WITH_ICON_CLASS : PanelMenu.MENUITEM_LINK_CLASS;
writer.startElement("li", null);
writer.writeAttribute("id", submenu.getClientId(), null);
writer.writeAttribute("class", styleClass, null);
if (style != null) {
writer.writeAttribute("style", style, null);
}
writer.startElement("a", null);
writer.writeAttribute("class", linkClass, null);
//toggle icon
writer.startElement("span", null);
writer.writeAttribute("class", toggleIconClass, null);
writer.endElement("span");
//user icon
if (hasIcon) {
writer.startElement("span", null);
writer.writeAttribute("class", "ui-icon " + icon, null);
writer.endElement("span");
}
//submenu label
writer.startElement("span", null);
writer.writeAttribute("class", PanelMenu.MENUITEM_TEXT_CLASS, null);
writer.writeText(submenu.getLabel(), null);
writer.endElement("span");
writer.endElement("a");
//submenu children
if (submenu.getElementsCount() > 0) {
List<MenuElement> elements = submenu.getElements();
writer.startElement("ul", null);
writer.writeAttribute("class", listClass, null);
for (MenuElement element : elements) {
if (element.isRendered()) {
if (element instanceof MenuItem) {
writer.startElement("li", null);
writer.writeAttribute("class", Menu.MENUITEM_CLASS, null);
encodeMenuItem(context, menu, (MenuItem) element);
writer.endElement("li");
}
else if (element instanceof Submenu) {
encodeDescendantSubmenu(context, menu, (Submenu) element);
}
}
}
writer.endElement("ul");
}
writer.endElement("li");
}
}
and CustomBaseMenuRenderer:
public class CustomBaseMenuRenderer extends BaseMenuRenderer {
#Override
protected void encodeMenuItem(FacesContext context, AbstractMenu menu, MenuItem menuitem) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String title = menuitem.getTitle();
String style = menuitem.getStyle();
boolean disabled = menuitem.isDisabled();
writer.startElement("a", null);
writer.writeAttribute("tabindex", "-1", null);
if (shouldRenderId(menuitem)) {
writer.writeAttribute("id", menuitem.getClientId(), null);
}
if (title != null) {
writer.writeAttribute("title", title, null);
}
String styleClass = this.getLinkStyleClass(menuitem);
if (disabled) {
styleClass = styleClass + " ui-state-disabled";
}
writer.writeAttribute("class", styleClass, null);
if (style != null) {
writer.writeAttribute("style", style, null);
}
if (disabled) {
writer.writeAttribute("href", "#", null);
writer.writeAttribute("onclick", "return false;", null);
}
else {
setConfirmationScript(context, menuitem);
String onclick = menuitem.getOnclick();
//GET
if (menuitem.getUrl() != null || menuitem.getOutcome() != null) {
String targetURL = getTargetURL(context, (UIOutcomeTarget) menuitem);
writer.writeAttribute("href", targetURL, null);
if (menuitem.getTarget() != null) {
writer.writeAttribute("target", menuitem.getTarget(), null);
}
}
//POST
else {
writer.writeAttribute("href", "#", null);
UIComponent form = ComponentTraversalUtils.closestForm(context, menu);
if (form == null) {
throw new FacesException("MenuItem must be inside a form element");
}
String command;
if (menuitem.isDynamic()) {
String menuClientId = menu.getClientId(context);
Map<String, List<String>> params = menuitem.getParams();
if (params == null) {
params = new LinkedHashMap<String, List<String>>();
}
List<String> idParams = new ArrayList<String>();
idParams.add(menuitem.getId());
params.put(menuClientId + "_menuid", idParams);
command = menuitem.isAjax() ? buildAjaxRequest(context, menu, (AjaxSource) menuitem, form, params) : buildNonAjaxRequest(context, menu, form, menuClientId, params, true);
}
else {
command = menuitem.isAjax() ? buildAjaxRequest(context, (AjaxSource) menuitem, form)
: buildNonAjaxRequest(context, ((UIComponent) menuitem), form, ((UIComponent) menuitem).getClientId(context), true);
}
onclick = (onclick == null) ? command : onclick + ";" + command;
}
if (onclick != null) {
if (menuitem.requiresConfirmation()) {
writer.writeAttribute("data-pfconfirmcommand", onclick, null);
writer.writeAttribute("onclick", menuitem.getConfirmationScript(), "onclick");
}
else {
writer.writeAttribute("onclick", onclick, null);
}
}
}
encodeMenuItemContent(context, menu, menuitem);
writer.endElement("a");
}
#Override
protected boolean shouldRenderId(MenuElement element) {
if (element instanceof UIComponent) {
return shouldWriteId((UIComponent) element);
}
return false;
}
#Override
protected void encodeMarkup(FacesContext context, AbstractMenu abstractMenu) throws IOException {
// TODO Auto-generated method stub
}
#Override
protected void encodeScript(FacesContext context, AbstractMenu abstractMenu) throws IOException {
// TODO Auto-generated method stub
}
}
now you should be able to set Ids in the backend as expected.
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.
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";
}
?>
I have an app that uses a browserfield to connect to a web-page.
All is working ok and the simulator shows the right page.
If I set the simulator Network Properties to "Out of Coverage" and click on a link in my web-page then I get an exception - in the BrowserFieldConnectionManagerImpl
How can catch this exception so I can take appropriate action?
The app is using BlackBerry SDK
The code is here:
public final class example_Screen extends MainScreen {
// Create the ErrorHandler class
public class MyBrowserFieldErrorHandler extends BrowserFieldErrorHandler {
protected MyBrowserFieldErrorHandler(BrowserField browserField){
super(browserField);
}
public void displayContentError(String url, String errorMessage) {
System.out.println("JERRY: displayContentError" + url);
System.out.println("JERRY: displayContentError" + errorMessage);
}
public void displayContentError(String url, InputConnection connection, Throwable t) {
displayContentError(url, t.getMessage());
}
public void navigationRequestError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
}
public void requestContentError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
}
public InputConnection resourceRequestError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
InputConnection connection = null;
return connection;
}
}
/**
* Creates a new example_Screen object
*/
public example_Screen() {
GIFEncodedImage ourAnimation = (GIFEncodedImage) GIFEncodedImage.getEncodedImageResource("2.gif");
AnimatedGIFField _ourAnimation = new AnimatedGIFField(ourAnimation, Field.FIELD_HCENTER + Field.FIELD_VCENTER);
this.add(_ourAnimation);
LabelField _ourLabelField = new LabelField("Updating ...", Field.FIELD_HCENTER + Field.FIELD_VCENTER);
this.add(_ourLabelField);
int anim_ht = _ourAnimation.getPreferredHeight();
int label_ht = _ourLabelField.getPreferredHeight();
EncodedImage ei = EncodedImage.getEncodedImageResource("img/menu.png");
int currentWidthFixed32 = Fixed32.toFP(ei.getWidth());
int currentHeightFixed32 = Fixed32.toFP(ei.getHeight());
int displayWidthFixed32 = Fixed32.toFP(Display.getWidth());
int displayHeightFixed32 = Fixed32.toFP((Display.getHeight() - anim_ht - label_ht));
int scaleXFixed32 = Fixed32.div(currentWidthFixed32, displayWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, displayHeightFixed32);
ei = ei.scaleImage32(scaleXFixed32, scaleYFixed32);
BitmapField bmp = new BitmapField(ei.getBitmap(), Field.FIELD_HCENTER + Field.FIELD_VCENTER);
add(bmp);
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
BrowserField browserField = new BrowserField(myBrowserFieldConfig);
add(browserField);
browserField.requestContent("http://www.bbc.co.uk");
BrowserFieldListener listener = new BrowserFieldListener() {
public void documentAborted(BrowserField browserField, Document document) {
System.out.println("JERRY: documentAborted");
}
public void documentCreated(BrowserField browserField, ScriptEngine scriptEngine, Document document) {
System.out.println("JERRY: documentCreated");
}
public void documentError(BrowserField browserField, Document document) {
System.out.println("JERRY: documentError");
}
public void documentLoaded(BrowserField browserField, Document document) {
System.out.println("JERRY: documentLoaded");
Node node = document.getFirstChild();
String nodeText = node.getTextContent();
int index = -1;
if (nodeText != null) {
String errorText = "Error requesting content for:";
index = nodeText.indexOf(errorText);
}
Screen screen = browserField.getScreen();
try {
synchronized (Application.getEventLock()) {
if (index == -1) {
System.out.println("JERRY: documentLoaded: no error");
int count = screen.getFieldCount();
if (count > 1) {
screen.deleteRange(0, (count-1));
System.out.println("JERRY: documentLoaded: " + (count-1) + " fields deleted");
} else {
System.out.println("JERRY: documentLoaded: only 1 field so none deleted");
}
} else {
System.out.println("JERRY: documentLoaded: error");
}
}
} catch (final Exception ex) {
System.out.println("example_Screen: documentLoaded: exception caught: " + ex.toString());
}
}
public void documentUnloading(BrowserField browserField, Document document) {
System.out.println("JERRY: documentUnloading");
}
public void downloadProgress(BrowserField browserField, ContentReadEvent event) {
System.out.println("JERRY: downloadProgress");
}
};
browserField.addListener(listener);
// Attach the Error Handler to the BrowserField
BrowserFieldErrorHandler eHandler = new MyBrowserFieldErrorHandler(browserField);
browserField.getConfig().setProperty(BrowserFieldConfig.ERROR_HANDLER, eHandler);
}
}
BrowserField contains a method, addListener() which takes a reference to BrowserFieldListener implementation.
Extend BrowserFieldListener and process errors in methods documentError() and documentAborted() of this implementation.
Then add a reference of your class instance that extends BrowserFieldListener to your browser field via browserField.addListener(browserFieldListener);.
EDIT:
If this does not work, then use BrowserFieldErrorHandler class from RIM API. Build your own error handler and pass its instance to the browserfield configuration.
Below, there's sample code:
// Create the ErrorHandler class
public class MyBrowserFieldErrorHandler extends BrowserFieldErrorHandler {
public void displayContentError(String url, String errorMessage) {
String error = "Error: (url=" + url + "): " + t.getMessage();
Dialog.ask(Dialog.D_OK, error);
logMessage(“BrowserFieldError: “ + error );
}
public void displayContentError(String url, InputConnection connection, Throwable t) {
displayContentError(url, t.getMessage());
}
public void requestContentError(BrowserFieldRequest request, Throwable t){
displayContentError(request.getURL(), t.getMessage());
}
}
// Attach the Error Handler to the BrowserField
BrowserFieldErrorHandler eHandler = new MyBrowserFieldErrorHandler();
browserField.getConfig().setProperty(BrowserFieldConfig.ERROR_HANDLER,eHandler);
I get this sample code from DevCon2010 presentation of BrowserField capabilities. You can get it here: http://dev.tuyennguyen.ca/wp-content/uploads/2011/02/DEV49.pdf
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);
}
}