<div class="col-md-10 lo-main-pane ng-scope">
    <div class="row">
        <div class="lo-content-area col-md-12">
            <div ups-breadcrumb/>

            <h1>Example:
                <span ng-hide="variantType != 'send'">Sending push notifications</span>
                <span ng-show="variantType != 'send'">Register devices for receiving notifications</span>
            </h1>

            <p ng-hide="variantType != 'send'">Make your backend server send push notifications through this UnifiedPush Server.</p>

            <p ng-show="variantType != 'send'">Use the code snippet bellow to register your device and allow it to receiving notifications through this UnifiedPush Server.</p>

            <tabset class="ups-code-examples">
                <tab heading="Simple push" ng-hide="variantType != 'simplePush'" active="tab('simplePush').active">
                    <div class="ups-code-block js" hljs compile="true">
(function() {
     var endpoint, endpointRequest, SPClient, UPClient;

     // config params for UnifiedPush server
     var variantId = "{{ variant.variantID }}";
     var variantSecret = "{{ variant.secret }}";
     var unifiedPushUrl = "{{ currentLocation }}";

      // If your SimplePush Server is running on Openshift, the URL is {{ simplePushUrl() }}
      // If your SimplePush Server is using Mozilla's network, the URL will be wss://push.services.mozilla.com
      // or do you run a custom server?
     var simplePushUrl = "[URL of the SimplePush Server you are using]";

      // create the 'UnifiedPush' client object:
     UPClient = AeroGear.UnifiedPushClient(variantId, variantSecret, unifiedPushUrl);

     // onConnect callback function called when SimplePush
     // successfully establishes connection to the server
     function spConnect() {

         // use 'PushManager' to request a new PushServer URL endpoint for 'Mail' notifications:
         endpointRequest = navigator.push.register();
          // the DOMRequest returns 'successfully':
         endpointRequest.onsuccess = function( event ) {
             // extract the endpoint object from the event:
             endpoint = event.target.result;

             // if it is the first registration, need to register
             // the 'pushEndpoint' with the UnifiedPush server.
             if ( endpoint ) {
                 // assemble the metadata for registration with the UnifiedPush server
                 var metadata = {
                     deviceToken: endpoint
                 };

                 var settings = {
                     success: function() {
                        //success handler
                     },
                     error: function() {
                        //error handler
                     }
                 };

                 settings.metadata = metadata;

                 // register with the server
                 UPClient.registerWithPushServer(settings);
             } else {
                 console.log("'Endpoint' was already registered!");
             }
         };
         // set the notification handler:
         navigator.setMessageHandler( "push", function( message ) {
             if ( message.pushEndpoint === endpoint ) {
                 // let's react on the endpoint
             }
         });
     }

     // onClose callback function:
     function spClose() {
         // handle onclose - e.g. allow reconnect
     }

     SPClient = AeroGear.SimplePushClient({
         simplePushServerURL: simplePushUrl,
         onConnect: spConnect,
         onClose: spClose
    });
 })();
                    </div>
                </tab>
                <tab heading="Chrome" ng-hide="variantType != 'chrome'" active="tab('chrome').active">
                    <div class="ups-code-block js" hljs compile="true">
chrome.pushMessaging.getChannelId( true, function(channelId) {
    /*
        Set our Variant ID and Secret and the location of the UnifiedPush Server
    */
    var variantId = "{{ variant.variantID }}",
        variantSecret = "{{ variant.secret }}",
        pushServerURL = "{{ currentLocation }}";

    // Once we have the channelID we can then register with the UnifiedPush Server using
    // the AeroGear.js library
    var client = AeroGear.UnifiedPushClient(
            variantId,
            variantSecret,
            pushServerURL
        ),settings = {};
        // The channelId will be the "device token"

    settings.metadata = {
        deviceToken: channelId.channelId
    };

    // Register with the UnifiedPush Server
    client.registerWithPushServer( settings );

});
                    </div>
                </tab>
                <tab heading="Android" ng-hide="variantType != 'android'" active="tab('android').active" ng-click="tab('android').active = true">
 <div class="ups-code-block java" hljs compile="true">
