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

The following examples show how to use com.amazonaws.services.sns.model.Topic. 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: AWSSNSMetaDataExtension.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<MetaData> meta(Map<String, Object> parameters) {
    final String accessKey = ConnectorOptions.extractOption(parameters, "accessKey");
    final String secretKey = ConnectorOptions.extractOption(parameters, "secretKey");
    final String region = ConnectorOptions.extractOption(parameters, "region");
    AmazonSNSClientBuilder clientBuilder;
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
    clientBuilder = AmazonSNSClientBuilder.standard().withCredentials(credentialsProvider);
    clientBuilder = clientBuilder.withRegion(Regions.valueOf(region));
    AmazonSNS sqsClient = clientBuilder.build();
    try {
        ListTopicsResult result = sqsClient.listTopics();
        Set<String> setTopic = new HashSet<String>();
        if (result.getTopics() != null) {
            for (Topic entry : result.getTopics()) {
            	setTopic.add(entry.getTopicArn());
            }
        }
        return Optional.of(MetaDataBuilder.on(getCamelContext()).withAttribute(MetaData.CONTENT_TYPE, "text/plain").withAttribute(MetaData.JAVA_TYPE, String.class)
            .withPayload(setTopic).build());
    } catch (Exception e) {
        throw new IllegalStateException("Get information about existing topics with has failed.", e);
    }
}
 
Example #2
Source File: SnsExecutor.java    From spring-integration-aws with MIT License 6 votes vote down vote up
private void createTopicIfNotExists() {
	for (Topic topic : client.listTopics().getTopics()) {
		if (topic.getTopicArn().contains(topicName)) {
			topicArn = topic.getTopicArn();
			break;
		}
	}
	if (topicArn == null) {
		CreateTopicRequest request = new CreateTopicRequest(topicName);
		CreateTopicResult result = client.createTopic(request);
		topicArn = result.getTopicArn();
		log.debug("Topic created, arn: " + topicArn);
	} else {
		log.debug("Topic already created: " + topicArn);
	}
}
 
Example #3
Source File: TemporarySQSQueue.java    From front50 with Apache License 2.0 6 votes vote down vote up
private String getSnsTopicArn(AmazonSNS amazonSNS, String topicName) {
  ListTopicsResult listTopicsResult = amazonSNS.listTopics();
  String nextToken = listTopicsResult.getNextToken();
  List<Topic> topics = listTopicsResult.getTopics();

  while (nextToken != null) {
    listTopicsResult = amazonSNS.listTopics(nextToken);
    nextToken = listTopicsResult.getNextToken();
    topics.addAll(listTopicsResult.getTopics());
  }

  return topics.stream()
      .filter(t -> t.getTopicArn().toLowerCase().endsWith(":" + topicName.toLowerCase()))
      .map(Topic::getTopicArn)
      .findFirst()
      .orElseThrow(
          () ->
              new IllegalArgumentException("No SNS topic found (topicName: " + topicName + ")"));
}
 
Example #4
Source File: NotificationMessagingTemplateTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void convertAndSend_withPayloadAndSubject_shouldSetSubject() throws Exception {
	// Arrange
	AmazonSNS amazonSns = mock(AmazonSNS.class);
	NotificationMessagingTemplate notificationMessagingTemplate = new NotificationMessagingTemplate(
			amazonSns);
	String physicalTopicName = "arn:aws:sns:eu-west:123456789012:test";
	when(amazonSns.listTopics(new ListTopicsRequest(null)))
			.thenReturn(new ListTopicsResult()
					.withTopics(new Topic().withTopicArn(physicalTopicName)));
	notificationMessagingTemplate.setDefaultDestinationName(physicalTopicName);

	// Act
	notificationMessagingTemplate.sendNotification("My message", "My subject");

	// Assert
	verify(amazonSns)
			.publish(new PublishRequest(physicalTopicName, "My message", "My subject")
					.withMessageAttributes(isNotNull()));
}
 
Example #5
Source File: NotificationMessagingTemplateTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void convertAndSend_withDestinationPayloadAndSubject_shouldSetSubject()
		throws Exception {
	// Arrange
	AmazonSNS amazonSns = mock(AmazonSNS.class);
	NotificationMessagingTemplate notificationMessagingTemplate = new NotificationMessagingTemplate(
			amazonSns);
	String physicalTopicName = "arn:aws:sns:eu-west:123456789012:test";
	when(amazonSns.listTopics(new ListTopicsRequest(null)))
			.thenReturn(new ListTopicsResult()
					.withTopics(new Topic().withTopicArn(physicalTopicName)));

	// Act
	notificationMessagingTemplate.sendNotification(physicalTopicName, "My message",
			"My subject");

	// Assert
	verify(amazonSns)
			.publish(new PublishRequest(physicalTopicName, "My message", "My subject")
					.withMessageAttributes(isNotNull()));
}
 
