Welcome!

Welcome to the official BlackBerry Support Community Forums.

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

inside custom component

BlackBerry Push Development

Reply
New Contributor
dev3
Posts: 5
Registered: ‎08-27-2013
My Device: blackberry curve 9360
My Carrier: 96171016127
Accepted Solution

Blackberry push notification

[ Edited ]

Hello,

 

I am new in Blackberry, we have develop an application related to soccer already on blackberry store(myFixtures) but we need to add in the new version the ability to use the push notification to push a match(result , status , started..)

for server side i have use this code :

 

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.Vector;
import javax.net.ssl.HttpsURLConnection;


public class Pusher {
 private static String _appid = "xxx-xxxxxxxxxxxxxxxx";
 private static String _spacers = "mPsbVQo0a68eIL3OAxnm";
 private static String _auth = "Basic <base64token>"; // Replace <base64token> with your APPID:PASS and encode
 private static String _pushurl = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest";
 private static String _uagent = "Hallgren Networks BB Push Server/1.0";
 private static boolean _output = false;

 public static boolean pushMessage(Vector<String> pins, String msg) {
  if (pins.isEmpty())
   return false;
  if (msg.equals(""))
   return false;

  String pushid = "" + System.currentTimeMillis();
  String delivebefore = getDeliveryTime();
  StringBuffer dataToSend = new StringBuffer();
  dataToSend.append("--" + _spacers + "\r\n");
  dataToSend.append("Content-Type: application/xml; charset=UTF-8\r\n\r\n");
  dataToSend.append("<?xml version=\"1.0\"?>\r\n");
  dataToSend.append("<!DOCTYPE pap PUBLIC \"-//WAPFORUM//DTD PAP 2.1//EN\" \"http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd\">\r\n");
  dataToSend.append("<pap>\r\n");
  dataToSend.append("<push-message push-id=\"" + pushid + "\" ");
  dataToSend.append("deliver-before-timestamp=\"" + delivebefore + "\" ");
  dataToSend.append("source-reference=\"" + _appid + "\">");
  for (int i = 0; i < pins.size(); ++i)
   dataToSend.append("<address address-value=\"" + pins.elementAt(i) + "\"/>");
  dataToSend.append("<quality-of-service delivery-method=\"unconfirmed\"/>\r\n");
  dataToSend.append("</push-message>\r\n");
  dataToSend.append("</pap>\r\n");
  dataToSend.append("--" + _spacers + "\r\n");
  dataToSend.append("Content-Type: text/plain\r\n");
  dataToSend.append("Push-Message-ID: " + pushid + "\r\n");
  dataToSend.append("\r\n");
  dataToSend.append(msg + "\r\n");
  dataToSend.append("--" + _spacers + "--");
  printer("-------------------------------------------------------------------");
  printer(dataToSend.toString());
  printer("-------------------------------------------------------------------");

  URL url;
  HttpsURLConnection connection = null;
  try {
   url = new URL(_pushurl);
   connection = (HttpsURLConnection) url.openConnection();
   connection.setRequestMethod("POST");
   connection.setRequestProperty("Content-Type", "multipart/related; boundary=" + _spacers + "; type=application/xml");
   connection.setRequestProperty("User-Agent", _uagent);
   connection.setRequestProperty("Authorization", _auth);
   connection.setDoInput(true);
   connection.setDoOutput(true);

   DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
   wr.writeBytes(dataToSend.toString());
   wr.flush();
   wr.close();
   BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
   StringBuilder sb = new StringBuilder();
   String line = null;
   while ((line = rd.readLine()) != null) {
    sb.append(line + '\n');
   }
   printer(connection.getResponseCode() + " | " + connection.getResponseMessage());
   printer(sb.toString());
   if (sb.toString().contains("code=\"1001\""))
    return true;
   return false;
  } catch (Exception e) {
   printer(e.getMessage());
   return false;
  } finally {
   if (connection != null) {
    connection.disconnect();
   }
  }

 }

