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
Developer
bert2002
Posts: 172
Registered: ‎05-01-2010
My Device: Z10

Re: Push API sample code needed

Great. Thanks for the fast reply. Now I will figure out how to get the registration done in an widget  :smileyvery-happy:



----------------------------------------------------------
find my widgets -> http://blackberry.itbert.de
Regular Visitor
gmurciam
Posts: 1
Registered: ‎08-03-2010
My Device: Not Specified

Re: Push API sample code needed

Im not sure if anyone still needs any code, but this is working code for j2se

 

 

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 userid:password encode, http://bit.ly/diYQUr enter 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");
		v.add("87654321");
		v.add("12345678");
		v.add("87654321");
		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");
		}
		
	}
	*/
}

 

 

It works pretty well so far

Visitor
shashika
Posts: 1
Registered: ‎08-04-2010
My Device: Not Specified

Re: Push API sample code needed

Hi,

 

I tried this code.

 

I get connection.getResponseCode()=200 and connection.getResponseMessage()=OK

 

But I don't receive anything in inputstream

BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));

It gives me null value and message is not sent to device

 

what could be exact issue that inputstream object has null value.

 

Thanks,

shashika

 

 

 

Regular Contributor
rahul_kalidindi
Posts: 67
Registered: ‎06-30-2010
My Device: Storm 9550

Re: Push API sample code needed

Hi,

 

I want to know how to use Application id and Push port in the client application. Most of the code in this thread is for the server side. Can i get client side sample that uses the application id and push port credentials.I looked at http push demo client app but it doesnt use these credentials. I registered with BIS and got these credentials...

 

So can anyone please help me out.

New Contributor
mehedi
Posts: 2
Registered: ‎09-21-2010
My Device: Not Specified

Re: Push API sample code needed

Hi Bullety,

 

I am trying to develop a push initiator using ruby on rails.  php and java codes works but the ruby script is not working but I am getting the response code 200 and doing the same thing.

 

Here is my ruby script I am using pap push format:

 

require 'net/http'

require 'net/https'

require 'uri'

require 'rubygems'

require 'restclient'

 

boundary='fghjkklllmnggddcvjjkkm'

push_id=Time.now.to_i.to_s

pin='312acd76'

delivery_method='unconfirmed'

t= Time.now+(60*5)

delivery_before=t.strftime("%Y-%m-%dT%H:%M:%SZ ")

content='very bad ninja'

content_type=%w["Content-Type: multipart/related; boundary=fghjkklllmnggddcvjjkkm;/xml" "Accept: text/html, image/gif, image/jpeg, *;  q=.2, */*; q=.2, Connection: keep-alive", "User-Agent: Hallgren Networks BB Push Server/1.0"]

 

app_id='811-9Bt2yRM15O78M3a8'

pass='fSGBqegc8'

port='20754'

url = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest"

 

data="--#{boundary}

Content-Type: application/xml; charset=UTF-8

<?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-message push-id='#{push_id}' deliver-before-timestamp='#{delivery_before}' source-reference='#{app_id}'>

    <address address-value='#{pin}'/>

    <quality-of-service delivery-method='#{delivery_method}'/>

  </push-message>

</pap>

--#{boundary}\n

Content-Type: text/html\n\n

Push-Message-ID:#{push_id}\n\n#{content}\n\n--#{boundary}--"

 

response = RestClient::Request.execute(:method => :smileytongue:ost,

  :url => url,

  :smileytongue:ayload => data,

  :headers=>{

    :content_type=> content_type,

    :user_agent=> "User-Agent: Hallgren Networks BB Push Server/1.0"},

  :user=>app_id,

  :smileytongue:assword=>pass,

  :smileytongue:ort=> port)

 

puts data

puts response.code

puts response

 

Above code sends the following pap message:

 

--fghjkklllmnggddcvjjkkm

Content-Type: application/xml; charset=UTF-8

<?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-message push-id='1285124936' deliver-before-timestamp='2010-09-22T09:13:56Z ' source-reference='811-9Bt2yRM15O78M3a8'>

    <address address-value='312acd76'/>

    <quality-of-service delivery-method='unconfirmed'/>

  </push-message>

</pap>

--fghjkklllmnggddcvjjkkm

 

Content-Type: text/html

Push-Message-ID:1285124936

 

very bad ninja

 

--fghjkklllmnggddcvjjkkm--

 

 

