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

Java Development

Reply
Contributor
ratheesh
Posts: 26
Registered: ‎07-04-2011
My Device: curve 9300

Push Notification using Blackerry push plus (server is php)

[ Edited ]

Hi

 

Iam developing an to implement push notification in blackberry

first i register bb push server with push plus  package and i got a response from RIM

 


Many thanks for your registration with the BlackBerry Push Service!


Credentials have been assigned to your application for the BlackBerry Push Service Evaluation
 
   
Registrant details:
  
Company Name:
********
 
First Name:
*****
 
Last Name:
*******
 
Email:
developer@******s.com
 
   
Login credentials for the Content Provider Admin Portal
 
Portal Address:
 
Portal Username:
developer@************.com
 
Portal Pwd:
**************!
 
   
Configuration properties for the Push Initiator (server application)
 
Name:
*********
 
App ID:
27****************************
 
Pwd:
q*******
 
CPID (Content Provider ID):
2***
 
Start Date (MM/DD/YYYY):
7/13/2012
 
Expiry Date (MM/DD/YYYY):
11/13/2012
 
Service Type:
Plus
 
PPG Base URL**
 
Source IP:
Whitelisting no longer required
 
Usage:
BES & BIS
 
   
*If you are using the BlackBerry Push Service SDK and developing applications that uses the BlackBerry Enterprise Server for delivering content, Username is not required for submitting push requests. 

If a username is required, you need to obtain it from your BlackBerry Enterprise Server administrator.


** For evaluation use only.
 
 
 
 
 
 
 
 
Configuration properties for the push-enabled application (client application)
 
Application Credentials (for use in your client application):
 
Application ID:
2753**********************744
 
PPG Base URL**
 
Push Port:
3*****1
 
   
Note: Server URL uses https while client URL uses http. 

The BlackBerry Push Service SDK and related documentation can be downloaded at www.blackberry.com/developers/pushservice.  

When you have completed your testing and evaluation of the BlackBerry Push Service, please go to www.blackberry.com/developers/pushservice for further instructions to get production credentials for your application.


If you have any questions about the service, here’s where you can get more information:


General information: www.blackberry.com/developers/pushservice

Developer Documentation:  http://docs.blackberry.com/en/developers/?userType=21


Support Forums:  

http://supportforums.blackberry.com/rim/?category.id=BlackBerryDevelopment


Knowledgebase:  

http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/customview.html?func=...


Since Eval is a testing environment for performance purposes we have limited your push capacity to: 


- 2000 Daily Push Quota (Pin Count) (where you will receive a warning)

- 5000 Absolute Daily Push Quota (Pin Count)

- 100 subscribers


Also your Eval account is valid for 4 months. After that you are requested to move to production 


If you want to change any of these parameters please let us know. 


Thanks,


BlackBerry Push Service Management

 

 

 




After that i have made the code for client side by using the sample code provided by simon_hain

package com.isec7.samples;

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.CoverageInfo;
import net.rim.device.api.system.DeviceInfo;

/**
* Registers and receives bis push messages.<br/>
* Based on PushLib43.java found in (standard installtion) <br/>
* C:\Program Files\BPSS\pushsdk\client-sample-app\pushdemo\com\rim\samples\device\push\lib<br/>
* Please note that the registration to your content provider is not included.<br/>
* You have to enter your port and app id, and change the connection suffix<br/>
* Unregister-code is left if needed, but not implemented.<br/>
* It is suggested to replace the sysouts with a real logger service.
*
* @author simon_hain of supportforums.blackberry.com
*/
public class PushAgent {

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 = "your port";
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = "your secret key";
private static final String CONNECTION_SUFFIX = ";deviceside=false;ConnectionType=seekrit string";

private MessageReadingThread messageReadingThread;

/**
* Instantiates a new push agent.
*
*/
public PushAgent() {
// remove the coverage check if compiling for OS < 4.6
if (!CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) {
System.out.println("Error: Coverage not sufficient");
return;
}
if (DeviceInfo.isSimulator()) {
System.out.println("Error: Registration can only be done for real devices");
return;
}
messageReadingThread = new MessageReadingThread();
messageReadingThread.start();
registerBpas();
}

/**
* Thread that processes incoming connections through {@link PushMessageReader}.
*/
private static class MessageReadingThread extends Thread {

private boolean running;
private ServerSocketConnection socket;
private HttpServerConnection conn;
private InputStream inputStream;
private PushInputStream pushInputStream;

/**
* Instantiates a new message reading thread.
*/
public MessageReadingThread() {
this.running = true;
}

/**
* {@inheritDoc}
*
* @see java.lang.Thread#run()
*/
public void run() {
String url = "http://:" + PUSH_PORT + CONNECTION_SUFFIX;
System.out.println("Starting to listen for push messages through '" + url + "'");

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) {
System.out.println("Failed to read push message, caused by " + e.getMessage());
running = false;
}
} finally {
close(conn, pushInputStream, null);
}
}

System.out.println("Stopped listening for push messages");
}

/**
* Stop running.
*/
public void stopRunning() {
running = false;
close(socket, null, null);
}

/**
* On listen error.
*
* @param ex
* the ex
*/
private void onListenError(final Exception ex) {
System.out.println("Failed to open port, caused by " + ex);
}
}

/**
* Safely closes connection and streams.
*
* @param conn
* the conn
* @param is
* the is
* @param os
* the os
*/
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) {
}
}
}

/**
* Form a register request.
*
* @param bpasUrl
* the bpas url
* @param appId
* the app id
* @param token
* the token
* @return the the built request
*/
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();
}

