Example usage for com.amazonaws.services.sns AmazonSNSClient AmazonSNSClient

List of usage examples for com.amazonaws.services.sns AmazonSNSClient AmazonSNSClient

Introduction

In this page you can find the example usage for com.amazonaws.services.sns AmazonSNSClient AmazonSNSClient.

Prototype

AmazonSNSClient(AwsSyncClientParams clientParams) 

Source Link

Document

Constructs a new client to invoke service methods on Amazon SNS using the specified parameters.

Usage

From source file:com.clicktravel.infrastructure.runtime.config.aws.AwsConfiguration.java

License:Apache License

@Bean
@Autowired/*from   w w  w . j  a va 2 s .co  m*/
public AmazonSNS amazonSnsClient(final AWSCredentials awsCredentials,
        @Value("${aws.sns.client.endpoint}") final String endpoint) {
    final AmazonSNS amazonSnsClient = new AmazonSNSClient(awsCredentials);
    logger.info("Setting AWS SNS endpoint to: " + endpoint);
    amazonSnsClient.setEndpoint(endpoint);
    return amazonSnsClient;
}

From source file:com.comcast.cmb.common.controller.AdminServletBase.java

License:Apache License

/**
  * Method to set the aws credentials for sqs and sns handlers
  * @param userId//w  ww.j a va2 s.c  o m
  * @throws ServletException
  */
protected void connect(HttpServletRequest request) throws ServletException {

    String userId = request.getParameter("userId");

    IUserPersistence userHandler = PersistenceFactory.getUserPersistence();

    try {
        user = userHandler.getUserById(userId);
    } catch (PersistenceException ex) {
        throw new ServletException(ex);
    }

    if (user == null) {
        throw new ServletException("User " + userId + " does not exist");
    }

    if (!user.getUserName().equals(getAuthenticatedUser(request).getUserName())
            && !getAuthenticatedUser(request).getIsAdmin()) {
        throw new ServletException("Only admin may impersonate other users");
    }

    awsCredentials = new BasicAWSCredentials(user.getAccessKey(), user.getAccessSecret());

    sqs = new AmazonSQSClient(awsCredentials);
    sqs.setEndpoint(CMBProperties.getInstance().getCQSServiceUrl());

    sns = new AmazonSNSClient(awsCredentials);
    sns.setEndpoint(CMBProperties.getInstance().getCNSServiceUrl());
}

From source file:com.comcast.cmb.test.tools.CMBTutorial.java

License:Apache License