package com.push.pushapplication;

import java.net.URI;
import java.net.URISyntaxException;

import org.jboss.aerogear.android.unifiedpush.PushConfig;
import org.jboss.aerogear.android.unifiedpush.PushRegistrar;
import org.jboss.aerogear.android.unifiedpush.Registrations;

import android.app.Application;

public class PushApplication extends Application {

    private final String VARIANT_ID       = "{{ variant.variantID }}";
    private final String SECRET           = "{{ variant.secret }}";
    private final String GCM_SENDER_ID    = "{{ variant.projectNumber }}";
    private final String UNIFIED_PUSH_URL = "{{ currentLocation }}";

    private PushRegistrar registration;

    @Override
    public void onCreate() {
        super.onCreate();

        Registrations registrations = new Registrations();

        try {
            PushConfig config = new PushConfig(new URI(UNIFIED_PUSH_URL), GCM_SENDER_ID);
            config.setVariantID(VARIANT_ID);
            config.setSecret(SECRET);
            config.setAlias(MY_ALIAS);

            registration = registrations.push("unifiedpush", config);

            registration.register(getApplicationContext(), new Callback() {
                private static final long serialVersionUID = 1L;

                @Override
                public void onSuccess(Void ignore) {
                     Toast.makeText(MainActivity.this, "Registration Succeeded!",
                             Toast.LENGTH_LONG).show();
               }

               @Override
               public void onFailure(Exception exception) {
                     Log.e("MainActivity", exception.getMessage(), exception);
               }
            });

        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}
</div>
                </tab>
                <tab heading="iOS - Objective-C" ng-hide="variantType != 'ios'" active="tab('ios').active" ng-click="tab('ios').active = true">
                    <div class="ups-code-block" hljs compile="true" language="objectivec" include="'objectivec'"></div>
                    <script type="text/ng-template" id="objectivec">
- (void)application:(UIApplication *)application
 didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
   NSLog(@"APNS Success");

   AGDeviceRegistration *registration =
     [[AGDeviceRegistration alloc] initWithServerURL:
        [NSURL URLWithString:@"{{ currentLocation }}"]];

   [registration registerWithClientInfo:^(id clientInfo) {
     
     // apply the token, to identify this device
     [clientInfo setDeviceToken:deviceToken];

     [clientInfo setVariantID:@"{{ variant.variantID }}"];
     [clientInfo setVariantSecret:@"{{ variant.secret }}"];

     // --optional config--
     // set some 'useful' hardware information params
     UIDevice *currentDevice = [UIDevice currentDevice];
     [clientInfo setOperatingSystem:[currentDevice systemName]];
     [clientInfo setOsVersion:[currentDevice systemVersion]];
     [clientInfo setDeviceType: [currentDevice model]];

     } success:^() {
       NSLog(@"UPS registration worked");

     } failure:^(NSError *error) {
       NSLog(@"UPS registration Error: %@", error);
   }];
 }
                  </script>

                </tab>
                <tab heading="iOS - Swift" ng-hide="variantType != 'ios'" active="tab('iOSSwift').active" ng-click="tab('iOSSwift').active = true">
                    <div class="ups-code-block" hljs compile="true" language="objectivec" include="'swift'"></div>
                    <script type="text/ng-template" id="swift">
func application(application: UIApplication!, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData!) {
    println("APNS Success")

    let registration = AGDeviceRegistration(serverURL: NSURL(string: "{{ currentLocation }}"))

    registration.registerWithClientInfo({ (clientInfo: AGClientDeviceInformation!)  in
        
        // apply the token, to identify this device
        clientInfo.deviceToken = deviceToken

        clientInfo.variantID = "{{ variant.variantID }}"
        clientInfo.variantSecret = "{{ variant.secret }}"

        // --optional config--
        // set some 'useful' hardware information params
        let currentDevice = UIDevice()        
        clientInfo.operatingSystem = currentDevice.systemName
        clientInfo.osVersion = currentDevice.systemVersion
        clientInfo.deviceType = currentDevice.model

    }, success: {
        println("UPS registration worked");

    }, failure: { (error:NSError!) -> () in
        println("UPS registration Error: \(error.localizedDescription)")
    })
}
                    </script>

