List of usage examples for com.amazonaws.services.sns AmazonSNSClient publish
@Override
public PublishResult publish(PublishRequest request)
Sends a message to an Amazon SNS topic or sends a text message (SMS message) directly to a phone number.
From source file:awslabs.lab31.SolutionCode.java
License:Open Source License
@Override public void publishTopicMessage(AmazonSNSClient snsClient, String topicArn, String subject, String message) { // TODO: Construct a PublishRequest object using the provided subject, message, and topic ARN. PublishRequest publishRequest = new PublishRequest().withMessage(message).withSubject(subject) .withTopicArn(topicArn);// w w w . j a va2s . com // TODO: Submit the request using the publish method of the snsClient object. snsClient.publish(publishRequest); }
From source file:awslabs.lab31.StudentCode.java
License:Open Source License
/** * Publish a message to the specified SNS topic. Hint: Use the publish() method of the client object. * // w w w .ja v a 2s . c o m * @param snsClient The SNS client object. * @param topicArn The ARN for the topic to post the message to. * @param subject The subject of the message to publish. * @param message The body of the message to publish. */ @Override public void publishTopicMessage(AmazonSNSClient snsClient, String topicArn, String subject, String message) { PublishRequest request = new PublishRequest().withSubject(subject).withMessage(message) .withTopicArn(topicArn); snsClient.publish(request); }
From source file:com.comcast.cmb.test.tools.CMBTutorial.java
License:Apache License
public static void main(String[] args) { try {//from w w w. j a va2 s . co m 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:dsmwatcher.DSMWatcher.java
License:Open Source License
public void notifyAdmin(Instance instance, ArrayList<String> violations, Boolean remediated) throws Exception { AmazonSNSClient snsClient = new AmazonSNSClient().withRegion(region); String message = "The instance " + instance.getInstanceId() + " with IP address " + instance.getPrivateIpAddress() + " was found with the following violations:"; if (!remediated) { for (String reason : violations) message += "\n" + reason; if (enableIsolation) message += "\nEnforcement is enabled and the instance has been isolated"; else/*from www . j av a 2 s . c o m*/ message += "\nEnforcement is disabled - no action was taken"; } else message = "The instance " + instance.getInstanceId() + " with IP address " + instance.getPrivateIpAddress() + " is no longer in violation of any policies and has been removed from isolation"; PublishRequest publishRequest = new PublishRequest(topicARN, message); snsClient.publish(publishRequest); }
From source file:org.apache.nifi.processors.aws.sns.PutSNS.java
License:Apache License
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { FlowFile flowFile = session.get();/*from ww w .j av a 2s . c o m*/ if (flowFile == null) { return; } if (flowFile.getSize() > MAX_SIZE) { getLogger().error( "Cannot publish {} to SNS because its size exceeds Amazon SNS's limit of 256KB; routing to failure", new Object[] { flowFile }); session.transfer(flowFile, REL_FAILURE); return; } final Charset charset = Charset .forName(context.getProperty(CHARACTER_ENCODING).evaluateAttributeExpressions(flowFile).getValue()); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); final String message = new String(baos.toByteArray(), charset); final AmazonSNSClient client = getClient(); final PublishRequest request = new PublishRequest(); request.setMessage(message); if (context.getProperty(USE_JSON_STRUCTURE).asBoolean()) { request.setMessageStructure("json"); } final String arn = context.getProperty(ARN).evaluateAttributeExpressions(flowFile).getValue(); final String arnType = context.getProperty(ARN_TYPE).getValue(); if (arnType.equalsIgnoreCase(ARN_TYPE_TOPIC.getValue())) { request.setTopicArn(arn); } else { request.setTargetArn(arn); } final String subject = context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue(); if (subject != null) { request.setSubject(subject); } for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) { if (entry.getKey().isDynamic() && !StringUtils.isEmpty(entry.getValue())) { final MessageAttributeValue value = new MessageAttributeValue(); value.setStringValue( context.getProperty(entry.getKey()).evaluateAttributeExpressions(flowFile).getValue()); value.setDataType("String"); request.addMessageAttributesEntry(entry.getKey().getName(), value); } } try { client.publish(request); session.transfer(flowFile, REL_SUCCESS); session.getProvenanceReporter().send(flowFile, arn); getLogger().info("Successfully published notification for {}", new Object[] { flowFile }); } catch (final Exception e) { getLogger().error("Failed to publish Amazon SNS message for {} due to {}", new Object[] { flowFile, e }); flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } }
From source file:shnakkydoodle.notifying.provider.aws.AwsProvider.java
License:Open Source License
/** * Publish a notification// w w w .j ava2 s. com */ @Override public String insertNotification(String topicName, String subject, String message) { AmazonSNSClient snsClient = getSNSClient(); // find the topic NotificationTopic notificationTopic = this.retrieveNotificationTopic(topicName); if (notificationTopic == null) { this.insertNotificationTopic(topicName, ""); } // publish to an SNS topic PublishRequest publishRequest = new PublishRequest(this.retrieveNotificationTopic(topicName).getTopicId(), subject); PublishResult publishResult = snsClient.publish(publishRequest); return publishResult.getMessageId(); }