public static void main(String[] args) {

    try {/* ww  w  .ja  v a 2  s  .  c  om*/

        Util.initLog4jTest();

        //TODO: set user id and credentials for two distinct users

        // user "cqs_test_1"

        //BasicAWSCredentials user1Credentials = new BasicAWSCredentials("<access_key>", "<secret_key>");

        BasicAWSCredentials user1Credentials = new BasicAWSCredentials("Z2DVBFRNZ2C2SSXDWS5F",
                "bH2UQiJkpctBaE3eaDob19fj5J9Q1FVafrZantBp");

        // user "cqs_test_2"

        //String user2Id = "<user_id>";
        String user2Id = "389653920093";

        //BasicAWSCredentials user2Credentials = new BasicAWSCredentials("<access_key>", "<secret_key>");

        BasicAWSCredentials user2Credentials = new BasicAWSCredentials("QL8Q1VOBCSJC5FZ2DMIU",
                "n6a82gyJZ04Z+Xqp7OgfqPtbbKqVc3UbuOTNrF+7");

        // service urls

        //TODO: add service URLs

        //String cqsServerUrl = "http://<host>:<port>";
        //String cnsServerUrl = "http://<host>:<port>";

        String cqsServerUrl = "http://localhost:6059";
        String cnsServerUrl = "http://localhost:6061";

        // initialize service

        AmazonSQSClient sqs = new AmazonSQSClient(user1Credentials);
        sqs.setEndpoint(cqsServerUrl);

        AmazonSNSClient sns = new AmazonSNSClient(user2Credentials);
        sns.setEndpoint(cnsServerUrl);

        // create queue

        Random randomGenerator = new Random();

        String queueName = QUEUE_PREFIX + randomGenerator.nextLong();

        HashMap<String, String> attributeParams = new HashMap<String, String>();
        CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName);
        createQueueRequest.setAttributes(attributeParams);
        String queueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

        AddPermissionRequest addPermissionRequest = new AddPermissionRequest();
        addPermissionRequest.setQueueUrl(queueUrl);
        addPermissionRequest.setActions(Arrays.asList("SendMessage"));
        addPermissionRequest.setLabel(UUID.randomUUID().toString());
        addPermissionRequest.setAWSAccountIds(Arrays.asList(user2Id));
        sqs.addPermission(addPermissionRequest);

        // create topic

        String topicName = "TSTT" + randomGenerator.nextLong();

        CreateTopicRequest createTopicRequest = new CreateTopicRequest(topicName);
        CreateTopicResult createTopicResult = sns.createTopic(createTopicRequest);
        String topicArn = createTopicResult.getTopicArn();

        // subscribe and confirm cqs endpoint

        SubscribeRequest subscribeRequest = new SubscribeRequest();
        String queueArn = getArnForQueueUrl(queueUrl);
        subscribeRequest.setEndpoint(queueArn);
        subscribeRequest.setProtocol("cqs");
        subscribeRequest.setTopicArn(topicArn);
        SubscribeResult subscribeResult = sns.subscribe(subscribeRequest);
        String subscriptionArn = subscribeResult.getSubscriptionArn();

        if (subscriptionArn.equals("pending confirmation")) {

            Thread.sleep(500);

            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
            receiveMessageRequest.setQueueUrl(queueUrl);
            receiveMessageRequest.setMaxNumberOfMessages(1);
            ReceiveMessageResult receiveMessageResult = sqs.receiveMessage(receiveMessageRequest);

            List<Message> messages = receiveMessageResult.getMessages();

            if (messages != null && messages.size() == 1) {

                JSONObject o = new JSONObject(messages.get(0).getBody());

                if (!o.has("SubscribeURL")) {
                    throw new Exception("message is not a confirmation messsage");
                }

                String subscriptionUrl = o.getString("SubscribeURL");
                httpGet(subscriptionUrl);

                DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
                deleteMessageRequest.setReceiptHandle(messages.get(0).getReceiptHandle());
                deleteMessageRequest.setQueueUrl(queueUrl);
                sqs.deleteMessage(deleteMessageRequest);

            } else {
                throw new Exception("no confirmation message found");
            }
        }

        // publish and receive message

        PublishRequest publishRequest = new PublishRequest();
        String messageText = "quamvis sint sub aqua, sub aqua maledicere temptant";
        publishRequest.setMessage(messageText);
        publishRequest.setSubject("unit test message");
        publishRequest.setTopicArn(topicArn);
        sns.publish(publishRequest);

        Thread.sleep(500);

        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
        receiveMessageRequest.setQueueUrl(queueUrl);
        receiveMessageRequest.setMaxNumberOfMessages(1);
        ReceiveMessageResult receiveMessageResult = sqs.receiveMessage(receiveMessageRequest);

        List<Message> messages = receiveMessageResult.getMessages();

        if (messages != null && messages.size() == 1) {

            String messageBody = messages.get(0).getBody();

            if (!messageBody.contains(messageText)) {
                throw new Exception("message text not found");
            }

            DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
            deleteMessageRequest.setReceiptHandle(messages.get(0).getReceiptHandle());
            deleteMessageRequest.setQueueUrl(queueUrl);
            sqs.deleteMessage(deleteMessageRequest);

        } else {
            throw new Exception("no messages found");
        }

        // subscribe and confirm http endpoint

        String id = randomGenerator.nextLong() + "";
        String endPointUrl = CMBTestingConstants.HTTP_ENDPOINT_BASE_URL + "recv/" + id;
        String lastMessageUrl = CMBTestingConstants.HTTP_ENDPOINT_BASE_URL + "info/" + id + "?showLast=true";

        subscribeRequest = new SubscribeRequest();
        subscribeRequest.setEndpoint(endPointUrl);
        subscribeRequest.setProtocol("http");
        subscribeRequest.setTopicArn(topicArn);
        subscribeResult = sns.subscribe(subscribeRequest);
        subscriptionArn = subscribeResult.getSubscriptionArn();

        if (subscriptionArn.equals("pending confirmation")) {

            Thread.sleep(500);

            String response = httpGet(lastMessageUrl);

            JSONObject o = new JSONObject(response);

            if (!o.has("SubscribeURL")) {
                throw new Exception("message is not a confirmation messsage");
            }

            String subscriptionUrl = o.getString("SubscribeURL");

            response = httpGet(subscriptionUrl);
        }

        // publish and receive message

        publishRequest = new PublishRequest();
        publishRequest.setMessage(messageText);
        publishRequest.setSubject("unit test message");
        publishRequest.setTopicArn(topicArn);
        sns.publish(publishRequest);

        Thread.sleep(500);

        String response = httpGet(lastMessageUrl);

        if (response != null && response.length() > 0) {

            if (!response.contains(messageText)) {
                throw new Exception("message text not found");
            }

        } else {
            throw new Exception("no messages found");
        }

        // delete queue and topic

        DeleteTopicRequest deleteTopicRequest = new DeleteTopicRequest(topicArn);
        sns.deleteTopic(deleteTopicRequest);

        sqs.deleteQueue(new DeleteQueueRequest(queueUrl));

        System.out.println("OK");

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.connexience.server.model.archive.glacier.SetupUtils.java

License:Open Source License

public static String setupSNS(String accessKey, String secretKey, String domainName, String vaultName,
        String queueARN) {//from   ww  w .j  a  v a 2s .c  o m
    String topicARN = null;
    try {
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);

        AmazonSNSClient amazonSNSClient = new AmazonSNSClient(awsCredentials);
        amazonSNSClient.setEndpoint("https://sns." + domainName + ".amazonaws.com/");

        String topicName = vaultName + "-inkspot_glacier-topic";
        CreateTopicRequest createTopicRequest = new CreateTopicRequest();
        createTopicRequest.withName(topicName);

        CreateTopicResult createTopicResult = amazonSNSClient.createTopic(createTopicRequest);
        if (createTopicResult != null) {
            topicARN = createTopicResult.getTopicArn();

            SubscribeRequest subscribeRequest = new SubscribeRequest();
            subscribeRequest.withTopicArn(topicARN);
            subscribeRequest.withProtocol("sqs");
            subscribeRequest.withEndpoint(queueARN);

            SubscribeResult subscribeResult = amazonSNSClient.subscribe(subscribeRequest);
            if (subscribeResult == null)
                logger.warn("Unable to subscribe topic: \"" + topicName + "\" to queue: \"" + queueARN + "\"");
        } else
            logger.warn("Unable to create topic: \"" + topicName + "\"");

        amazonSNSClient.shutdown();
    } catch (AmazonServiceException amazonServiceException) {
        logger.warn("AmazonServiceException: " + amazonServiceException);
        logger.debug(amazonServiceException);
    } catch (IllegalArgumentException illegalArgumentException) {
        logger.warn("IllegalArgumentException: " + illegalArgumentException);
        logger.debug(illegalArgumentException);
    } catch (AmazonClientException amazonClientException) {
        logger.warn("AmazonClientException: " + amazonClientException);
        logger.debug(amazonClientException);
    } catch (Throwable throwable) {
        logger.warn("Throwable: " + throwable);
        logger.debug(throwable);
    }

    return topicARN;
}

