The Notifications REST API is accessible using HTTPS. The initHttpsClient method creates an HTTPS client, which is used to execute the HTTP requests:
private void initHttpsClient() { Scheme httpScheme = new Scheme("https", SSLSocketFactory.getSocketFactory(), 443); SchemeRegistry sr = new SchemeRegistry(); sr.register(httpScheme); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr); client = new DefaultHttpClient(cm, params); Credentials creds = new UsernamePasswordCredentials(serviceId, serviceSecret); client.getCredentialsProvider().setCredentials(new AuthScope("alpha.one.ovi.com", 443, AuthScope.ANY_REALM), creds); }
The following code example shows how the expected parameters are parsed from the command-line parameters.
private static Map<String, String> parseArguments(String[] args) throws Exception { Map<String, String> parameters = new HashMap<String, String>(); for (String arg : args) { String[] parameter = arg.split(":"); if (parameter.length != 2) { throw new IllegalArgumentException("Argument in wrong format: " + arg); } parameters.put(parameter[0].toLowerCase(), parameter[1]); } //Check that the required arguments are found. if (!parameters.containsKey("payload") || !parameters.containsKey("service_id") || !parameters.containsKey("service_secret") || !parameters.containsKey("nid")) { throw new IllegalArgumentException(MANDATORY_PARAMETER_MISSING); } return parameters; }
When the required parameters are parsed, the service can then send the notification to the client application using the Notifications REST API. The sendNotificationWithNotificationId is used when the recipient is specified with the Notification ID. The sendHttpPost method then creates the HTTP request and sends it to the REST API.
private void sendNotificationWithNotificationId(String payload, String nid) { //Notification ID must be URL encoded String encodedNid; try { encodedNid = URLEncoder.encode(nid, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Notification ID URL encoding failed:" + e.getMessage()); } sendHttpPost(new ArrayList<NameValuePair>(), REST_API_BASE_URI + "nid/" + encodedNid); } private void sendHttpPost(List<NameValuePair> headerParameters, String requestUri) { //Create the HTTP POST Request HttpPost httpPost = new HttpPost(requestUri.toString()); try { httpPost.setEntity(new UrlEncodedFormEntity(headerParameters, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Encoding error while converting HTTP parameters to UTF-8.", e); } //Push the notification with HTTPS client try { HttpResponse response = client.execute(httpPost); System.out.println("HTTP Response from Notifications API: " + response.getStatusLine().getStatusCode()); if (response.getEntity() != null) { response.getEntity().consumeContent(); } } catch (IOException e) { throw new RuntimeException("HTTP POST Request to " + requestUri.toString() + " failed with error: " + e.getMessage()); } }
Now that all the functions required to send notifications are defined, the actual service application is run with the main method. The main method parses the arguments, creates an instance of the MyService class, and pushes the notifications to the client application. The main method then calls sendNotificationWithNotificationId for sending the notification.
public static void main(String[] args) { try { //Arguments must be given to push the notifications. if (args.length == 0) { throw new IllegalArgumentException(MANDATORY_PARAMETER_MISSING); } //Parse command-line arguments Map<String, String> parameters = parseArguments(args); //Create service instance MyService service = new MyService(parameters.get("service_id"), parameters.get("service_secret")); //Push the notifications to the client application. By default one notification is sent but with count parameter the amount can be configured. int notificationAmount = parameters.get("count") == null ? 1 : Integer.valueOf(parameters.get("count")); for (int sent = 0; sent < notificationAmount; sent++) { service.sendNotificationWithNotificationId(parameters.get("payload"), parameters.get("nid")); } service.shutdownConnection(); } catch (Exception ex) { ex.printStackTrace(); } System.exit(0); }
Note that the MyService class stores the service_id and service_secret parameters and initiates the HTTPS client:
public MyService(String serviceId, String serviceSecret) throws Exception { this.serviceId = serviceId; this.serviceSecret = serviceSecret; initHttpsClient();
Now that the example service source code is ready, you can compile the application. The first step is to download the following files. Download the JAR files and the MyService.java file to the same directory if you want to use the example commands. Otherwise, you must configure the Java environment variables correctly.
Apache libraries:
httpmime-4.0.1.jar (Included in the httpclient-4.0.1 package)
The httpclient-4.0.1.jar and httpmime-4.0.1.jar files can be found in the httpcomponents-client.-4.0.1-bin package under the lib directory. httpcore-4.0.1.jar is located in the httpcomponents-core-4.0.1-bin package in the lib directory. Download the binary package type suited to your development environment.
The Java SDK must be installed and configured in the class path before you can compile the example MIDlet.
javac -cp .;httpclient-4.0.1.jar;apache-mime4j-0.ient-4.0.1.jar;commons-codec-1.3.jar;commons-logging-1.1.1.jar;httpcore-4.0.1.jar;httpmime-4.0.1.jar MyService.java
The MyService.class file should now be available in the directory.