/**
* Form an unregister request.
*
* @param bpasUrl
* the bpas url
* @param appId
* the app id
* @param token
* the token
* @return the built request
*/
private String formUnRegisterRequest(String bpasUrl, String appId, String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subDereg?");
sb.append("serviceid=").append(appId);
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}

/**
* Register to the BPAS.
*/
private void registerBpas() {
final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null) + CONNECTION_SUFFIX;
/**
* As the connection suffix is fixed I just use a Thread to call the connection code
*
**/
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) || USER_ALREADY_SUBSCRIBED.equals(response)) {
System.out.println("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();
}
}

 

onether class for push message reader

 

package com.isec7.samples;

import java.io.ByteArrayInputStream;

import javax.microedition.io.Connection;

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.util.Arrays;

/**
* Source (on standard installation): C:\Program Files\BPSS\pushsdk\client-sample-app\pushdemo\com\rim\samples\device\push <br/>
* Reads incoming push messages and extracts texts and images.
*/
public final class PushMessageReader {

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

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);
// 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 {
PushAgent.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;
}

}

 

after exicuting this code , i got a suceess response from the server  rc=200

 

 

In my server side i use the php as the web server

 

 

i use the following code for php side 

 

 


<?php

// APP ID provided by RIM
$appid = 'PUT YOUR APPID HERE';
// Password provided by RIM
$password = 'PUT YOUR PASSWORD HERE';
// Application device port
$appport = PUT YOUR PORT NUM HERE;

try {
// Message to send :
$message = "Hi welcome to BIS push implementation!!!!!!!";

//Deliver before timestamp
$deliverbefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+1 minutes'));

// An array of address must be in PIN format or "push_all"
// Format = WAPPUSH=PIN%3APORT/TYPE=USER@rim.com

$addresstosendto[] = 'push_all';

$addresses = '';
foreach ($addresstosendto as $value) {
$addresses .= '<address address-value="' . $value . '" />';
}

// create a new cURL resource
$err = false;
$ch = curl_init();
$messageid = microtime(true);

$data = '--asdwewe. "\r\n" .Content-Type: application/xml; charset=UTF-8' . "\r\n\r\n".
'<?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="' . $messageid . '" deliver-before-timestamp="' . $deliverbefore . '" source-reference="' . $appid . '">'
. $addresses .
'<quality-of-service delivery-method="unconfirmed"/>
</push-message>
</pap>' . "\r\n" .
'--asdwewe' . "\r\n" .
'Content-Type: text/plain' . "\r\n" .
//'Content-Encoding: binary'. "\r\n" .
'Push-Message-ID: ' . $messageid . "\r\n\r\n" .
stripslashes($message) . "\r\n" .
'--asdwewe--' . "\r\n";

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://pushapi.eval.blackberry.com/mss/PD_pushRequest");
curl_setopt($ch, CURLOPT_PORT , 443);
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
curl_setopt($ch, CURLOPT_CAINFO, getcwd()."\cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT, "My 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);

$__extra_Headers = array(
"Content-Type: multipart/related; boundary=asdwewe; type=application/xml",
"Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2",
"Connection: keep-alive",
"X-Rim-Push-Dest-Port: ".$appport,
"X-RIM-PUSH-ID: ".$messageid,
"X-RIM-Push-Reliability-Mode: APPLICATION"
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $__extra_Headers);


// grab URL and pass it to the browser
$xmldata = curl_exec($ch);
if($xmldata === false){
echo 'Error pada CURL : ' . curl_error($ch)."\n";
}else{
echo 'Operasi push berhasil'."\n";
}


// 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)."\n";
$err = true;
}
xml_parser_free($p);

echo 'Our PUSH-ID: ' . $messageid . "<br \>\n";
if (!$err && $vals[1]['tag'] == 'PUSH-RESPONSE') {
echo 'PUSH-ID: ' . $vals[1]['attributes']['PUSH-ID'] . "<br \>\n";
echo 'REPLY-TIME: ' . $vals[1]['attributes']['REPLY-TIME'] . "<br \>\n";
echo 'Response CODE: ' . $vals[2]['attributes']['CODE'] . "<br \>\n";
echo 'Response DESC: ' . $vals[2]['attributes']['DESC'] . "<br \> \n";
} else {
echo '<p>An error has occured</p>' . "\n";
echo 'Error CODE: ' . $vals[1]['attributes']['CODE'] . "<br \>\n";
echo 'Error DESC: ' . $vals[1]['attributes']['DESC'] . "<br \>\n";
}


} catch (Exception $e) {
var_dump($e->getMessage());
}

exit();
// ---------------------------------------------------------------------------------------------------------------

?>

 

 

while pushing a data to the BB push server , it returs the response

 

Response DESC: The request has been accepted for processing.

I have given the address value in the php file as  push to all and a specific pin number but the response is same 

 

I want to it is because of the type of the sevice type , i use the push plus not essetial 

if we neeed any payme for push plus , but the RIM does not specify anything in the mail.

 

i tried to use urbain airship , but it need  push essential service 

 

please help me what i did wrong here ?

 

we can implement push service using push plus (with out payment)

why it gives the 1001 error while sending a push to bb server ?

 

Thanks 

Ratheesh CN

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

Contributor
ratheesh
Posts: 26
Registered: ‎07-04-2011
My Device: curve 9300

Re: Push Notification using Blackerry push plus (server is php)

any issues in my php code ?

client side is ok and im getting the correct respnse(200) ?

 

why BB push server not accept any pushes ?