com.amazonaws.services.sns.model.SubscribeResult Java Examples

The following examples show how to use com.amazonaws.services.sns.model.SubscribeResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AwsGlacierInventoryRetriever.java    From core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * For retrieving vault inventory. For initializing SNS for determining when
 * job completed. Does nothing if member snsTopicName is null. Sets members
 * snsTopicARN and snsSubscriptionARN.
 */
   void setupSNS() {
	// If no snsTopicName setup then simply return
	if (snsTopicName == null)
		return;

	CreateTopicRequest request = new CreateTopicRequest()
			.withName(snsTopicName);
	CreateTopicResult result = snsClient.createTopic(request);
	snsTopicARN = result.getTopicArn();

	SubscribeRequest request2 = new SubscribeRequest()
			.withTopicArn(snsTopicARN).withEndpoint(sqsQueueARN)
			.withProtocol("sqs");
	SubscribeResult result2 = snsClient.subscribe(request2);

	snsSubscriptionARN = result2.getSubscriptionArn();
}
 
Example #2
Source File: TopicImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public Subscription subscribe(SubscribeRequest request,
        ResultCapture<SubscribeResult> extractor) {

    ActionResult result = resource.performAction("Subscribe", request,
            extractor);

    if (result == null) return null;
    return new SubscriptionImpl(result.getResource());
}
 
Example #3
Source File: TopicImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public Subscription subscribe(String endpoint, String protocol,
        ResultCapture<SubscribeResult> extractor) {

    SubscribeRequest request = new SubscribeRequest()
        .withEndpoint(endpoint)
        .withProtocol(protocol);
    return subscribe(request, extractor);
}
 
Example #4
Source File: SnsExecutor.java    From spring-integration-aws with MIT License 5 votes vote down vote up
private void processUrlSubscription(Subscription urlSubscription) {

		String snsUrlSubscriptionArn = null;
		for (Subscription subscription : client.listSubscriptions()
				.getSubscriptions()) {
			if (subscription.getTopicArn().equals(topicArn)
					&& subscription.getProtocol().equals(
							urlSubscription.getProtocol())
					&& subscription.getEndpoint().contains(
							urlSubscription.getEndpoint())) {
				if (!subscription.getSubscriptionArn().equals(
						"PendingConfirmation")) {
					snsUrlSubscriptionArn = subscription.getSubscriptionArn();
					break;
				}
			}
		}
		if (snsUrlSubscriptionArn == null) {

			SubscribeRequest request = new SubscribeRequest(topicArn,
					urlSubscription.getProtocol(),
					urlSubscription.getEndpoint());
			SubscribeResult result = client.subscribe(request);
			snsUrlSubscriptionArn = result.getSubscriptionArn();
			log.info("Subscribed URL to SNS with subscription ARN: "
					+ snsUrlSubscriptionArn);
		} else {
			log.info("Already subscribed with ARN: " + snsUrlSubscriptionArn);
		}
	}
 
Example #5
Source File: SnsMessageBroker.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
private void subscribeOwnNode(Handler<AsyncResult<Void>> callback) {
  logger.info("Subscribing the NODE=" + Node.OWN_INSTANCE.getUrl());

  final String subscriptionErrorMsg = "The Node could not be subscribed as AdminMessage listener. "
      + "No AdminMessages will be received by this node.";
  if (OWN_NODE_MESSAGING_URL == null)
    throw new NullPointerException("No messaging node URL provided. " + subscriptionErrorMsg);

  //First check whether there is an existing subscription for the own endpoint
  loadSubscriptions(subscriptionsResult -> {
    if (subscriptionsResult.succeeded()) {
      oldSubscriptions = subscriptionsResult.result();
      logger.info("Subscriptions have been loaded [" + oldSubscriptions.size() + "] for NODE=" + Node.OWN_INSTANCE.getUrl());
      /*
      Check whether a subscription to the own node's endpoint already exists.
      (could happen by accident when this node re-uses an IP from a previously running node)
      */
      if (oldSubscriptions.stream().noneMatch(subscription -> OWN_NODE_MESSAGING_URL.equals(subscription.getEndpoint()))) {
        logger
            .info("Current node is not subscribed yet, subscribing NODE=" + Node.OWN_INSTANCE.getUrl() + " into TOPIC_ARN=" + TOPIC_ARN);
        SNS_CLIENT
            .subscribeAsync(TOPIC_ARN, SNS_HTTP_PROTOCOL, OWN_NODE_MESSAGING_URL, new AsyncHandler<SubscribeRequest, SubscribeResult>() {
              @Override
              public void onError(Exception e) {
                logger.error(subscriptionErrorMsg, e);
                callback.handle(Future.failedFuture(e));
              }

              @Override
              public void onSuccess(SubscribeRequest request, SubscribeResult subscribeResult) {
                logger.info("Subscription succeeded for NODE=" + Node.OWN_INSTANCE.getUrl() + " into TOPIC_ARN=" + TOPIC_ARN);
                callback.handle(Future.succeededFuture());
              }
            });
      }
    }
    else {
      logger.error(subscriptionErrorMsg, subscriptionsResult.cause());
    }
  });
}
 
