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

The following examples show how to use com.amazonaws.services.sns.model.CreateTopicResult. 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: DynamicTopicDestinationResolverTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void resolveDestination_withAutoCreateEnabled_shouldCreateTopicDirectly()
		throws Exception {
	// Arrange
	String topicArn = "arn:aws:sns:eu-west:123456789012:test";

	AmazonSNS sns = mock(AmazonSNS.class);
	when(sns.createTopic(new CreateTopicRequest("test")))
			.thenReturn(new CreateTopicResult().withTopicArn(topicArn));

	DynamicTopicDestinationResolver resolver = new DynamicTopicDestinationResolver(
			sns);
	resolver.setAutoCreate(true);

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

	// Assert
	assertThat(resolvedDestinationName).isEqualTo(topicArn);
}
 
Example #3
Source File: SnsWebhookManager.java    From Singularity with Apache License 2.0 6 votes vote down vote up
private String getOrCreateSnsTopic(WebhookType type) {
  return typeToArn.computeIfAbsent(
    type,
    t -> {
      String topic = webhookConf.getSnsTopics().get(type);
      try {
        LOG.info("Attempting to create sns topic {}", topic);
        CreateTopicRequest createTopicRequest = new CreateTopicRequest(topic);
        CreateTopicResult createTopicResult = snsClient.createTopic(createTopicRequest);
        return createTopicResult.getTopicArn();
      } catch (Throwable th) {
        LOG.error("Could not create sns topic {}", topic, th);
        throw th;
      }
    }
  );
}
 
Example #4
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 #5
Source File: SNSService.java    From oneops with Apache License 2.0 5 votes vote down vote up
/**
 * Sends using the sns publisher
 */
@Override
public boolean postMessage(NotificationMessage nMsg,
                           BasicSubscriber subscriber) {

    SNSSubscriber sub;
    if (subscriber instanceof SNSSubscriber) {
        sub = (SNSSubscriber) subscriber;
    } else {
        throw new ClassCastException("invalid subscriber " + subscriber.getClass().getName());
    }

    SNSMessage msg = buildSNSMessage(nMsg);
    AmazonSNS sns = new AmazonSNSClient(new BasicAWSCredentials(sub.getAwsAccessKey(), sub.getAwsSecretKey()));
    if (sub.getSnsEndpoint() != null) {
        sns.setEndpoint(sub.getSnsEndpoint());
    }

    CreateTopicRequest tRequest = new CreateTopicRequest();
    tRequest.setName(msg.getTopicName());
    CreateTopicResult result = sns.createTopic(tRequest);

    PublishRequest pr = new PublishRequest(result.getTopicArn(), msg.getTxtMessage()).withSubject(msg.getSubject());

    try {
        PublishResult pubresult = sns.publish(pr);
        logger.info("Published msg with id - " + pubresult.getMessageId());
    } catch (AmazonClientException ace) {
        logger.error(ace.getMessage());
        return false;
    }
    return true;
}
 
Example #6
Source File: SNSStashStateListener.java    From emodb with Apache License 2.0 5 votes vote down vote up
private Supplier<String> createTopicSupplier(final String topicName) {
    return Suppliers.memoize(new Supplier<String>() {
        @Override
        public String get() {
            // This will create the topic if it doesn't exist or return the existing topic if it does.
            CreateTopicResult topic = _amazonSNS.createTopic(topicName);
            return topic.getTopicArn();
        }
    });
}
 
Example #7
Source File: SNSImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public Topic createTopic(CreateTopicRequest request,
        ResultCapture<CreateTopicResult> extractor) {

    ActionResult result = service.performAction("CreateTopic", request,
            extractor);

    if (result == null) return null;
    return new TopicImpl(result.getResource());
}
 
Example #8
Source File: SNSImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public Topic createTopic(String name, ResultCapture<CreateTopicResult>
        extractor) {

    CreateTopicRequest request = new CreateTopicRequest()
        .withName(name);
    return createTopic(request, extractor);
}
 
Example #9
Source File: SNSImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public Topic createTopic(String name) {
    return createTopic(name, (ResultCapture<CreateTopicResult>)null);
}
 
Example #10
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 #11
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;
}
 
Example #12
Source File: SpringCloudSNSLiveTest.java    From tutorials with MIT License 3 votes vote down vote up
@BeforeClass
public static void setupAwsResources() {

    topicName = UUID.randomUUID().toString();

    AmazonSNS amazonSNS = SpringCloudAwsTestUtil.amazonSNS();

    CreateTopicResult result = amazonSNS.createTopic(topicName);
    topicArn = result.getTopicArn();
}
 
Example #13
Source File: SNS.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>CreateTopic</code> action and use a ResultCapture to
 * retrieve the low-level client response.
 *
 * <p>
 *
 * @return The <code>Topic</code> resource object associated with the result
 *         of this action.
 * @see CreateTopicRequest
 */
com.amazonaws.resources.sns.Topic createTopic(CreateTopicRequest request,
        ResultCapture<CreateTopicResult> extractor);
 
Example #14
Source File: SNS.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * The convenient method form for the <code>CreateTopic</code> action.
 *
 * @see #createTopic(CreateTopicRequest, ResultCapture)
 */
com.amazonaws.resources.sns.Topic createTopic(String name,
        ResultCapture<CreateTopicResult> extractor);