Just a second...

Example: Send a request message to the Push Notification Bridge

The following examples use the API to send a request message on a topic path to communicate with the Push Notification Bridge. The request message is in JSON and can be used to subscribe or unsubscribe from receiving push notifications when specific topics are updated.

Objective-C
                            //  Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples
//
//  Copyright (C) 2016, 2017 Push Technology Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

//** The default path at which the Push Notification Bridge listens for messaging
#define SERVICE_PATH @"push/notifications"

#import "MessagingToPushNotificationBridgeExample.h"

@import Diffusion;

@implementation MessagingToPushNotificationBridgeExample {
    PTDiffusionSession* _session;
}

-(void)startWithURL:(NSURL*)url {
    NSLog(@"Connecting...");

    [PTDiffusionSession openWithURL:url
                  completionHandler:^(PTDiffusionSession *session, NSError *error)
    {
        if (!session) {
            NSLog(@"Failed to open session: %@", error);
            return;
        }

        // At this point we now have a connected session.
        NSLog(@"Connected.");

        // Set ivar to maintain a strong reference to the session.
        _session = session;

        // An example APNs device token
        unsigned char tokenBytes[] =
           {0x5a, 0x88, 0x3a, 0x57, 0xe2, 0x89, 0x77, 0x84,
            0x1d, 0xc8, 0x1a, 0x0a, 0xa1, 0x4e, 0x2f, 0xdf,
            0x64, 0xc6, 0x5a, 0x8f, 0x7b, 0xb1, 0x9a, 0xa1,
            0x6e, 0xaf, 0xc3, 0x16, 0x13, 0x18, 0x1c, 0x97};
        NSData *const deviceToken =
            [NSData dataWithBytes:(void *)tokenBytes length:32];

        [self doPnSubscribe:@"some/topic/name" deviceToken:deviceToken];
    }];
}

/**
 * Compose a URI understood by the Push Notification Bridge from an APNs device token.
 * @param deviceID APNS device token.
 * @return string in format expected by the push notification bridge.
 */
-(NSString*)formatAsURI:(NSData*)deviceID {
    NSString *const base64 = [deviceID base64EncodedStringWithOptions:0];
    return [NSString stringWithFormat:@"apns://%@", base64];
}

/**
 * Compose and send a subscription request to the Push Notification bridge
 * @param topicPath Diffusion topic path subscribed-to by the Push Notification Bridge.
 */
- (void)doPnSubscribe:(NSString*) topicPath deviceToken:(NSData*)deviceToken {
    // Compose the JSON request from Obj-C literals
    NSDictionary *const requestDict = @{
      @"pnsub": @{
        @"destination": [self formatAsURI:deviceToken],
        @"topic": topicPath
    }};

    // Build a JSON request from that
    PTDiffusionJSON *const json =
        [[PTDiffusionJSON alloc] initWithObject:requestDict error:nil];

    [_session.messaging sendRequest:json.request
                             toPath:SERVICE_PATH
              JSONCompletionHandler:^(PTDiffusionJSON *json, NSError *error)
    {
        if (error) {
            NSLog(@"Send to \"%@\" failed: %@", SERVICE_PATH, error);
        } else {
            NSLog(@"Response: %@", json);
        }
    }];
}

@end
                        
Swift
                        //  Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples
//
//  Copyright (C) 2017 Push Technology Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

import Foundation
import Diffusion

class MessagingToPushNotificationBridgeExample {
    static let servicePath = "push/notifications"
    var session: PTDiffusionSession?

    func startWithURL(url: NSURL) throws {
        print("Connecting...")

        PTDiffusionSession.open(with: url as URL) { (session, error) -> Void in
            if session == nil {
                print("Failed to open session: \(error!)")
                return
            }

            // At this point we now have a connected session.
            print("Connected")

            // Set ivar to maintain a strong reference to the session.
            self.session = session

            // An example APNs device token

            let tokenBytes:[UInt8] = [0x5a, 0x88, 0x3a, 0x57, 0xe2, 0x89, 0x77, 0x84,
                              0x1d, 0xc8, 0x1a, 0x0a, 0xa1, 0x4e, 0x2f, 0xdf,
                              0x64, 0xc6, 0x5a, 0x8f, 0x7b, 0xb1, 0x9a, 0xa1,
                              0x6e, 0xaf, 0xc3, 0x16, 0x13, 0x18, 0x1c, 0x97]
            let deviceToken = NSData(bytes: tokenBytes, length: 32)

            self.doPnSubscribe(topicPath: "some/topic/path", deviceToken: deviceToken)
        }
    }