Example #6
Source File: TopicImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public Subscription subscribe(String endpoint, String protocol) {
    return subscribe(endpoint, protocol,
            (ResultCapture<SubscribeResult>)null);
}
 
Example #7
Source File: ControlChannel.java    From s3-bucket-loader with Apache License 2.0 4 votes vote down vote up
public void connectToTopic(boolean callerIsMaster, int maxAttempts, String userAccountPrincipalId, String userARN) throws Exception {
	
	
	// try up to max attempts to connect to pre-existing topic
	for (int i=0; i<maxAttempts; i++) {
		
		logger.debug("connectToTopic() attempt: " + (i+1));
		
		ListTopicsResult listResult = snsClient.listTopics();
		List<Topic> topics = listResult.getTopics();
		
		while(topics != null) {
			
			for (Topic topic : topics) {

				// note we do index of match....
				if (topic.getTopicArn().indexOf(snsControlTopicName) != -1) {
					snsTopicARN = topic.getTopicArn();
					logger.info("Found existing SNS topic by name: "+snsControlTopicName + " @ " + snsTopicARN);
					break;
				}
			}

			String nextToken = listResult.getNextToken();
			
			if (nextToken != null && snsTopicARN == null) {
				listResult = snsClient.listTopics(nextToken);
				topics = listResult.getTopics();
				
			} else {
				break;
			}
		}
		
		// if consumer, retry, otherwise is master, so just exit quick to create...
		if (snsTopicARN == null && !callerIsMaster) {
			Thread.currentThread().sleep(1000);
			continue;
		} else {
			break; // exit;
		}
	}
	
	
	
	// if master only he can create...
	if (snsTopicARN == null && callerIsMaster) {
		this.snsControlTopicName = this.snsControlTopicName.substring(0,(snsControlTopicName.length() > 80 ? 80 : this.snsControlTopicName.length()));
		
		logger.info("Attempting to create new SNS control channel topic by name: "+this.snsControlTopicName);
		
		CreateTopicResult createTopicResult = snsClient.createTopic(this.snsControlTopicName);
		snsTopicARN = createTopicResult.getTopicArn();
		snsClient.addPermission(snsTopicARN, "Permit_SNSAdd", 
								Arrays.asList(new String[]{userARN}), 
								Arrays.asList(new String[]{"Publish","Subscribe","Receive"}));
		logger.info("Created new SNS control channel topic by name: "+this.snsControlTopicName + " @ " + snsTopicARN);
		
	} else if (snsTopicARN == null) {
		throw new Exception("Worker() cannot start, snsControlTopicName has yet to be created by master?: " + this.snsControlTopicName);
	}
	
	// http://www.jorgjanke.com/2013/01/aws-sns-topic-subscriptions-with-sqs.html
	
	// create SQS queue to get SNS notifications (max 80 len)
	String prefix =  ("s3bktLoaderCC_" + mySourceIdentifier);
	String sqsQueueName = prefix.substring(0,(prefix.length() > 80 ? 80 : prefix.length()));
	
	CreateQueueResult createQueueResult = sqsClient.createQueue(sqsQueueName);
	this.sqsQueueUrl = createQueueResult.getQueueUrl();
	this.sqsQueueARN = sqsClient.getQueueAttributes(sqsQueueUrl, Arrays.asList(new String[]{"QueueArn"})).getAttributes().get("QueueArn");

	Statement statement = new Statement(Effect.Allow)
							.withActions(SQSActions.SendMessage)
							 .withPrincipals(new Principal("*"))
							 .withConditions(ConditionFactory.newSourceArnCondition(snsTopicARN))
							 .withResources(new Resource(sqsQueueARN));
	Policy policy = new Policy("SubscriptionPermission").withStatements(statement);

	HashMap<String, String> attributes = new HashMap<String, String>();
	attributes.put("Policy", policy.toJson());
	SetQueueAttributesRequest request = new SetQueueAttributesRequest(sqsQueueUrl, attributes);
	sqsClient.setQueueAttributes(request);

	logger.info("Created SQS queue: " + sqsQueueARN + " @ " + sqsQueueUrl);
	
	// subscribe our SQS queue to the SNS:s3MountTest topic
	SubscribeResult subscribeResult = snsClient.subscribe(snsTopicARN,"sqs",sqsQueueARN);
	snsSubscriptionARN = subscribeResult.getSubscriptionArn();
	logger.info("Subscribed for messages from SNS control channel:" + snsTopicARN + " ----> SQS: "+sqsQueueARN);
	logger.info("Subscription ARN: " + snsSubscriptionARN);
	
	this.consumerThread = new Thread(this,"ControlChannel msg consumer thread");
	this.consumerThread.start();

	logger.info("\n-------------------------------------------\n" +
				"CONTROL CHANNEL: ALL SNS/SQS resources hooked up OK\n" +
				"-------------------------------------------\n");
}
 