when I am ruuning the script I am getting the following response:

 

<?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="1285124936" sender-address="http://pushapi.eval.blackberry.com/mss/PD_pushRequest" sender-name="RIM Push-Data Service" reply-time="2010-09-22T03:08:55Z">

      <response-result code="1001" desc="The request has been accepted for processing."></response-result>

   </push-response>

</pap>

 

From the response its look likes push server is receiving my request but is not sending the notifications to device

Please HELP.

New Contributor
agmangas
Posts: 7
Registered: ‎08-20-2010
My Device: Bold 9000 ( Device Software 5.0 )

Re: Push API sample code needed

[ Edited ]

Hello everyone!

 

I just wanted to point out a little problem I encountered when using the PHP code posted by challgren ( many thanks for the code, it´s really usefull :smileyhappy: ), in case there are more people in my situation.

 

When trying to send the push message, I obtained an 'Invalid Document End' error, that was because cURL didn´t know how to handle the site´s SSL certificate.

 

By adding the following line of code before de cURL exec() everything started working:

 

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Hope this helps!

---------------------------------------------------------------
Andres Garcia Mangas
BerryLab Developer berrylab.es
Contributor
yogay2010
Posts: 37
Registered: ‎10-15-2010
My Device: Not Specified

Re: Push API sample code needed

Hi guys!!

 

Could anyone tell me how do i implement the clinet side of the application?

 

 

@chellgren:  you said you figured out the client side application..I got two variaes for client side fromRIM. App ID and Port number??Where do i use them? Could you share you code with us please??

 

Thank you i nadvance.

 

Sam

New Contributor
nickybee
Posts: 2
Registered: ‎01-13-2011
My Device: 9700 + a few others ;)

extending evaluation credentials ?? is it possible ??

excellent stuff @Bullety - thanks for all the explanations and code.

 

soooo annoying though. I mean RIM is almost making it purposely obscure to do this.

We've been through push notifications now on iphone (APNS), android (C2DM - cloud to device messaging - ha ha - google's fancy name for push), symbian (OVI notifications) - and they are all very straightforward to implement.

 

in fact symbian even has a developer facing http accessible area for testing client side implementations separately (i.e. a web interface for "sending" push messages") - RIM appears to be doing all this as an afterthought.

 

Anyway - I had one quick question. I applied for evaluation credentials from RIM and received them. However we didn't get around to re-visiting push notifications until last week - and of course the evaluation had expired by then. I tried to get an extension - but no way to do this that I could see - and no reply from RIM by email when I asked.

So I tried to apply for another set of credentials....

this worked - I received a response about 36 hours later (automated) - containing a whole new set of app ID etc etc - however I used the SAME EMAIL for the 2nd request.

 

I cannot login to the Push Service Evaluation portal with the new details.

 

So basically I'm stuck - the old credentials have timed out. The new credentials do not allow me to login.

 

Anyone got any ideas ??

 

I decided to try to apply for a 3rd set of credentials - this time using a different email address to see if that fixes it. Shame I couldn't just get an extension on the original credentials.

 

Nick

New Contributor
nickybee
Posts: 2
Registered: ‎01-13-2011
My Device: 9700 + a few others ;)

Re: extending evaluation credentials ?? is it possible ??

actually just to clarify...

 

the SECOND email I got from RIM with credentials is not actually entirely new credentials

 

it's a new Portal Password but same APPid and same Port Number.

 

however when I login to portal account I can only use the old password - which shows me the old -expired - account. So something seems to have gotten confused in the RIM accounts database.

 

Yet again - it would be nice if RIM had a web-accessible thing that would mimic API access so we could all collectively try typing in our APPid/password details to throw pushes to our registered devices...

 

anyway - if anyone knows which user on the support forum I should ask about this - by all means let me know

Visitor
aichholzer
Posts: 1
Registered: ‎03-24-2011
My Device: Torch

Re: Push API sample code needed

Hey Challgren,

 

Its been a while since you posted the code below, which seems to work just fine. I have created a sample form that submits a sample message to the Blackberry server, I get a response telling me the request has been accepted and all fine. I am submitting the message to a couple of PIN numbers. Question is; the messages never get to the devices... Do you have any idea on what else needs to be done?

 

I have read that the sample applciation (registered at BB) needs to be registered to accept messaged in order to forward those to the devices, but I cant find any details on it.

 

Could you please help me out a little?

Thank you