Example usage for com.amazonaws.services.sns AmazonSNSClient AmazonSNSClient

List of usage examples for com.amazonaws.services.sns AmazonSNSClient AmazonSNSClient

Introduction

In this page you can find the example usage for com.amazonaws.services.sns AmazonSNSClient AmazonSNSClient.

Prototype

AmazonSNSClient(AwsSyncClientParams clientParams) 

Source Link

Document

Constructs a new client to invoke service methods on Amazon SNS using the specified parameters.

Usage

From source file:net.smartcosmos.plugin.service.aws.notification.AwsNotificationService.java

License:Apache License

@Override
public void deleteTopic(INotificationEndpoint notificationEndpoint) {
    Preconditions.checkArgument((notificationEndpoint != null), "Notification endpoint must not be null");

    Preconditions.checkArgument((notificationEndpoint.getTopicArn() != null),
            "Notification Topic ARN must not be null");

    AmazonSNS sns = new AmazonSNSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sns.setRegion(usEast1);//from  ww w . j a va2s.  co m

    try {
        DeleteTopicRequest request = new DeleteTopicRequest(notificationEndpoint.getTopicArn());
        sns.deleteTopic(request);
    } finally {
        sns.shutdown();
    }

    //
    // Event
    //
    INotificationResultObject<IAccount> nro = new NotificationResultObject<>(EntityReferenceType.Account,
            notificationEndpoint.getAccount(), "");
    IEventService eventService = context.getServiceFactory().getEventService(notificationEndpoint.getAccount());
    eventService.recordEvent(EventType.NotificationWithdrawn, notificationEndpoint.getAccount(), null, nro);
}

From source file:net.smartcosmos.plugin.service.aws.notification.AwsNotificationService.java

License:Apache License