 public static String getDeliveryTime() {
  Date now = new Date(System.currentTimeMillis() + 300000);
  SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
  d.setTimeZone(TimeZone.getTimeZone("GMT"));
  return d.format(now);
 }

 private static void printer(Object response) {
  if (_output)
   System.out.println(response);
 }
 /*
 public static void main(String[] args) {
  Vector<String> v = new Vector<String>();
  v.add("12345678");
  if (pushMessage(v, "message"))
   System.out.println("Sent Ok");
  else {
   System.out.println("Returned False");
  }
  /////////////////////////// Or send to all 
  Vector<String> v1 = new Vector<String>();
  v1.add("push_all");
  if (pushMessage(v, "message"))
   System.out.println("Sent Ok");
  else {
   System.out.println("Returned False");
  }
  
 }
 */
}



and for user side this code :
http://supportforums.blackberry.com/t5/BlackBerry-Push-Development/Simplified-BIS-Push-client-sample... ( i have download  PushAgent.java,PushMessageReader.java ‏)

and i have change the required for  registration info.

then i have try to push a message to the mobile nothing received on the mobile.why ?

from server side they return :

 

200 | OK
<?xml version="1.0"?>
<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd"><pap><push-response push-id="1377597181057" sender-address="http://cpxxxxxx-xxxxxxx.pushapi.eval.blackberry.com/mss/PD_pushRequest" sender-name="RIM Push-Data Service" reply-time="2013-08-27T09:53:07Z"><response-result code="1001" desc="The request has been accepted for processing."></response-result></push-response></pap>

true

 

If can anyone help me.
Thanks in advance;

 

 

Please use plain text.
Developer
peter9477
Posts: 6,473
Registered: ‎12-08-2010
My Device: PlayBook, Z10
My Carrier: none

Re: Blackberry push notification

Note that you tried to obscure the appid in the code, but didn't obscure it in the response from the PPG. (The part after sender-address appears to include it.) You might want to edit the post to obscure that too.

Also, is that URL really correct? I'm using one that is just http://cpNNNN.pushapi.eval. etc, and doesn't include the full app id.

I would think, however, that the issue is on the receiving side. After all, the response there shows that the PPG has accepted your request so presumably it is sending the pushes to the devices.

Peter Hansen -- (BB10 and dev-related blog posts at http://peterhansen.ca.)
Author of White Noise and Battery Guru for BB10 and for PlayBook | Get more from your battery!
Please use plain text.
New Contributor
dev3
Posts: 5
Registered: ‎08-27-2013
My Device: blackberry curve 9360
My Carrier: 96171016127

Re: Blackberry push notification

[ Edited ]

Thanks For the reply,

on the receiving side i am using those 2 file that i have download i call :

 

UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
new PushAgent();
}
});

 

on the home page to register the device;

 

the code is :

 

package myFixturespackage;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.ServerSocketConnection;

import net.rim.device.api.io.IOUtilities;
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.DeviceInfo;
import net.rim.device.api.ui.component.Dialog;


public class PushAgent {

	private static final String REGISTER_SUCCESSFUL = "rc=200";
	private static final String USER_ALREADY_SUBSCRIBED = "rc=10003";

	private static final String PUSH_PORT =config.port;
	private static final String BPAS_URL =config.BPAS_URL; 
	private static final String APP_ID = config.APP_ID;
	private static final String CONNECTION_SUFFIX =config.getConnectionString();