Example #8
Source File: SnsExecutor.java    From spring-integration-aws with MIT License 4 votes vote down vote up
private void processSqsSubscription(Subscription sqsSubscription) {
	Assert.state(sqsExecutorMap != null,
			"'sqsExecutorMap' must not be null");

	SqsExecutor sqsExecutor = null;
	String endpointValue = sqsSubscription.getEndpoint();
	if (sqsExecutorMap.containsKey(endpointValue)) {
		sqsExecutor = sqsExecutorMap.get(endpointValue);
		sqsSubscription.setEndpoint(sqsExecutor.getQueueArn());
	} else {
		// endpointValue is the queue-arn
		sqsSubscription.setEndpoint(endpointValue);
	}

	String snsSqsSubscriptionArn = null;
	for (Subscription subscription : client.listSubscriptions()
			.getSubscriptions()) {
		if (subscription.getTopicArn().equals(topicArn)
				&& subscription.getProtocol().equals(
						sqsSubscription.getProtocol())
				&& subscription.getEndpoint().equals(
						sqsSubscription.getEndpoint())) {
			snsSqsSubscriptionArn = subscription.getSubscriptionArn();
			break;
		}
	}
	if (snsSqsSubscriptionArn == null) {
		SubscribeRequest request = new SubscribeRequest(topicArn,
				sqsSubscription.getProtocol(),
				sqsSubscription.getEndpoint());
		SubscribeResult result = client.subscribe(request);
		snsSqsSubscriptionArn = result.getSubscriptionArn();
		log.info("Subscribed SQS to SNS with subscription ARN: "
				+ snsSqsSubscriptionArn);
	} else {
		log.info("Already subscribed with ARN: " + snsSqsSubscriptionArn);
	}
	if (sqsExecutor != null) {
		sqsExecutor.addSnsPublishPolicy(topicName, topicArn);
	}
}
 
Example #9
Source File: Topic.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>Subscribe</code> action and use a ResultCapture to
 * retrieve the low-level client response.
 *
 * <p>
 * The following request parameters will be populated from the data of this
 * <code>Topic</code> resource, and any conflicting parameter value set in
 * the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>TopicArn</code></b>
 *         - mapped from the <code>Arn</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return The <code>Subscription</code> resource object associated with the
 *         result of this action.
 * @see SubscribeRequest
 */
com.amazonaws.resources.sns.Subscription subscribe(SubscribeRequest request,
        ResultCapture<SubscribeResult> extractor);
 
Example #10
Source File: Topic.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * The convenient method form for the <code>Subscribe</code> action.
 *
 * @see #subscribe(SubscribeRequest, ResultCapture)
 */
com.amazonaws.resources.sns.Subscription subscribe(String endpoint, String
        protocol, ResultCapture<SubscribeResult> extractor);