                </tab>
                <tab heading="Cordova" ng-hide="variantType == 'chrome' || variantType == 'simplePush' || variantType == 'send'"
                     active="tab('cordova').active" ng-click="tab('cordova').active = true">
                    <div class="ups-code-block js" hljs compile="true">
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        var pushConfig = {
           pushServerURL: "{{ currentLocation }}",
           {{variant.type}}: {
              {{ projectNumber(variant) }}
              variantID: "{{ variant.variantID }}",
              variantSecret: "{{ variant.secret }}"
           }
        };
        push.register(app.onNotification, successHandler, errorHandler, pushConfig);

        function successHandler() {
            console.log('success')
        }

        function errorHandler(message) {
            console.log('error ' + message);
        }
    },
    onNotification: function(event) {
        alert(event.alert);
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

app.initialize();
                    </div>
<br>
<p ng-show="variantType != 'send'">It's also possible to use an external config file named <b>push-config.json</b> and placed in the root of your <b>www</b> folder :</p>
<br>
                    <div class="ups-code-block">
<pre>
<code>
// ../www/push-config.json
{
  "pushServerURL": "{{ currentLocation }}",
  "{{variant.type}}" : {
    {{ projectNumberJson(variant) }}
    "variantID": "{{ variant.variantID }}",
    "variantSecret": "{{ variant.secret }}"
  }
}
</code>
</pre>
                    </div>
<br>
And then :
<br>
                   <div class="ups-code-block js" hljs compile="true">
var app = {
  // Application Constructor
  initialize: function() {
      this.bindEvents();
  },
  // Bind Event Listeners
  //
  // Bind any events that are required on startup. Common events are:
  // 'load', 'deviceready', 'offline', and 'online'.
  bindEvents: function() {
      document.addEventListener('deviceready', this.onDeviceReady, false);
  },
  // deviceready Event Handler
  //
  // The scope of 'this' is the event. In order to call the 'receivedEvent'
  // function, we must explicitly call 'app.receivedEvent(...);'
  onDeviceReady: function() {
      app.receivedEvent('deviceready');
      push.register(app.onNotification, successHandler, errorHandler);

      function successHandler() {
          console.log('success')
      }

      function errorHandler(message) {
          console.log('error ' + message);
      }
  },
  onNotification: function(event) {
      alert(event.alert);
  },
  // Update DOM on a Received Event
  receivedEvent: function(id) {
      var parentElement = document.getElementById(id);
      var listeningElement = parentElement.querySelector('.listening');
      var receivedElement = parentElement.querySelector('.received');

      listeningElement.setAttribute('style', 'display:none;');
      receivedElement.setAttribute('style', 'display:block;');

      console.log('Received Event: ' + id);
  }
};

app.initialize();
                    </div>

                </tab>

                <tab heading="Sending" ng-hide="variantType != 'send'" active="tab('send').active" ng-click="tab('send').active = true">
                    <div class="ups-code-block java" hljs compile="true">
JavaSender defaultJavaSender = new SenderClient.Builder("{{ currentLocation }}").build();
UnifiedMessage unifiedMessage = new UnifiedMessage.Builder()
        .pushApplicationId("{{ applicationId }}")
        .masterSecret("{{ application.masterSecret }}")
        .alert("Hello from Java Sender API!")
        .build();
defaultJavaSender.send(unifiedMessage, new MessageResponseCallback() {

    @Override
    public void onComplete(int statusCode) {
        //do cool stuff
    }

    @Override
    public void onError(Throwable throwable) {
        //bring out the bad news
    }
});
                    </div>
                </tab>
            </tabset>
        </div>
    </div>
</div>