	private MessageReadingThread messageReadingThread;

	
	public PushAgent() {
		if(CONNECTION_SUFFIX==null){
			Dialog.alert("No connection found,Please check your connection And Try Again");
			return;	
		}
		messageReadingThread = new MessageReadingThread();
		messageReadingThread.start();
		registerBpas();
	}

	
	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://:" + PUSH_PORT + CONNECTION_SUFFIX;
			try {
				socket = (ServerSocketConnection) Connector.open(url);
			} catch (IOException ex) {
				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) {
						System.out.println("Failed to read push message, caused by " + e.getMessage());
						running = false;
					}
				} finally {
					close(conn, pushInputStream, null);
				}
			}
			
		}

		private void onListenError(final Exception ex) {
			System.out.println("Failed to open port, caused by " + ex);
		}
	}

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

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

	


	private void registerBpas() {
		final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null) + CONNECTION_SUFFIX;
		
		new Thread() {
			public void run() {
				try {
					HttpConnection httpConnection = (HttpConnection) Connector.open(registerUrl);
					InputStream is = httpConnection.openInputStream();
					String response = new String(IOUtilities.streamToBytes(is));
					close(httpConnection, is, null);
					String nextUrl = formRegisterRequest(BPAS_URL, APP_ID, response) + CONNECTION_SUFFIX;
					HttpConnection nextHttpConnection = (HttpConnection) Connector.open(nextUrl);
					InputStream nextInputStream = nextHttpConnection.openInputStream();
					response = new String(IOUtilities.streamToBytes(nextInputStream));
					close(nextHttpConnection, is, null);
					if (REGISTER_SUCCESSFUL.equals(response)) {
						System.out.println("Registered successfully for BIS push");
					} 
					else if( USER_ALREADY_SUBSCRIBED.equals(response)){
						System.out.println("Already Registered successfully for BIS push");	
					}
					else {
						System.out.println("BPAS rejected registration");
					}
				} catch (IOException e) {
					System.out.println("IOException on register() " + e + " " + e.getMessage());
				}
			}
		}.start();
	}

	
}

 and to read the push this is the class  but i don't know where to include it :

 

package myFixturespackage;

import java.io.ByteArrayInputStream;

import javax.microedition.io.Connection;

import net.rim.blackberry.api.messagelist.ApplicationIndicatorRegistry;
import net.rim.device.api.io.Base64InputStream;
import net.rim.device.api.io.http.HttpServerConnection;
import net.rim.device.api.io.http.PushInputStream;
import net.rim.device.api.notification.NotificationsManager;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.system.ApplicationManagerException;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.UiEngine;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.util.Arrays;

public final class PushMessageReader {

	private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
	private static final String MESSAGE_TYPE_TEXT = "text";
	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];
	
	public static Bitmap popup = Bitmap.getBitmapResource("icon.png");
	
	private PushMessageReader() {
	}


	
	public static void process(PushInputStream pis, Connection conn) {Bitmap.getPredefinedBitmap(Bitmap.HOURGLASS), 1000);
		try {

			HttpServerConnection httpConn;
			if (conn instanceof HttpServerConnection) {
				httpConn = (HttpServerConnection) conn;
			} else {
				return;
			}

			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) {
				} else if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
					
					int size = pis.read(buffer);
					binaryData = new byte[size];
					System.arraycopy(buffer, 0, binaryData, 0, size);
					
					 NotificationsManager.triggerImmediateEvent(0, 0, null,
		                        null);
		             processTextMessage(buffer);
				} else if (msgType.indexOf(MESSAGE_TYPE_IMAGE) >= 0) {
					int size = pis.read(buffer);
					if (encoding != null && encoding.equalsIgnoreCase("base64")) {
						Base64InputStream bis = new Base64InputStream(new ByteArrayInputStream(buffer, 0, size));
						size = bis.read(imageBuffer);
					}
					binaryData = new byte[size];
					System.arraycopy(buffer, 0, binaryData, 0, size);	
					
				} else {
				}
			} else {
			}
			pis.accept();
		} catch (Exception e) {
		} finally {
			PushAgent.close(conn, pis, null);
		}
	}

	
	private static boolean alreadyReceived(String id) {
		if (id == null) {
			return false;
		}

		if (Arrays.contains(messageIdHistory, id)) {
			return true;
		}

		messageIdHistory[historyIndex++] = id;
		if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
			historyIndex = 0;
		}
		return false;
	}
	
	private static void processTextMessage(final byte[] data) {
	    synchronized (Application.getEventLock()) {

	      final UiEngine ui = Ui.getUiEngine();

	        final GlobalDialog screen = new GlobalDialog("MyFixtures",
	                  new String(data), new String(data));
	        
	      UiApplication.getUiApplication().invokeLater(new Runnable() {
	        	  public void run() {
	        		  ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
	        	  }
	        	});
	    }
	}
	