Example #6
Source File: NotificationMessagingTemplateTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void send_validTextMessage_usesTopicChannel() throws Exception {
	// Arrange
	AmazonSNS amazonSns = mock(AmazonSNS.class);
	NotificationMessagingTemplate notificationMessagingTemplate = new NotificationMessagingTemplate(
			amazonSns);
	String physicalTopicName = "arn:aws:sns:eu-west:123456789012:test";
	when(amazonSns.listTopics(new ListTopicsRequest(null)))
			.thenReturn(new ListTopicsResult()
					.withTopics(new Topic().withTopicArn(physicalTopicName)));
	notificationMessagingTemplate.setDefaultDestinationName(physicalTopicName);

	// Act
	notificationMessagingTemplate
			.send(MessageBuilder.withPayload("Message content").build());

	// Assert
	verify(amazonSns)
			.publish(new PublishRequest(physicalTopicName, "Message content", null)
					.withMessageAttributes(isNotNull()));
}
 
Example #7
Source File: DynamicTopicDestinationResolverTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void resolveDestination_withResourceIdResolver_shouldCallIt() throws Exception {
	// Arrange
	String physicalTopicName = "arn:aws:sns:eu-west:123456789012:myTopic";
	String logicalTopicName = "myTopic";

	ResourceIdResolver resourceIdResolver = mock(ResourceIdResolver.class);
	when(resourceIdResolver.resolveToPhysicalResourceId(logicalTopicName))
			.thenReturn(physicalTopicName);

	AmazonSNS sns = mock(AmazonSNS.class);
	when(sns.listTopics(new ListTopicsRequest(null)))
			.thenReturn(new ListTopicsResult()
					.withTopics(new Topic().withTopicArn(physicalTopicName)));

	DynamicTopicDestinationResolver resolver = new DynamicTopicDestinationResolver(
			sns, resourceIdResolver);

	// Assert
	String resolvedDestinationName = resolver.resolveDestination(logicalTopicName);

	// Assert
	assertThat(resolvedDestinationName).isEqualTo(physicalTopicName);
}
 
Example #8
Source File: DynamicTopicDestinationResolverTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void resolveDestination_withExistentTopicAndMarker_returnsTopicArnFoundWhileListingTopic()
		throws Exception {
	// Arrange

	AmazonSNS sns = mock(AmazonSNS.class);
	when(sns.listTopics(new ListTopicsRequest(null)))
			.thenReturn(new ListTopicsResult().withNextToken("mark"));

	String topicArn = "arn:aws:sns:eu-west:123456789012:test";
	when(sns.listTopics(new ListTopicsRequest("mark"))).thenReturn(
			new ListTopicsResult().withTopics(new Topic().withTopicArn(topicArn)));

	DynamicTopicDestinationResolver resolver = new DynamicTopicDestinationResolver(
			sns);

	// Act
	String resolvedDestinationName = resolver.resolveDestination("test");

	// Assert
	assertThat(resolvedDestinationName).isEqualTo(topicArn);
}
 
Example #9
Source File: DynamicTopicDestinationResolverTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void resolveDestination_withExistentTopic_returnsTopicArnFoundWhileListingTopic()
		throws Exception {
	// Arrange
	String topicArn = "arn:aws:sns:eu-west:123456789012:test";

	AmazonSNS sns = mock(AmazonSNS.class);
	when(sns.listTopics(new ListTopicsRequest(null))).thenReturn(
			new ListTopicsResult().withTopics(new Topic().withTopicArn(topicArn)));

	DynamicTopicDestinationResolver resolver = new DynamicTopicDestinationResolver(
			sns);

	// Act
	String resolvedDestinationName = resolver.resolveDestination("test");

	// Assert
	assertThat(resolvedDestinationName).isEqualTo(topicArn);
}
 
Example #10
Source File: DynamicTopicDestinationResolver.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
private String getTopicResourceName(String marker, String topicName) {
	ListTopicsResult listTopicsResult = this.amazonSns
			.listTopics(new ListTopicsRequest(marker));
	for (Topic topic : listTopicsResult.getTopics()) {
		AmazonResourceName resourceName = AmazonResourceName
				.fromString(topic.getTopicArn());
		if (resourceName.getResourceType().equals(topicName)) {
			return topic.getTopicArn();
		}
	}

	if (StringUtils.hasText(listTopicsResult.getNextToken())) {
		return getTopicResourceName(listTopicsResult.getNextToken(), topicName);
	}
	else {
		throw new IllegalArgumentException(
				"No topic found for name :'" + topicName + "'");
	}
}
 
Example #11
Source File: DefaultSnsTopicResourceFactoryTest.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateSnsTopicResource_withName() throws Exception {
    // Given
    final String name = randomString();
    final String topicArn = topicArnForName(name);
    final List<Topic> topics = Arrays.asList(randomTopic(), randomTopic(), topicForArn(topicArn), randomTopic());
    final ListTopicsResult mockListTopicsResult = mock(ListTopicsResult.class);
    when(mockListTopicsResult.getTopics()).thenReturn(topics);
    when(mockListTopicsResult.getNextToken()).thenReturn(null);
    final String nextToken = null;
    when(mockAmazonSnsClient.listTopics(nextToken)).thenReturn(mockListTopicsResult);
    final SnsTopicResource mockSnsTopicResource = mock(SnsTopicResource.class);
    whenNew(SnsTopicResource.class).withArguments(name, topicArn, mockAmazonSnsClient)
            .thenReturn(mockSnsTopicResource);

    // When
    final SnsTopicResource result = factory.createSnsTopicResource(name);

    // Then
    assertSame(mockSnsTopicResource, result);
}
 
