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

The following examples show how to use com.amazonaws.services.sns.model.Subscription. 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: SnsMessageBroker.java    From xyz-hub with Apache License 2.0 7 votes vote down vote up
private void unsubscribe(Subscription subscription) {
  if (PENDING_CONFIRMATION.equals(subscription.getSubscriptionArn())) {
    logger.warn("Could not remove subscription ({}) because it's pending for confirmation. It will be removed automatically "
        + "after 3 days.", subscription.getEndpoint());
    return;
  }
  SNS_CLIENT.unsubscribeAsync(subscription.getSubscriptionArn(), new AsyncHandler<UnsubscribeRequest, UnsubscribeResult>() {
    @Override
    public void onError(Exception e) {
      logger.error("Error un-subscribing endpoint {} from SNS: {}", subscription.getEndpoint(), e);
    }

    @Override
    public void onSuccess(UnsubscribeRequest request, UnsubscribeResult unsubscribeResult) {
      logger.debug("Endpoint {} has been successfully un-subscribed from SNS.", subscription.getEndpoint());
    }
  });
}
 
Example #2
Source File: SNSInventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch SNS topics test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchSNSTopicsTest() throws Exception {
    
    mockStatic(AmazonSNSClientBuilder.class);
    AmazonSNSClient snsClient = PowerMockito.mock(AmazonSNSClient.class);
    AmazonSNSClientBuilder amazonSNSClientBuilder = PowerMockito.mock(AmazonSNSClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonSNSClientBuilder.standard()).thenReturn(amazonSNSClientBuilder);
    when(amazonSNSClientBuilder.withCredentials(anyObject())).thenReturn(amazonSNSClientBuilder);
    when(amazonSNSClientBuilder.withRegion(anyString())).thenReturn(amazonSNSClientBuilder);
    when(amazonSNSClientBuilder.build()).thenReturn(snsClient);
    
    ListSubscriptionsResult listSubscriptionDefinitionsResult = new ListSubscriptionsResult();
    List<Subscription> subscriptionList = new ArrayList<>();
    subscriptionList.add(new Subscription());
    listSubscriptionDefinitionsResult.setSubscriptions(subscriptionList);
    when(snsClient.listSubscriptions( new ListSubscriptionsRequest())).thenReturn(listSubscriptionDefinitionsResult);
    assertThat(snsInventoryUtil.fetchSNSTopics(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #3
Source File: SnsMessageBroker.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
private void loadSubscriptions(String nextToken, Handler<AsyncResult<List<Subscription>>> callback) {
  ListSubscriptionsByTopicRequest req = new ListSubscriptionsByTopicRequest()
      .withTopicArn(TOPIC_ARN);
  if (nextToken != null) {
    req.setNextToken(nextToken);
  }
  SNS_CLIENT.listSubscriptionsByTopicAsync(req,
      new AsyncHandler<ListSubscriptionsByTopicRequest, ListSubscriptionsByTopicResult>() {
        @Override
        public void onError(Exception e) {
          callback.handle(Future.failedFuture(e));
        }

        @Override
        public void onSuccess(ListSubscriptionsByTopicRequest request, ListSubscriptionsByTopicResult result) {
          List<Subscription> subscriptions = result.getSubscriptions()
              .stream()
              .filter(subscription -> SNS_HTTP_PROTOCOL.equals(subscription.getProtocol())
                  && subscription.getEndpoint().contains(AdminApi.ADMIN_MESSAGES_ENDPOINT))
              .collect(Collectors.toCollection(LinkedList::new));
          if (result.getNextToken() != null) {
            loadSubscriptions(result.getNextToken(), subscriptionsResult -> {
              if (subscriptionsResult.succeeded()) {
                subscriptions.addAll(subscriptionsResult.result());
                callback.handle(Future.succeededFuture(subscriptions));
              } else {
                callback.handle(subscriptionsResult);
              }
            });
          }
          else {
            callback.handle(Future.succeededFuture(subscriptions));
          }
        }
      });
}
 
Example #4
Source File: SnsMessageBroker.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
private void checkSubscription(Subscription subscription) {
  String endpoint = subscription.getEndpoint();
  try {
    URL subscriptionUrl = new URL(endpoint);
    Node subscribedNode = Node.forIpAndPort(subscriptionUrl.getHost(), subscriptionUrl.getPort());
    subscribedNode.isAlive(ar -> {
      if (ar.failed()) {
        unsubscribe(subscription);
      }
    });
  }
  catch (MalformedURLException e) {
    logger.error("Subscription with endpoint {} could not be verified. It will be kept for now.", endpoint);
  }
}
 
Example #5
Source File: SnsExecutor.java    From spring-integration-aws with MIT License 5 votes vote down vote up
private void processSubscriptions() {
	if (subscriptionList != null && !subscriptionList.isEmpty()) {
		for (Subscription subscription : subscriptionList) {
			if (subscription.getProtocol().startsWith("http")) {
				processUrlSubscription(subscription);
			} else {
				// sqs subscription
				processSqsSubscription(subscription);
			}
		}
	}
}
 
Example #6
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 #7
Source File: SnsChannelParserTests.java    From spring-integration-aws with MIT License 5 votes vote down vote up
@Test
public void testSnsChannelParser() {
	setUp("SnsChannelParserTests.xml", getClass(), "snsChannel");

	final SnsExecutor snsExecutor = TestUtils.getPropertyValue(
			this.channel, "snsExecutor", SnsExecutor.class);
	assertNotNull(snsExecutor);

	final String topicNameProperty = TestUtils.getPropertyValue(
			snsExecutor, "topicName", String.class);
	assertEquals("testTopic", topicNameProperty);

	assertEquals(true, TestUtils.getPropertyValue(channel, "autoStartup",
			Boolean.class));

	assertTrue(TestUtils.getPropertyValue(channel, "phase", Integer.class) == 0);

	@SuppressWarnings("unchecked")
	final List<Subscription> subscriptions = TestUtils.getPropertyValue(
			snsExecutor, "subscriptionList", List.class);
	assertThat(subscriptions, is(not(empty())));
	Subscription defS = subscriptions.get(0);
	assertThat(defS.getEndpoint(), containsString("www.example.com"));

	Object snsExecutorProxy = context.getBean("snsExecutorProxy");
	assertNotNull(snsExecutorProxy);
	assertEquals(SnsExecutorProxy.class, snsExecutorProxy.getClass());
	SnsExecutor proxiedExecutor = TestUtils.getPropertyValue(
			snsExecutorProxy, "snsExecutor", SnsExecutor.class);
	assertNotNull(proxiedExecutor);
	SnsExecutor innerBean = context.getBean(SnsExecutor.class);
	assertSame(innerBean, proxiedExecutor);
}
 
Example #8
Source File: SnsParserUtils.java    From spring-integration-aws with MIT License 4 votes vote down vote up
public static void registerSubscriptions(final Element element,
		final ParserContext parserContext,
		final BeanDefinitionBuilder snsExecutorBuilder,
		final String channelAdapterId) {

	List<Subscription> subscriptionList = new ArrayList<Subscription>();
	Map<String, BeanReference> sqsExecutorMap = new ManagedMap<String, BeanReference>();

	// HTTP endpoint
	Element endpointElement = DomUtils.getChildElementByTagName(element,
			"endpoint");
	if (endpointElement != null) {
		String baseURI = endpointElement.getAttribute("base-uri");
		String requestPath = null;
		if (endpointElement.hasAttribute("request-path")) {
			requestPath = endpointElement.getAttribute("request-path");
		} else {
			requestPath = String.format("/%s.do", channelAdapterId);
		}
		subscriptionList.add(new Subscription().withEndpoint(
				baseURI.concat(requestPath)).withProtocol(
				baseURI.startsWith("https") ? "https" : "http"));

		// register a HttpEndpoint at this path
		BeanDefinitionBuilder httpEndpointBuilder = BeanDefinitionBuilder
				.genericBeanDefinition(HttpEndpoint.class);
		String beanName = String
				.format("%s-httpEndpoint", channelAdapterId);
		parserContext.registerBeanComponent(new BeanComponentDefinition(
				httpEndpointBuilder.getBeanDefinition(), beanName,
				new String[] { requestPath }));
		snsExecutorBuilder.addPropertyReference("httpEndpoint", beanName);
	}

	// subscriptions element
	Element subscriptionsElement = DomUtils.getChildElementByTagName(
			element, "subscriptions");
	if (subscriptionsElement != null) {
		NodeList childNodes = subscriptionsElement.getChildNodes();
		for (int i = 0; i < childNodes.getLength(); i++) {
			Node child = childNodes.item(i);
			if (child.getNodeType() == Node.ELEMENT_NODE) {
				Element childElement = (Element) child;
				String localName = child.getLocalName();
				if ("http".equals(localName)) {
					String uri = childElement.getAttribute("base-uri");
					if (childElement.hasAttribute("request-path")) {
						uri = uri.concat(childElement
								.getAttribute("request-path"));
					}
					subscriptionList.add(new Subscription().withEndpoint(
							uri).withProtocol(
							uri.startsWith("https") ? "https" : "http"));

				} else if ("sqs".equals(localName)) {
					String queueArn = null;
					if (childElement.hasAttribute("queue-arn")) {
						queueArn = childElement.getAttribute("queue-arn");
					}
					String queueId = null;
					if (childElement.hasAttribute("queue-id")) {
						queueId = childElement.getAttribute("queue-id");
					}
					Assert.state(queueArn != null || queueId != null,
							"One of 'queue-arn' or 'queue-id' needs to be defined");
					if (queueId != null) {
						String sqsBeanName = SqsParserUtils
								.getExecutorBeanName(queueId);
						snsExecutorBuilder.addDependsOn(sqsBeanName);
						sqsExecutorMap.put(queueId,
								new RuntimeBeanReference(sqsBeanName));
						subscriptionList.add(new Subscription()
								.withEndpoint(queueId).withProtocol("sqs"));

					} else {
						subscriptionList
								.add(new Subscription().withEndpoint(
										queueArn).withProtocol("sqs"));
					}
				}
			}
		}
		if (!sqsExecutorMap.isEmpty()) {
			snsExecutorBuilder.addPropertyValue("sqsExecutorMap",
					sqsExecutorMap);
		}
	}

	snsExecutorBuilder.addPropertyValue("subscriptionList",
			subscriptionList);

}
 
Example #9
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 #10
Source File: SnsExecutor.java    From spring-integration-aws with MIT License 4 votes vote down vote up
public void setSubscriptionList(List<Subscription> subscriptionList) {
	this.subscriptionList = subscriptionList;
}
 
Example #11
Source File: SnsMessageBroker.java    From xyz-hub with Apache License 2.0 2 votes vote down vote up
/**
 * Loads all subscriptions being relevant for the message broker. This includes only those using the HTTP protocol and pointing to an
 * admin messaging endpoint.
 */
private void loadSubscriptions(Handler<AsyncResult<List<Subscription>>> callback) {
  loadSubscriptions(null, callback);
}