static class GlobalDialog extends PopupScreen implements
    FieldChangeListener {
ButtonField mOKButton = new ButtonField("OK", ButtonField.CONSUME_CLICK
        | FIELD_HCENTER);
String data = "";

public GlobalDialog(String title, String text, String data) {
    super(new VerticalFieldManager());
    this.data = data;

    add(new LabelField(title));
    add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
    add(new LabelField(text, DrawStyle.HCENTER));

    mOKButton.setChangeListener(this);
    add(mOKButton);
}

public void fieldChanged(Field field, int context) {
    if (mOKButton == field) {
        try {
            ApplicationManager.getApplicationManager().launch(
                    "MyFixtures");
            ApplicationManager.getApplicationManager().postGlobalEvent(
                    0, 0, 0, data, null);

            ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
                    .getInstance();
            reg.unregister();

            close();
        } catch (ApplicationManagerException e) {
        }
    }
}
}

}

 

 

 

Please use plain text.
Developer
peter9477
Posts: 6,473
Registered: ‎12-08-2010
My Device: PlayBook, Z10
My Carrier: none

Re: Blackberry push notification

[ Edited ]

I can't help with the Java stuff, as I'm doing only BB10, but maybe others can. I suggest you reformat your code, however, since it's unreadable when you just paste it in like that. If you edit your post(s), you can use the little "C" icon in the edit bar to open up a dialog which will let you paste the code in and have the formatting (whitespace, indentation, etc) preserved. Then there's a better chance someone else will actually take the time to read it and help.

 

Edit: perfect! Thanks and good luck. :-)


Peter Hansen -- (BB10 and dev-related blog posts at http://peterhansen.ca.)
Author of White Noise and Battery Guru for BB10 and for PlayBook | Get more from your battery!
Please use plain text.
BlackBerry Development Advisor (Retired)
gbeukeboom
Posts: 2,559
Registered: ‎10-16-2009
My Device: BlackBerry Z10
My Carrier: Bell

Re: Blackberry push notification

Have you debugged the client? Is the registration successful?

 

Is the client a real device or simulator?

Does the client have a valid BlackBerry Data Plan?

Garett
@garettBeuk
--
Goodbye everybody!
Please use plain text.
New Contributor
dev3
Posts: 5
Registered: ‎08-27-2013
My Device: blackberry curve 9360
My Carrier: 96171016127

Re: Blackberry push notification

Hello,

 

I am debuging it on blackberry curve 9360 device i am using dataplan (3g) also i have try the wifi when calling the first url :smileysad:http://pushapi.eval.blackberry.com/mss/PD_subReg?serviceid=xxxx-xxxxxx&osversion=xxxxxxx&model=xxx)
it return <html></html> only on wifi and on mobile internet return time out request . so i am not able to register the device for push .

Please use plain text.
BlackBerry Development Advisor (Retired)
gbeukeboom
Posts: 2,559
Registered: ‎10-16-2009
My Device: BlackBerry Z10
My Carrier: Bell

Re: Blackberry push notification

Does your data plan include BlackBerry data specifically? Does your home screen display a BlackBerry logo next to the radio? Does your device have '3g' or '3G'?

 

It also appears you are missing some suffixes for your connection string, do you have a device-side parameter appended?

Garett
@garettBeuk
--
Goodbye everybody!
Please use plain text.
New Contributor
dev3
Posts: 5
Registered: ‎08-27-2013
My Device: blackberry curve 9360
My Carrier: 96171016127

Re: Blackberry push notification

Thanks a lot for your reply ,

I was using A 3G plan that does not include BlackBerry data specifically and the BlackBerry logo next to the radio was not appearing when i have change the plan it work well.

Please use plain text.