@Override
public void publish(INotificationEndpoint notificationEndpoint, String json) {
    Preconditions.checkArgument((notificationEndpoint != null), "Endpoint must not be null");

    Preconditions.checkArgument((notificationEndpoint.getTopicArn() != null),
            "Endpoint is missing a notification URL definition");

    Preconditions.checkArgument((!notificationEndpoint.isPendingConfirmation()),
            "Endpoint has not yet been confirmed");

    AmazonSNS sns = new AmazonSNSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sns.setRegion(usEast1);/*from  ww  w . ja  va  2 s .c o m*/

    try {
        String subject = "SMART COSMOS Objects Event Notification";

        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(json);
            if (jsonObject.has(EVENT_TYPE)) {
                String eventType = jsonObject.getString(EVENT_TYPE);
                subject = "Objects Event: " + eventType;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        PublishRequest request = new PublishRequest(notificationEndpoint.getTopicArn(), json, subject);
        PublishResult result = sns.publish(request);

        //
        // Event
        //
        INotificationResultObject<IAccount> nro = new NotificationResultObject<>(EntityReferenceType.Account,
                notificationEndpoint.getAccount(), result.getMessageId());
        IEventService eventService = context.getServiceFactory()
                .getEventService(notificationEndpoint.getAccount());
        eventService.recordEvent(EventType.NotificationBroadcast, notificationEndpoint.getAccount(), null, nro);

    } finally {
        sns.shutdown();
    }
}

From source file:net.smartcosmos.plugin.service.aws.notification.AwsNotificationService.java

License:Apache License

@Override
public void unsubscribe(INotificationEndpoint notificationEndpoint) {
    Preconditions.checkArgument((notificationEndpoint != null), "Notification endpoint must not be null");

    AmazonSNS sns = new AmazonSNSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sns.setRegion(usEast1);/*  w ww .  j av a  2 s.c om*/

    try {

        UnsubscribeRequest request = new UnsubscribeRequest(notificationEndpoint.getSubscriptionArn());
        sns.unsubscribe(request);

        //
        // Event
        //
        INotificationResultObject<IAccount> nro = new NotificationResultObject<>(EntityReferenceType.Account,
                notificationEndpoint.getAccount(), "");
        IEventService eventService = context.getServiceFactory()
                .getEventService(notificationEndpoint.getAccount());
        eventService.recordEvent(EventType.NotificationUnsubscribe, notificationEndpoint.getAccount(), null,
                nro);
    } finally {
        sns.shutdown();
    }
}

From source file:net.smartcosmos.plugin.service.aws.notification.AwsNotificationService.java

License:Apache License

@Override
public void confirmSubscription(INotificationEndpoint notificationEndpoint, String token) {
    Preconditions.checkArgument((notificationEndpoint != null), "Notification endpoint must not be null");

    Preconditions.checkArgument((notificationEndpoint.getTopicArn() != null),
            "Notification Topic ARN must not be null");

    AmazonSNS sns = new AmazonSNSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sns.setRegion(usEast1);//from   w w  w.j  ava 2 s  . co m

    try {
        ConfirmSubscriptionRequest request = new ConfirmSubscriptionRequest(notificationEndpoint.getTopicArn(),
                token);

        ConfirmSubscriptionResult result = sns.confirmSubscription(request);

        //
        // Event
        //
        INotificationResultObject<IAccount> nro = new NotificationResultObject<>(EntityReferenceType.Account,
                notificationEndpoint.getAccount(), result.getSubscriptionArn());
        IEventService eventService = context.getServiceFactory()
                .getEventService(notificationEndpoint.getAccount());
        eventService.recordEvent(EventType.NotificationSubscriptionConfirmed, notificationEndpoint.getAccount(),
                null, nro);
    } finally {
        sns.shutdown();
    }
}

From source file:net.smartcosmos.plugin.service.aws.notification.AwsNotificationService.java

License:Apache License

@Override
public boolean isHealthy() {
    try {/* w ww  . j  a  v  a 2s  .c om*/
        AmazonSNS sns = new AmazonSNSClient(credentials);
        Region usEast1 = Region.getRegion(Regions.US_EAST_1);
        sns.setRegion(usEast1);
        sns.listTopics();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.apache.camel.component.aws.sns.SnsEndpoint.java

License:Apache License

/**
 * Provide the possibility to override this method for an mock implementation
 *
 * @return AmazonSNSClient/*  w w w  .ja v  a 2 s . c o  m*/
 */
AmazonSNS createSNSClient() {
    AWSCredentials credentials = new BasicAWSCredentials(configuration.getAccessKey(),
            configuration.getSecretKey());
    AmazonSNS client = new AmazonSNSClient(credentials);
    if (configuration.getAmazonSNSEndpoint() != null) {
        client.setEndpoint(configuration.getAmazonSNSEndpoint());
    }
    return client;
}

From source file:org.springframework.cloud.aws.messaging.config.annotation.SnsConfiguration.java

License:Apache License

@ConditionalOnMissingAmazonClient(AmazonSNS.class)
@Bean/*from www  .  ja v  a 2  s. co m*/
public AmazonSNS amazonSNS() {
    AmazonSNSClient amazonSNSClient;
    if (this.awsCredentialsProvider != null) {
        amazonSNSClient = new AmazonSNSClient(this.awsCredentialsProvider);
    } else {
        amazonSNSClient = new AmazonSNSClient();
    }

    if (this.regionProvider != null) {
        amazonSNSClient.setRegion(this.regionProvider.getRegion());
    }

    return amazonSNSClient;
}

From source file:org.traccar.database.DataManager.java

License:Apache License

/**
 * Initialize database//from   w  w w .ja  va 2 s .c o m
 */
private void initDatabase(Properties properties) throws Exception {

    // Load driver
    String driver = properties.getProperty("database.driver");
    if (driver != null) {
        String driverFile = properties.getProperty("database.driverFile");

        if (driverFile != null) {
            URL url = new URL("jar:file:" + new File(driverFile).getAbsolutePath() + "!/");
            URLClassLoader cl = new URLClassLoader(new URL[] { url });
            Driver d = (Driver) Class.forName(driver, true, cl).newInstance();
            DriverManager.registerDriver(new DriverDelegate(d));
        } else {
            Class.forName(driver);
        }
    }

    // Initialize data source
    ComboPooledDataSource ds = new ComboPooledDataSource();
    ds.setDriverClass(properties.getProperty("database.driver"));
    ds.setJdbcUrl(properties.getProperty("database.url"));
    ds.setUser(properties.getProperty("database.user"));
    ds.setPassword(properties.getProperty("database.password"));
    ds.setIdleConnectionTestPeriod(600);
    ds.setTestConnectionOnCheckin(true);
    dataSource = ds;

    // Load statements from configuration
    String query;

    query = properties.getProperty("database.selectDevice");
    if (query != null) {
        queryGetDevices = new NamedParameterStatement(query, dataSource);
    }

    awsAccessKeyId = properties.getProperty("aws.accessKey");
    awsSecretAccessKey = properties.getProperty("aws.accessSecret");
    String awsSQSQueueName = properties.getProperty("aws.queueName");

    if (awsAccessKeyId != null && awsSecretAccessKey != null) {
        AWSCredentialsProvider credentialsProvider = new AWSCredentialsProvider() {
            @Override
            public AWSCredentials getCredentials() {
                return new AWSCredentials() {
                    @Override
                    public String getAWSAccessKeyId() {
                        return awsAccessKeyId;
                    }

                    @Override
                    public String getAWSSecretKey() {
                        return awsSecretAccessKey;
                    }
                };
            }

            @Override
            public void refresh() {

            }
        };
        snsClient = new AmazonSNSClient(credentialsProvider);
        snsClient.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1));
        GsonBuilder builder = new GsonBuilder();
        gson = builder.create();

        if (awsSQSQueueName != null) {
            // Create the connection factory using the environment variable credential provider.
            // Connections this factory creates can talk to the queues in us-east-1 region.
            SQSConnectionFactory connectionFactory = SQSConnectionFactory.builder()
                    .withRegion(Region.getRegion(Regions.AP_SOUTHEAST_1))
                    .withAWSCredentialsProvider(credentialsProvider).build();

            // Create the connection.
            SQSConnection connection = connectionFactory.createConnection();

            // Get the wrapped client
            AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient();

            // Create an SQS queue named 'TestQueue'  if it does not already exist.
            if (!client.queueExists(awsSQSQueueName)) {
                client.createQueue(awsSQSQueueName);
            }

            // Create the non-transacted session with AUTO_ACKNOWLEDGE mode
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // Create a queue identity with name 'TestQueue' in the session
            Queue queue = session.createQueue(awsSQSQueueName);

            // Create a consumer for the 'TestQueue'.
            MessageConsumer consumer = session.createConsumer(queue);

            // Instantiate and set the message listener for the consumer.
            consumer.setMessageListener(new AWSSqsMessageListener());

            // Start receiving incoming messages.
            connection.start();
        }
    }

    query = properties.getProperty("database.insertPosition");
    if (query != null) {
        queryAddPosition = new NamedParameterStatement(query, dataSource, Statement.RETURN_GENERATED_KEYS);
    }

    query = properties.getProperty("database.updatePosition");
    if (query != null) {
        queryUpdatePosition = new NamedParameterStatement(query, dataSource);
    }

    query = properties.getProperty("database.updateLatestPosition");
    if (query != null) {
        queryUpdateLatestPosition = new NamedParameterStatement(query, dataSource);
    }
}

From source file:org.transitime.maintenance.AwsGlacier.java

License:Open Source License

/********************** Member Functions **************************/

public AwsGlacier(String region) {
    // Get credentials from credentials file, environment variable, or 
    // Java property. 
    // See http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/auth/DefaultAWSCredentialsProviderChain.html
    AWSCredentialsProviderChain credentialsProvider = new DefaultAWSCredentialsProviderChain();
    credentials = credentialsProvider.getCredentials();
    logger.debug("Read in credentials AWSAccessKeyId={} AWSSecretKey={}...", credentials.getAWSAccessKeyId(),
            credentials.getAWSSecretKey().substring(0, 4));

    // Create the glacier client and set to specified region.
    glacierClient = new AmazonGlacierClient(credentials);
    glacierClient.setEndpoint("https://glacier." + region + ".amazonaws.com");

    // Set up params needed for retrieving vault inventory
    sqsClient = new AmazonSQSClient(credentials);
    sqsClient.setEndpoint("https://sqs." + region + ".amazonaws.com");
    snsClient = new AmazonSNSClient(credentials);
    snsClient.setEndpoint("https://sns." + region + ".amazonaws.com");

    // Create the ArchiveTransferManager used for uploading and 
    // downloading files. Need to use ArchiveTransferManager constructor 
    // that allows one to specify sqsClient & snsClient so that they have
    // the proper region. If use ArchiveTransferManager without specifying
    // sqs and sns clients then default ones are constructed, but these
    // use the default Virginia region, which is wrong.
    atm = new ArchiveTransferManager(glacierClient, sqsClient, snsClient);
}

From source file:org.transitime.maintenance.AwsGlacierInventoryRetriever.java

License:Open Source License

/********************** Member Functions **************************/

public AwsGlacierInventoryRetriever(String region) {
    // Get credentials from credentials file, environment variable, or 
    // Java property. 
    // See http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/auth/DefaultAWSCredentialsProviderChain.html
    AWSCredentialsProviderChain credentialsProvider = new DefaultAWSCredentialsProviderChain();
    AWSCredentials credentials = credentialsProvider.getCredentials();
    logger.debug("Read in credentials AWSAccessKeyId={} AWSSecretKey={}...", credentials.getAWSAccessKeyId(),
            credentials.getAWSSecretKey().substring(0, 4));

    // Create the glacier client and set to specified region.
    glacierClient = new AmazonGlacierClient(credentials);
    glacierClient.setEndpoint("https://glacier." + region + ".amazonaws.com");

    // Set up params needed for retrieving vault inventory
    sqsClient = new AmazonSQSClient(credentials);
    sqsClient.setEndpoint("https://sqs." + region + ".amazonaws.com");
    snsClient = new AmazonSNSClient(credentials);
    snsClient.setEndpoint("https://sns." + region + ".amazonaws.com");
    setupSQS();//from   w  w  w  .  j  av a 2  s .c  o m
    setupSNS();
}