    /**
     * Compose a URI understood by the Push Notification Bridge from an APNs device token.
     * @param deviceID APNS device token.
     * @return string in format expected by the push notification bridge.
     */
    func formatAsURI(token:NSData) -> String {
        return String(format:"apns://", token.base64EncodedString())
    }

    func doPnSubscribe(topicPath: String, deviceToken: NSData) {
        // Compose the JSON request from literals
        let requestDict = [
            "pnsub" : [
                "destination": formatAsURI(token: deviceToken),
                "topic": topicPath
            ]
        ]

        // Build a JSON request from that
        let json = try! PTDiffusionJSON(object: requestDict)

        session?.messaging.send(
            json.request,
            toPath: MessagingToPushNotificationBridgeExample.servicePath,
            jsonCompletionHandler: {
            (json, error) -> Void in

            if (nil == json) {
                print("Send to \"\(MessagingToPushNotificationBridgeExample.servicePath)\" failed: \(error!)")
            } else {
                print("Response: \(json!)")
            }
        })
    }
}
                    
Android
                        /*******************************************************************************
 * Copyright (C) 2017 Push Technology Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.pushtechnology.diffusion.examples;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pushtechnology.diffusion.client.Diffusion;
import com.pushtechnology.diffusion.client.features.Messaging;
import com.pushtechnology.diffusion.client.session.Session;
import com.pushtechnology.diffusion.datatype.json.JSON;

/**
 * An example of a client using the 'Messaging' feature to request the Push
 * Notification Bridge subscribe to a topic and relay updates to a GCM
 * registration ID.
 *
 * @author Push Technology Limited
 * @since 5.9
 */
public class ClientSendingPushNotificationSubscription {

    private static final Logger LOG = LoggerFactory
        .getLogger(ClientSendingPushNotificationSubscription.class);

    private final String pushServiceTopicPath;
    private final Session session;
    private final Messaging messaging;

    /**
     * Constructs message sending application.
     *
     * @param pushServiceTopicPath topic path on which the Push Notification
     *        Bridge is taking requests.
     */
    public ClientSendingPushNotificationSubscription(
        String pushServiceTopicPath) {
        this.pushServiceTopicPath = pushServiceTopicPath;
        this.session =
            Diffusion.sessions().principal("client")
                .password("password").open("ws://diffusion.example.com:80");
        this.messaging = session.feature(Messaging.class);
    }

    /**
     * Close the session.
     */
    public void close() {
        session.close();
    }

    /**
     * Compose & send a subscription request to the Push Notification Bridge.
     *
     * @param subscribedTopic topic to which the bridge subscribes.
     * @param gcmRegistrationID GCM registration ID to which the bridge relays
     *        updates.
     * @throws ExecutionException If the Push Notification Bridge cannot process
     *         the request
     * @throws InterruptedException If the current thread was interrupted while
     *         waiting for a response
     */
    public void requestPNSubscription(String gcmRegistrationID,
        String subscribedTopic)
        throws InterruptedException, ExecutionException {

        // Compose the request
        final String gcmDestination = "gcm://" + gcmRegistrationID;
        final JSONObject jsonObject =
            buildSubscriptionRequest(gcmDestination, subscribedTopic);
        final JSON request =
            Diffusion.dataTypes().json().fromJsonString(jsonObject.toString());

        // Send the request
        final CompletableFuture<JSON> response =
            messaging.sendRequest(
                pushServiceTopicPath,
                request,
                JSON.class,
                JSON.class);

        LOG.info("Received response from PN Bridge: {}",
            response.get().toJsonString());
    }

    /**
     * Compose a subscription request.
     * <P>
     *
     * @param destination The {@code gcm://} or {@code apns://} destination for
     *        any push notifications.
     * @param topic Diffusion topic subscribed-to by the Push Notification
     *        Bridge.
     * @return a complete request
     */
    private static JSONObject buildSubscriptionRequest(
        String destination,
        String topic) {

        final JSONObject subObject = new JSONObject();

        subObject
            .put("destination", destination)
            .put("topic", topic);

        final JSONObject contentObj = new JSONObject();
        contentObj.put("pnsub", subObject);

        return contentObj;
    }
}