io.starter.messaging.SNSMobilePush.java Source code

Java tutorial

Introduction

Here is the source code for io.starter.messaging.SNSMobilePush.java

Source

package io.starter.messaging;

/*
 * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 * http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file 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 io.starter.messaging.tools.AmazonSNSClientWrapper;
import io.starter.messaging.tools.NotificationMessageGenerator.Platform;
import io.starter.util.SystemConstants;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.model.MessageAttributeValue;

public class SNSMobilePush implements SystemConstants {

    private AmazonSNSClientWrapper snsClientWrapper;

    public SNSMobilePush(AmazonSNS snsClient) {
        this.snsClientWrapper = new AmazonSNSClientWrapper(snsClient);

    }

    public SNSMobilePush() throws IOException {
        this(getSNS());
    }

    private static AmazonSNS getSNS() throws IOException {
        String awsAccessKey = System.getProperty("AWS_ACCESS_KEY_ID"); // "YOUR_AWS_ACCESS_KEY";
        String awsSecretKey = System.getProperty("AWS_SECRET_KEY"); // "YOUR_AWS_SECRET_KEY";

        if (awsAccessKey == null)
            awsAccessKey = AWS_ACCESS_KEY;
        if (awsSecretKey == null)
            awsSecretKey = AWS_SECRET_KEY;

        AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
        AmazonSNS sns = new AmazonSNSClient(credentials);

        sns.setEndpoint("https://sns.us-west-2.amazonaws.com");
        return sns;
    }

    public static final Map<Platform, Map<String, MessageAttributeValue>> attributesMap = new HashMap<Platform, Map<String, MessageAttributeValue>>();
    static {
        attributesMap.put(Platform.ADM, null);
        attributesMap.put(Platform.GCM, null);
        attributesMap.put(Platform.APNS, null);
        attributesMap.put(Platform.APNS_SANDBOX, null);
        attributesMap.put(Platform.BAIDU, addBaiduNotificationAttributes());
        attributesMap.put(Platform.WNS, addWNSNotificationAttributes());
        attributesMap.put(Platform.MPNS, addMPNSNotificationAttributes());
    }

    public static void main(String[] args) throws IOException {
        /*
         * TODO: Be sure to fill in your AWS access credentials in the
         * AwsCredentials.properties file before you try to run this sample.
         * http://aws.amazon.com/security-credentials
         */

        String awsAccessKey = System.getProperty("AWS_ACCESS_KEY_ID"); // "YOUR_AWS_ACCESS_KEY";
        String awsSecretKey = System.getProperty("AWS_SECRET_KEY"); // "YOUR_AWS_SECRET_KEY";

        if (awsAccessKey == null)
            awsAccessKey = AWS_ACCESS_KEY;
        if (awsSecretKey == null)
            awsSecretKey = AWS_SECRET_KEY;

        AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);

        AmazonSNS sns = new AmazonSNSClient(
                new PropertiesCredentials(SNSMobilePush.class.getResourceAsStream("AwsCredentials.properties")));

        // AmazonSNS sns = new AmazonSNSClient(credentials);

        sns.setEndpoint("https://sns.us-west-2.amazonaws.com");
        System.out.println("===========================================\n");
        System.out.println("Initializing Communication with Amazon SNS");
        System.out.println("===========================================\n");
        try {
            SNSMobilePush sample = new SNSMobilePush(sns);
            /* TODO: Uncomment the services you wish to use. */
            // sample.starterAndroidAppNotification();
            // sample.starterKindleAppNotification();
            sample.starterAppleAppNotification();
            // sample.starterAppleSandboxAppNotification();
            // sample.starterBaiduAppNotification();
            // sample.starterWNSAppNotification();
            // sample.starterMPNSAppNotification();
        } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException, which means your request made it "
                    + "to Amazon SNS, but was rejected with an error response for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with SNS, such as not "
                    + "being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());
        }
    }

    public void starterAndroidAppNotification() {
        // TODO: Please fill in following values for your application. You can
        // also change the notification payload as per your preferences using
        // the method
        // com.amazonaws.sns.samples.tools.NotificationMessageGenerator.getSampleAndroidMessage()
        String serverAPIKey = "";
        String applicationName = "";
        String registrationId = "";
        snsClientWrapper.starterNotification(Platform.GCM, "", serverAPIKey, registrationId, applicationName,
                attributesMap, null);
    }

    public void starterKindleAppNotification() {
        // TODO: Please fill in following values for your application. You can
        // also change the notification payload as per your preferences using
        // the method
        // com.amazonaws.sns.samples.tools.NotificationMessageGenerator.getSampleKindleMessage()
        String clientId = "";
        String clientSecret = "";
        String applicationName = "";

        String registrationId = "";
        snsClientWrapper.starterNotification(Platform.ADM, clientId, clientSecret, registrationId, applicationName,
                attributesMap, null);
    }

    public void starterAppleAppNotification() {
        // TODO: Please fill in following values for your application. You can
        // also change the notification payload as per your preferences using
        // the method
        // com.amazonaws.sns.samples.tools.NotificationMessageGenerator.getSampleAppleMessage()
        String certificate = "-----BEGIN CERTIFICATE-----\n" + "-----END CERTIFICATE-----\n";

        String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n"
                + "dTw3PM/t6GrTISNM3DzaaBv52d8pceI5oh6o+lNafohaeeBjdZEy\n" + "-----END RSA PRIVATE KEY-----\n";

        String applicationName = "StarterPush";

        String deviceToken = "f7a004910d68ad275039e69a388b56c73601b67d4837c46dc2dd60eb7100557c";

        // This is 64 hex characters.
        snsClientWrapper.starterNotification(Platform.APNS, certificate, privateKey, deviceToken, applicationName,
                attributesMap, null);
    }

    public void starterAppleSandboxAppNotification() {
        // TODO: Please fill in following values for your application. You can
        // also change the notification payload as per your preferences using
        // the method
        // com.amazonaws.sns.samples.tools.NotificationMessageGenerator.getSampleAppleMessage()
        String certificate = "-----BEGIN CERTIFICATE-----\n" + "-----END CERTIFICATE-----\n";

        String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" + "-----END RSA PRIVATE KEY-----\n";

        String applicationName = "Starter";

        String deviceToken = "f7a004910d68ad275039e69a388b56c73601b67d4837c46dc2dd60eb7100557c";

        snsClientWrapper.starterNotification(Platform.APNS_SANDBOX, certificate, privateKey, deviceToken,
                applicationName, attributesMap, null);
    }

    public void starterBaiduAppNotification() {
        /*
         * TODO: Please fill in the following values for your application. If
         * you wish to change the properties of your Baidu notification, you can
         * do so by modifying the attribute values in the method
         * addBaiduNotificationAttributes() . You can also change the
         * notification payload as per your preferences using the method
         * com.amazonaws
         * .sns.samples.tools.NotificationMessageGenerator.getSampleBaiduMessage
         * ()
         */
        String userId = "";
        String channelId = "";
        String apiKey = "";
        String secretKey = "";
        String applicationName = "";
        snsClientWrapper.starterNotification(Platform.BAIDU, apiKey, secretKey, channelId + "|" + userId,
                applicationName, attributesMap, null);
    }

    public void starterWNSAppNotification() {
        /*
         * TODO: Please fill in the following values for your application. If
         * you wish to change the properties of your WNS notification, you can
         * do so by modifying the attribute values in the method
         * addWNSNotificationAttributes() . You can also change the notification
         * payload as per your preferences using the method
         * com.amazonaws.sns.samples
         * .tools.NotificationMessageGenerator.getSampleWNSMessage()
         */
        String notificationChannelURI = "";
        String packageSecurityIdentifier = "";
        String secretKey = "";
        String applicationName = "";
        snsClientWrapper.starterNotification(Platform.WNS, packageSecurityIdentifier, secretKey,
                notificationChannelURI, applicationName, attributesMap, null);
    }

    public void starterMPNSAppNotification() {
        /*
         * TODO: Please fill in the following values for your application. If
         * you wish to change the properties of your MPNS notification, you can
         * do so by modifying the attribute values in the method
         * addMPNSNotificationAttributes() . You can also change the
         * notification payload as per your preferences using the method
         * com.amazonaws
         * .sns.samples.tools.NotificationMessageGenerator.getSampleMPNSMessage
         * ()
         */
        String notificationChannelURI = "";
        String applicationName = "";
        snsClientWrapper.starterNotification(Platform.MPNS, "", "", notificationChannelURI, applicationName,
                attributesMap, null);
    }

    private static Map<String, MessageAttributeValue> addBaiduNotificationAttributes() {
        Map<String, MessageAttributeValue> notificationAttributes = new HashMap<String, MessageAttributeValue>();
        notificationAttributes.put("AWS.SNS.MOBILE.BAIDU.DeployStatus",
                new MessageAttributeValue().withDataType("String").withStringValue("1"));
        notificationAttributes.put("AWS.SNS.MOBILE.BAIDU.MessageKey",
                new MessageAttributeValue().withDataType("String").withStringValue("default-channel-msg-key"));
        notificationAttributes.put("AWS.SNS.MOBILE.BAIDU.MessageType",
                new MessageAttributeValue().withDataType("String").withStringValue("0"));
        return notificationAttributes;
    }

    private static Map<String, MessageAttributeValue> addWNSNotificationAttributes() {
        Map<String, MessageAttributeValue> notificationAttributes = new HashMap<String, MessageAttributeValue>();
        notificationAttributes.put("AWS.SNS.MOBILE.WNS.CachePolicy",
                new MessageAttributeValue().withDataType("String").withStringValue("cache"));
        notificationAttributes.put("AWS.SNS.MOBILE.WNS.Type",
                new MessageAttributeValue().withDataType("String").withStringValue("wns/badge"));
        return notificationAttributes;
    }

    private static Map<String, MessageAttributeValue> addMPNSNotificationAttributes() {
        Map<String, MessageAttributeValue> notificationAttributes = new HashMap<String, MessageAttributeValue>();
        notificationAttributes.put("AWS.SNS.MOBILE.MPNS.Type",
                new MessageAttributeValue().withDataType("String").withStringValue("token")); // This attribute is
        // required.
        notificationAttributes.put("AWS.SNS.MOBILE.MPNS.NotificationClass",
                new MessageAttributeValue().withDataType("String").withStringValue("realtime")); // This attribute is
        // required.

        return notificationAttributes;
    }

    public void starterAppleAppNotification(String msg, String deviceToken) {
        // TODO: Please fill in following values for your application. You can
        // also change the notification payload as per your preferences using
        // the method
        // com.amazonaws.sns.samples.tools.NotificationMessageGenerator.getSampleAppleMessage()
        String certificate = "-----BEGIN CERTIFICATE-----\n" + "-----END CERTIFICATE-----\n";

        String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" + "-----END RSA PRIVATE KEY-----\n";

        String applicationName = "StarterPush";

        // This is 64 hex characters.
        snsClientWrapper.starterNotification(Platform.APNS, certificate, privateKey, deviceToken, applicationName,
                attributesMap, msg);
    }
}