From source file:com.dev.appx.sns.SNSMobilePush.java

License:Open Source License

public static void igniteSNS() throws IOException {
    /*//ww w .java  2s .c om
     * 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
     */
    AmazonSNS sns = new AmazonSNSClient(
            new PropertiesCredentials(SNSMobilePush.class.getResourceAsStream("/AwsCredentials.properties")));

    sns.setEndpoint("https://sns.us-west-2.amazonaws.com");
    System.out.println("===========================================\n");
    System.out.println("Getting Started with Amazon SNS");
    System.out.println("===========================================\n");
    try {
        SNSMobilePush sample = new SNSMobilePush(sns);
        /* TODO: Uncomment the services you wish to use. */
        //sample.demoAndroidAppNotification();
        // sample.demoKindleAppNotification();
        // sample.demoAppleAppNotification();
        // sample.demoAppleSandboxAppNotification();
        // sample.demoBaiduAppNotification();
        // sample.demoWNSAppNotification();
        // sample.demoMPNSAppNotification();
        sample.createTopic("test");
    } 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());
    }
}

From source file:com.dev.appx.sns.SNSMobilePush.java

License:Open Source License

public void createTopic(String topic) throws IOException {
    //create a new SNS client and set endpoint
    AmazonSNSClient snsClient = new AmazonSNSClient(new ClasspathPropertiesFileCredentialsProvider());

    /*AmazonSNS snsClient = new AmazonSNSClient(new PropertiesCredentials(
    SNSMobilePush.class/*from w  ww .  j a v a 2  s. c  om*/
          .getResourceAsStream("AwsCredentials.properties")));*/

    snsClient.setRegion(Region.getRegion(Regions.US_EAST_1));

    //create a new SNS topic
    CreateTopicRequest createTopicRequest = new CreateTopicRequest(topic);
    CreateTopicResult createTopicResult = snsClient.createTopic(createTopicRequest);
    //print TopicArn
    System.out.println(createTopicResult);
    //get request id for CreateTopicRequest from SNS metadata      
    System.out.println("CreateTopicRequest - " + snsClient.getCachedResponseMetadata(createTopicRequest));
}