Example #12
Source File: SNSManager.java    From AWS-MIMIC-IIItoOMOP with Apache License 2.0 6 votes vote down vote up
public PublishResult publishFailure(String topicName, String table, String stack) 
{
    PublishResult result = null;
    
    for(Topic topic : sns.listTopics().getTopics())
    {
        if(sns.getTopicAttributes(topic.getTopicArn()).getAttributes().get("DisplayName").equals(topicName))
        {
            PublishRequest publishRequest = new PublishRequest(topic.getTopicArn(), "[ERROR]: " + table + " table was not able to be staged in S3. \n\n" + stack);
    
            result = sns.publish(publishRequest);
        }
        
    }
    return result;
}
 
Example #13
Source File: SNSManager.java    From AWS-MIMIC-IIItoOMOP with Apache License 2.0 6 votes vote down vote up
public PublishResult publishSuccess(String topicName, String table) 
{
    PublishResult result = null;
    
    for(Topic topic : sns.listTopics().getTopics())
    {
        if(sns.getTopicAttributes(topic.getTopicArn()).getAttributes().get("DisplayName").equals(topicName))
        {
            PublishRequest publishRequest = new PublishRequest(topic.getTopicArn(), table + " table has been staged in S3");
    
            result = sns.publish(publishRequest);
        }
        
    }
    return result;
}
 
Example #14
Source File: DefaultSnsTopicResourceFactory.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
private String topicArnForNameInTopics(final String name, final List<Topic> topics) {
    final String topicArnSuffix = ":" + name;
    for (final Topic topic : topics) {
        final String topicArn = topic.getTopicArn();
        final int pos = topicArn.lastIndexOf(topicArnSuffix);
        if (pos == -1) {
            continue;
        }
        final String actualName = topicArn.substring(pos + 1);
        if (actualName.equals(name)) {
            return topicArn;
        }
    }
    return null;
}
 
Example #15
Source File: FileManager.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate SNS topics.
 *
 * @param topicMap the subscription map
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void generateSNSTopics(Map<String, List<Topic>> topicMap) throws IOException {
	String fieldNames;
	String keys;
	fieldNames = "topicArn";
	keys = "discoverydate`accountid`accountname`region`topicarn";
	FileGenerator.generateJson(topicMap, fieldNames, "aws-snstopic.data",keys);

}
 
Example #16
Source File: DefaultSnsTopicResourceFactoryTest.java    From Cheddar with Apache License 2.0 4 votes vote down vote up
private Topic randomTopic() {
    return topicForArn(topicArnForName(randomString(20)));
}
 
Example #17
Source File: DefaultSnsTopicResourceFactoryTest.java    From Cheddar with Apache License 2.0 4 votes vote down vote up
private Topic topicForArn(final String topicArn) {
    return new Topic().withTopicArn(topicArn);
}
 
Example #18
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 #19
Source File: AmazonNotificationUtils.java    From usergrid with Apache License 2.0 4 votes vote down vote up
public static String getTopicArn( final AmazonSNSClient sns, final String queueName, final boolean createOnMissing )
    throws Exception {

    if ( logger.isTraceEnabled() ) {
        logger.trace( "Looking up Topic ARN: {}", queueName );
    }

    ListTopicsResult listTopicsResult = sns.listTopics();
    String topicArn = null;

    for ( Topic topic : listTopicsResult.getTopics() ) {
        String arn = topic.getTopicArn();

        if ( queueName.equals( arn.substring( arn.lastIndexOf( ':' ) ) ) ) {
            topicArn = arn;

            if (logger.isTraceEnabled()) {
                logger.trace( "Found existing topic arn=[{}] for queue=[{}]", topicArn, queueName );
            }
        }
    }

    if ( topicArn == null && createOnMissing ) {
        if (logger.isTraceEnabled()) {
            logger.trace("Creating topic for queue=[{}]...", queueName);
        }

        CreateTopicResult createTopicResult = sns.createTopic( queueName );
        topicArn = createTopicResult.getTopicArn();

        if (logger.isTraceEnabled()) {
            logger.trace("Successfully created topic with name {} and arn {}", queueName, topicArn);
        }
    }
    else {
        logger.error( "Error looking up topic ARN for queue=[{}] and createOnMissing=[{}]", queueName,
            createOnMissing );
    }

    if ( logger.isTraceEnabled() ) {
        logger.trace( "Returning Topic ARN=[{}] for Queue=[{}]", topicArn, queueName );
    }


    return topicArn;
}