Example usage for com.amazonaws.services.kinesis.model PutRecordResult getSequenceNumber

List of usage examples for com.amazonaws.services.kinesis.model PutRecordResult getSequenceNumber

Introduction

In this page you can find the example usage for com.amazonaws.services.kinesis.model PutRecordResult getSequenceNumber.

Prototype


public String getSequenceNumber() 

Source Link

Document

The sequence number identifier that was assigned to the put data record.

Usage

From source file:kinesisAlertAnalysis.java

License:Open Source License

public static void main(String[] args) throws Exception {

    init();/*from  w w w.  java2s.com*/

    final String myStreamName = "alertsStream";
    final Integer myStreamSize = 1;

    /*
     * The ProfileCredentialsProvider will return your [awsReilly]
     * credential profile by reading from the credentials file located at
     * (/Users/johnreilly/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("jreilly").getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (/Users/johnreilly/.aws/credentials), and is in valid format.", e);
    }

    // Describe the stream and check if it exists.
    DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest().withStreamName(myStreamName);
    try {
        StreamDescription streamDescription = kinesis.describeStream(describeStreamRequest)
                .getStreamDescription();
        System.out.printf("Stream %s has a status of %s.\n", myStreamName, streamDescription.getStreamStatus());

        if ("DELETING".equals(streamDescription.getStreamStatus())) {
            System.out.println("Stream is being deleted. This sample will now exit.");
            System.exit(0);
        }

        // Wait for the stream to become active if it is not yet ACTIVE.
        if (!"ACTIVE".equals(streamDescription.getStreamStatus())) {
            waitForStreamToBecomeAvailable(myStreamName);
        }
    } catch (ResourceNotFoundException ex) {
        System.out.printf("Stream %s does not exist. Creating it now.\n", myStreamName);

        // Create a stream. The number of shards determines the provisioned throughput.
        CreateStreamRequest createStreamRequest = new CreateStreamRequest();
        createStreamRequest.setStreamName(myStreamName);
        createStreamRequest.setShardCount(myStreamSize);
        kinesis.createStream(createStreamRequest);
        // The stream is now being created. Wait for it to become active.
        waitForStreamToBecomeAvailable(myStreamName);
    }

    // List all of my streams.
    ListStreamsRequest listStreamsRequest = new ListStreamsRequest();
    listStreamsRequest.setLimit(10);
    ListStreamsResult listStreamsResult = kinesis.listStreams(listStreamsRequest);
    List<String> streamNames = listStreamsResult.getStreamNames();
    while (listStreamsResult.isHasMoreStreams()) {
        if (streamNames.size() > 0) {
            listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1));
        }

        listStreamsResult = kinesis.listStreams(listStreamsRequest);
        streamNames.addAll(listStreamsResult.getStreamNames());
    }
    // Print all of my streams.
    System.out.println("List of my streams: ");
    for (int i = 0; i < streamNames.size(); i++) {
        System.out.println("\t- " + streamNames.get(i));
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usEast1);

    System.out.println("");
    System.out.println("===========================================");
    System.out.println("Getting Started with sqsAlertCache");
    System.out.println("===========================================\n");

    try {

        String thisQueue = "alertCache";
        String nextQueue = "alertReceive";

        // Receive messages
        System.out.println("Receiving messages from " + thisQueue + ".");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(thisQueue);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        System.out.println("Message count for " + thisQueue + ": " + messages.size() + "\n");

        for (Message message : messages) {

            System.out.println("  Message");
            System.out.println("    MessageId:     " + message.getMessageId());
            System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
            System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
            System.out.println("    Body:          " + message.getBody());
            for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
            System.out.println();

            // Write record to the stream
            long createTime = System.currentTimeMillis();
            PutRecordRequest putRecordRequest = new PutRecordRequest();
            putRecordRequest.setStreamName(myStreamName);
            putRecordRequest.setData(ByteBuffer.wrap(String.format(message.getBody(), createTime).getBytes()));
            putRecordRequest.setPartitionKey(String.format("partitionKey-%d", createTime));
            PutRecordResult putRecordResult = kinesis.putRecord(putRecordRequest);
            System.out.printf(
                    "Successfully put record, partition key : %s, ShardID : %s, SequenceNumber : %s.\n",
                    putRecordRequest.getPartitionKey(), putRecordResult.getShardId(),
                    putRecordResult.getSequenceNumber());

            // then send message to cache queue
            System.out.println("Sending messages to next queue.");
            sqs.sendMessage(new SendMessageRequest(nextQueue, message.getBody()));

            // delete message after sending to persist queue
            System.out.println("Deleting message from this queue.\n");
            String messageRecieptHandle = message.getReceiptHandle();
            sqs.deleteMessage(new DeleteMessageRequest(thisQueue, messageRecieptHandle));
        }

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:sqsAlertStream.java

License:Open Source License

public static void main(String[] args) throws Exception {

    // get credentials
    String user = "jreilly";
    AWSCredentials credentials = whgHelper.getCred(user);

    // use credentials to set access to SQS
    AmazonSQS sqs = whgHelper.setQueueAccess(credentials);

    // define queue that messages will be retrieved from
    String thisQueue = "alertStream";
    String nextQueue = "alertErrorHandling";

    // set access to stream instance
    kinesis = new AmazonKinesisClient(credentials);

    final String streamName = "alertsStream";
    final Integer streamSize = 1;

    while (1 > 0) {

        // pull list of current messages (up to 10) in the queue
        List<Message> messages = whgHelper.getMessagesFromQueue(thisQueue, sqs);
        System.out.println("Count of messages in " + thisQueue + ": " + messages.size());

        try {//from   w  w w  .ja va2  s  . co m

            for (Message message : messages) {

                whgHelper.printMessage(message);
                for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                    whgHelper.printMessageEntry(entry);
                }

                // Write record to the stream
                long createTime = System.currentTimeMillis();
                PutRecordRequest putRecordRequest = new PutRecordRequest();
                putRecordRequest.setStreamName(streamName);
                putRecordRequest
                        .setData(ByteBuffer.wrap(String.format(message.getBody(), createTime).getBytes()));
                putRecordRequest.setPartitionKey(String.format("partitionKey-%d", createTime));
                PutRecordResult putRecordResult = kinesis.putRecord(putRecordRequest);
                System.out.printf(
                        "Successfully put record, partition key : %s, ShardID : %s, SequenceNumber : %s.\n",
                        putRecordRequest.getPartitionKey(), putRecordResult.getShardId(),
                        putRecordResult.getSequenceNumber());

                // then send message to cache queue
                System.out.println("Sending messages to next queue.");
                sqs.sendMessage(new SendMessageRequest(nextQueue, message.getBody()));

                // delete message after sending to persist queue
                System.out.println("Deleting message from this queue.\n");
                String messageRecieptHandle = message.getReceiptHandle();
                sqs.deleteMessage(new DeleteMessageRequest(thisQueue, messageRecieptHandle));
            }
            Thread.sleep(20000); // do nothing for 1000 miliseconds (1 second)

        } catch (AmazonServiceException ase) {
            whgHelper.errorMessagesAse(ase);
        } catch (AmazonClientException ace) {
            whgHelper.errorMessagesAce(ace);
        }
    }
}

From source file:AmazonKinesisRecordProducerSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//  www .jav a  2  s  . co m

    final String myStreamName = AmazonKinesisApplicationSample.SAMPLE_APPLICATION_STREAM_NAME;
    final Integer myStreamSize = 1;

    // Describe the stream and check if it exists.
    DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest().withStreamName(myStreamName);
    try {
        StreamDescription streamDescription = kinesis.describeStream(describeStreamRequest)
                .getStreamDescription();
        System.out.printf("Stream %s has a status of %s.\n", myStreamName, streamDescription.getStreamStatus());

        if ("DELETING".equals(streamDescription.getStreamStatus())) {
            System.out.println("Stream is being deleted. This sample will now exit.");
            System.exit(0);
        }

        // Wait for the stream to become active if it is not yet ACTIVE.
        if (!"ACTIVE".equals(streamDescription.getStreamStatus())) {
            waitForStreamToBecomeAvailable(myStreamName);
        }
    } catch (ResourceNotFoundException ex) {
        System.out.printf("Stream %s does not exist. Creating it now.\n", myStreamName);

        // Create a stream. The number of shards determines the provisioned throughput.
        CreateStreamRequest createStreamRequest = new CreateStreamRequest();
        createStreamRequest.setStreamName(myStreamName);
        createStreamRequest.setShardCount(myStreamSize);
        kinesis.createStream(createStreamRequest);
        // The stream is now being created. Wait for it to become active.
        waitForStreamToBecomeAvailable(myStreamName);
    }

    // List all of my streams.
    ListStreamsRequest listStreamsRequest = new ListStreamsRequest();
    listStreamsRequest.setLimit(10);
    ListStreamsResult listStreamsResult = kinesis.listStreams(listStreamsRequest);
    List<String> streamNames = listStreamsResult.getStreamNames();
    while (listStreamsResult.isHasMoreStreams()) {
        if (streamNames.size() > 0) {
            listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1));
        }

        listStreamsResult = kinesis.listStreams(listStreamsRequest);
        streamNames.addAll(listStreamsResult.getStreamNames());
    }
    // Print all of my streams.
    System.out.println("List of my streams: ");
    for (int i = 0; i < streamNames.size(); i++) {
        System.out.println("\t- " + streamNames.get(i));
    }

    System.out.printf("Putting records in stream : %s until this application is stopped...\n", myStreamName);
    System.out.println("Press CTRL-C to stop.");
    // Write records to the stream until this program is aborted.
    while (true) {
        long createTime = System.currentTimeMillis();
        PutRecordRequest putRecordRequest = new PutRecordRequest();
        putRecordRequest.setStreamName(myStreamName);
        putRecordRequest.setData(ByteBuffer.wrap(String.format("testData-%d", createTime).getBytes()));
        putRecordRequest.setPartitionKey(String.format("partitionKey-%d", createTime));
        PutRecordResult putRecordResult = kinesis.putRecord(putRecordRequest);
        System.out.printf("Successfully put record, partition key : %s, ShardID : %s, SequenceNumber : %s.\n",
                putRecordRequest.getPartitionKey(), putRecordResult.getShardId(),
                putRecordResult.getSequenceNumber());
    }
}

From source file:com.calamp.services.kinesis.events.writer.CalAmpEventWriter.java

License:Open Source License

/**
 * Uses the Kinesis client to send the event to the given stream.
 *
 * @param trade instance representing the stock trade
 * @param kinesisClient Amazon Kinesis client
 * @param streamName Name of stream /*from  ww  w.j  a  v a 2s  .co  m*/
 */
public static void sendEvent(CalAmpEvent event, AmazonKinesis kinesisClient, String streamName) {
    byte[] bytes = event.toJsonAsBytes();
    // The bytes could be null if there is an issue with the JSON serialization by the Jackson JSON library.
    if (bytes == null) {
        LOG.warn("Could not get JSON bytes for stock trade");
        return;
    }

    LOG.info("Putting trade: " + event.toString());
    PutRecordRequest putRecord = new PutRecordRequest();
    putRecord.setStreamName(CalAmpParameters.unorderdStreamName);
    putRecord.setPartitionKey(String.valueOf(event.getMachineId()));
    putRecord.setData(ByteBuffer.wrap(bytes));

    //This is needed to guaranteed FIFO ordering per partitionKey
    if (prevSeqNum != null) {
        putRecord.setSequenceNumberForOrdering(prevSeqNum);
    }
    try {
        PutRecordResult res = kinesisClient.putRecord(putRecord);
        prevSeqNum = res.getSequenceNumber();
        Utils.lazyLog(putRecord, CalAmpParameters.writeLogName);
    } catch (AmazonClientException ex) {
        LOG.warn("Error sending record to Amazon Kinesis.", ex);
    }
}

From source file:com.facebook.presto.kinesis.util.MockKinesisClient.java

License:Apache License

@Override
public PutRecordsResult putRecords(PutRecordsRequest putRecordsRequest)
        throws AmazonServiceException, AmazonClientException {
    // Setup method to add a batch of new records:
    InternalStream theStream = this.getStream(putRecordsRequest.getStreamName());
    if (theStream != null) {
        PutRecordsResult result = new PutRecordsResult();
        ArrayList<PutRecordsResultEntry> resultList = new ArrayList<PutRecordsResultEntry>();
        for (PutRecordsRequestEntry entry : putRecordsRequest.getRecords()) {
            PutRecordResult putResult = theStream.putRecord(entry.getData(), entry.getPartitionKey());
            resultList.add((new PutRecordsResultEntry()).withShardId(putResult.getShardId())
                    .withSequenceNumber(putResult.getSequenceNumber()));
        }//from w ww.  java  2 s. co  m

        result.setRecords(resultList);
        return result;
    } else {
        throw new AmazonClientException("This stream does not exist!");
    }
}

From source file:com.mh2c.LogGenerator.java

License:Apache License

/**
 * Generates log lines and sends them to Kinesis.
 *
 * @param streamName Kinesis stream name
 * @param recsPerSecond number of records to send each second
 * @param numRecords total number of records to send
 *//*ww w .  j  a  v  a  2s . c om*/
public void generate(String streamName, int recsPerSecond, int numRecords) throws InterruptedException {

    AmazonKinesisClient client = new AmazonKinesisClient();

    int numPasses = (numRecords + recsPerSecond - 1) / recsPerSecond;
    int recordsLeft = numRecords;
    for (int i = 0; i < numPasses; i++) {
        int numToGenerate = Math.min(recordsLeft, recsPerSecond);
        for (int j = 0; j < numToGenerate; j++) {
            String logLine = generateLogLine();

            PutRecordRequest request = new PutRecordRequest().withStreamName(streamName)
                    .withPartitionKey(PARTITION_KEY)
                    .withData(ByteBuffer.wrap(logLine.getBytes(StandardCharsets.UTF_8)));
            PutRecordResult result = client.putRecord(request);
            System.out.println(
                    String.format("Wrote to shard %s as %s", result.getShardId(), result.getSequenceNumber()));
        }

        recordsLeft -= numToGenerate;
        if (recordsLeft > 0) {
            Thread.sleep(1000L);
        }
    }
}

From source file:io.radiowitness.kinesis.producer.PutRecordTask.java

License:Open Source License

@Override
public void onSuccess(PutRecordRequest request, PutRecordResult result) {
    future.set(result.getSequenceNumber());
}

From source file:org.apache.streams.amazon.kinesis.KinesisPersistWriter.java

License:Apache License

@Override
public void write(StreamsDatum entry) {

    String document = (String) TypeConverterUtil.getInstance().convert(entry.getDocument(), String.class);

    PutRecordRequest putRecordRequest = new PutRecordRequest().withStreamName(config.getStream())
            .withPartitionKey(entry.getId()).withData(ByteBuffer.wrap(document.getBytes()));

    PutRecordResult putRecordResult = client.putRecord(putRecordRequest);

    entry.setSequenceid(new BigInteger(putRecordResult.getSequenceNumber()));

    LOGGER.debug("Wrote {}", entry);
}