From source file:com.dev.appx.sns.SNSMobilePush.java

License:Open Source License

public void deleteTopic(String topicArn) throws IOException {

    //AmazonSNSClient snsClient = new AmazonSNSClient(new ClasspathPropertiesFileCredentialsProvider());   

    AmazonSNS snsClient = new AmazonSNSClient(
            new PropertiesCredentials(SNSMobilePush.class.getResourceAsStream("AwsCredentials.properties")));
    //delete an SNS topic
    DeleteTopicRequest deleteTopicRequest = new DeleteTopicRequest(topicArn);
    snsClient.deleteTopic(deleteTopicRequest);
    //get request id for DeleteTopicRequest from SNS metadata
    System.out.println("DeleteTopicRequest - " + snsClient.getCachedResponseMetadata(deleteTopicRequest));

}

From source file:com.github.abhinavmishra14.aws.glacier.service.impl.GlacierArchiveServiceImpl.java

License:Open Source License

/**
 * The Constructor.<br/>/*ww  w  .j  av  a 2  s.c o  m*/
 * This Constructor will return glacier client using accessKey and secretKey.<br/>
 * Additionally it will set the given endPoint for performing upload operation over vault.<br/>
 * Default endpoint will be always: "https://glacier.us-east-1.amazonaws.com/"
 * SSL Certificate checking will be disabled based on provided flag.
 *
 * @param accessKey the access key
 * @param secretKey the secret key
 * @param disableCertCheck the disable cert check
 * @param endpoint the endpoint
 */
public GlacierArchiveServiceImpl(final String accessKey, final String secretKey, final boolean disableCertCheck,
        final String endpoint) {
    super();
    AWSUtil.notNull(accessKey, ERR_MSG_ACCESSKEY);
    AWSUtil.notNull(secretKey, ERR_MSG_SECRETKEY);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("GlacierArchiveServiceImpl is initializing using keys..");
    }
    final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    final AWSCredentialsProvider credentialsProvider = new StaticCredentialsProvider(credentials);
    glacierClient = new AmazonGlacierClient(credentialsProvider);
    sqsClient = new AmazonSQSClient(credentialsProvider);
    snsClient = new AmazonSNSClient(credentialsProvider);
    if (disableCertCheck) {
        System.setProperty(DISABLE_CERT_PARAM, TRUE);//Disable cert check
    }
    if (StringUtils.isNotBlank(endpoint)) {
        glacierClient.setEndpoint(endpoint);
    }
}

From source file:com.github.gregwhitaker.sns.Producer.java

License:Apache License

public Producer(String name, String topicArn) {
    this.name = name;
    this.topicArn = topicArn;
    this.snsClient = new AmazonSNSClient(new DefaultAWSCredentialsProviderChain());
    this.snsClient.setRegion(Region.getRegion(Regions.US_WEST_2));
}

From source file:com.haskins.cloudtrailviewer.dialog.resourcedetail.detailpanels.SnsTopic.java

License:Open Source License

@Override
public String retrieveDetails(ResourceDetailRequest detailRequest) {

    String response = null;// w w w  .  ja va2 s  .  c om

    try {

        AmazonSNS client = new AmazonSNSClient(credentials);
        client.setRegion(Region.getRegion(Regions.fromName(detailRequest.getRegion())));

        buildUI(null);

    } catch (IllegalArgumentException | AmazonClientException e) {
        response = e.getMessage();
        LOGGER.log(Level.WARNING, "Problem retrieving SNS details from AWS", e);
    }

    return response;
}