Java Code Examples for com.amazonaws.services.sns.model.ListTopicsResult#getTopics()

The following examples show how to use com.amazonaws.services.sns.model.ListTopicsResult#getTopics() . 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: 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 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: 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 5
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;
}