

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Usar o JMS com o Amazon SQS
<a name="sqs-java-message-service-jms-client"></a>

A biblioteca de mensagens Java do Amazon SQS é uma interface Java Message Service (JMS) para o Amazon SQS que permite aproveitar o Amazon SQS em aplicações que já utilizam JMS. A interface permite que você use o Amazon SQS como o provedor de JMS com o mínimo de alterações no código. Junto com o AWS SDK para Java, a biblioteca de mensagens Java do Amazon SQS permite criar conexões e sessões JMS, bem como produtores e consumidores que enviam e recebem mensagens de e para filas do Amazon SQS.

A biblioteca oferece suporte ao envio e recebimento de mensagens para uma fila (o modelo ponto a ponto JMS) de acordo com a [especificação JMS 1.1](http://docs.oracle.com/javaee/6/api/javax/jms/package-summary.html). A biblioteca oferece suporte ao envio de mensagens de texto, de byte ou de objeto de forma síncrona para filas do Amazon SQS. A biblioteca também dá suporte ao recebimento de objetos de forma síncrona ou assíncrona.

Para mais informações sobre recursos da biblioteca de mensagens Java do Amazon SQS compatíveis com a especificação JMS 1.1, consulte [Implementações do Amazon SQS compatíveis com o JMS 1.1](supported-implementations.md) e as [Perguntas frequentes do Amazon SQS](https://aws.amazon.com/sqs/faqs/).

# Pré-requisitos para trabalhar com o JMS e o Amazon SQS
<a name="prerequisites"></a>

Antes de começar, você deve cumprir os seguintes pré-requisitos:
+ **SDK para Java**

  Há duas maneiras de incluir o SDK for Java no seu projeto:
  + Faça download e instale o SDK for Java.
  + Use o Maven para obter a biblioteca de mensagens Java do Amazon SQS.
**nota**  
O SDK for Java é incluído como uma dependência.  
O [SDK for Java](https://aws.amazon.com/sdkforjava/) e a biblioteca cliente Java estendida para o Amazon SQS exigem o J2SE Development Kit 8.0 ou posterior.

    Para obter mais informações sobre como fazer download do SDK for Java, consulte [SDK for Java](https://aws.amazon.com/sdkforjava/).
+ **Biblioteca de Mensagens Java do Amazon SQS** 

  Se você não usar o Maven, é necessário adicionar o pacote `amazon-sqs-java-messaging-lib.jar` ao caminho da classe Java. Para obter mais informações sobre como fazer download da biblioteca, consulte [Biblioteca de mensagens Java do Amazon SQS](https://github.com/awslabs/amazon-sqs-java-messaging-lib).
**nota**  
A biblioteca de mensagens Java do Amazon SQS inclui suporte para [Maven](http://maven.apache.org/) e [Spring Framework](http://projects.spring.io/spring-framework/).  
Para exemplos de código que usam Maven, Spring Framework e a biblioteca de mensagens Java do Amazon SQS, consulte [Exemplos de Java funcionais para usar o JMS com filas padrão do Amazon SQS](sqs-jms-code-examples.md).  

  ```
  <dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>amazon-sqs-java-messaging-lib</artifactId>
    <version>1.0.4</version>
    <type>jar</type>
  </dependency>
  ```
+ **Fila do Amazon SQS**

  Crie uma fila usando o Console de gerenciamento da AWS do Amazon SQS, a API `CreateQueue` ou o cliente encapsulado do Amazon SQS incluído na biblioteca de mensagens Java do Amazon SQS.
  + Para obter mais informações sobre como criar uma fila com o Amazon SQS usando o Console de gerenciamento da AWS ou a API `CreateQueue`, [consulte Criar uma fila](creating-sqs-standard-queues.md#step-create-standard-queue).
  + Para obter mais informações sobre o uso da biblioteca de mensagens Java do Amazon SQS, consulte [Usar a Biblioteca de Mensagens Java do Amazon SQS](getting-started.md).

# Usar a Biblioteca de Mensagens Java do Amazon SQS
<a name="getting-started"></a>

Para começar a usar o Serviço de Mensagens Java (JMS) com o Amazon SQS, use os exemplos de código nesta seção. As seções a seguir mostram como criar uma conexão e uma sessão do JMS, e como enviar e receber uma mensagem.

O objeto do cliente encapsulado do Amazon SQS incluído na biblioteca de mensagens Java do Amazon SQS verifica se uma fila do Amazon SQS existe. Se a fila não existir, o cliente a criará.

## Criação de uma conexão do JMS
<a name="creating-connection"></a>

Antes de começar, consulte os pré-requisitos em [Pré-requisitos para trabalhar com o JMS e o Amazon SQS](prerequisites.md).

1. Crie uma connection factory e chame o método `createConnection` contra a factory.

   ```
   // Create a new connection factory with all defaults (credentials and region) set automatically
   SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
           new ProviderConfiguration(),
           AmazonSQSClientBuilder.defaultClient()
           );
    
   // Create the connection.
   SQSConnection connection = connectionFactory.createConnection();
   ```

   A classe `SQSConnection` estende `javax.jms.Connection`. Com os métodos de conexão do JMS padrão, `SQSConnection` oferece métodos adicionais, como `getAmazonSQSClient` e `getWrappedAmazonSQSClient`. Os dois métodos permitem que você execute operações administrativas não incluídas na especificação JMS, como a criação de novas filas. Contudo, o método `getWrappedAmazonSQSClient` também fornece uma versão encapsulada do cliente do Amazon SQS usada pela conexão atual. O wrapper transforma cada exceção de um cliente em um `JMSException`, permitindo que ele seja mais facilmente usado pelo código existente que espera ocorrências de `JMSException`.

1. Você pode usar objetos de cliente retornados de `getAmazonSQSClient` e de `getWrappedAmazonSQSClient` para executar operações administrativas não incluídas na especificação do JMS (por exemplo, você pode criar uma fila do Amazon SQS).

    Se você tiver um código que espera exceções JMS, deve usar `getWrappedAmazonSQSClient`:
   + Se você usar `getWrappedAmazonSQSClient`, o objeto de cliente retornado transformará todas as exceções em exceções JMS.
   + Se você usar `getAmazonSQSClient`, todas as exceções serão exceções do Amazon SQS.

## Criar uma fila do Amazon SQS
<a name="creating-queue"></a>

O objeto de cliente encapsulado verifica se uma fila do Amazon SQS existe.

Se a fila não existir, o cliente a criará. Se a fila existir, a função não retornará nada. Para obter mais informações, consulte a seção "Criar uma fila, se necessário" no exemplo [TextMessageSender.java](sqs-jms-code-examples.md#example-sender).

### Como criar uma fila padrão
<a name="creating-queue-standard"></a>

```
// Get the wrapped client
AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient();
 
// Create an SQS queue named MyQueue, if it doesn't already exist
if (!client.queueExists("MyQueue")) {
    client.createQueue("MyQueue");
}
```

### Para criar uma fila FIFO
<a name="creating-queue-FIFO"></a>

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

// Create an Amazon SQS FIFO queue named MyQueue.fifo, if it doesn't already exist
if (!client.queueExists("MyQueue.fifo")) {
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("FifoQueue", "true");
    attributes.put("ContentBasedDeduplication", "true");
    client.createQueue(new CreateQueueRequest().withQueueName("MyQueue.fifo").withAttributes(attributes));
}
```

**nota**  
O nome de uma fila FIFO deve terminar com o sufixo `.fifo`.  
Para obter mais informações sobre o atributo `ContentBasedDeduplication`, consulte [Processamento exatamente uma vez no Amazon SQS](FIFO-queues-exactly-once-processing.md).

## Envio de mensagens de forma síncrona
<a name="send-messages-synchronously"></a>

1. Quando a conexão e a fila do Amazon SQS subjacente estiverem prontas, crie uma sessão JMS sem transação com o modo `AUTO_ACKNOWLEDGE`.

   ```
   // Create the nontransacted session with AUTO_ACKNOWLEDGE mode
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   ```

1. Para enviar uma mensagem de texto para a fila, crie uma identidade de fila JMS e um produtor de mensagem.

   ```
   // Create a queue identity and specify the queue name to the session
   Queue queue = session.createQueue("MyQueue");
    
   // Create a producer for the 'MyQueue'
   MessageProducer producer = session.createProducer(queue);
   ```

1. Crie uma mensagem de texto e envie-a para a fila.
   + Para enviar uma mensagem para uma fila padrão, você não precisa definir parâmetros adicionais.

     ```
     // Create the text message
     TextMessage message = session.createTextMessage("Hello World!");
      
     // Send the message
     producer.send(message);
     System.out.println("JMS Message " + message.getJMSMessageID());
     ```
   + Para enviar uma mensagem para uma fila FIFO, você deve definir o ID do grupo de mensagens. Você também pode definir um ID de eliminação de duplicação de mensagem. Para obter mais informações, consulte [Termos-chave de fila FIFO do Amazon SQS](FIFO-key-terms.md).

     ```
     // Create the text message
     TextMessage message = session.createTextMessage("Hello World!");
     
     // Set the message group ID
     message.setStringProperty("JMSXGroupID", "Default");
     
     // You can also set a custom message deduplication ID
     // message.setStringProperty("JMS_SQS_DeduplicationId", "hello");
     // Here, it's not needed because content-based deduplication is enabled for the queue
     
     // Send the message
     producer.send(message);
     System.out.println("JMS Message " + message.getJMSMessageID());
     System.out.println("JMS Message Sequence Number " + message.getStringProperty("JMS_SQS_SequenceNumber"));
     ```

## Recebimento de mensagens de forma síncrona
<a name="receive-messages-synchronously"></a>

1. Para receber mensagens, crie um consumidor para a mesma fila e invoque o método `start`.

   Você também pode chamar o método `start` na conexão a qualquer momento. No entanto, o consumidor não começa a receber mensagens até você chamá-lo.

   ```
   // Create a consumer for the 'MyQueue'
   MessageConsumer consumer = session.createConsumer(queue);
   // Start receiving incoming messages
   connection.start();
   ```

1. Chame o método `receive` no consumidor com um tempo limite definido como 1 segundo e imprima o conteúdo da mensagem recebida.
   + Após receber uma mensagem de uma fila padrão, você pode acessar o conteúdo da mensagem.

     ```
     // Receive a message from 'MyQueue' and wait up to 1 second
     Message receivedMessage = consumer.receive(1000);
      
     // Cast the received message as TextMessage and display the text
     if (receivedMessage != null) {
         System.out.println("Received: " + ((TextMessage) receivedMessage).getText());
     }
     ```
   + Após receber uma mensagem de uma fila FIFO, você pode acessar o conteúdo da mensagem e outros atributos de mensagem específicos à FIFO, como o ID do grupo de mensagens, o ID de eliminação de duplicação de mensagens e o número de sequência. Para obter mais informações, consulte [Termos-chave de fila FIFO do Amazon SQS](FIFO-key-terms.md).

     ```
     // Receive a message from 'MyQueue' and wait up to 1 second
     Message receivedMessage = consumer.receive(1000);
     
     // Cast the received message as TextMessage and display the text
     if (receivedMessage != null) {
         System.out.println("Received: " + ((TextMessage) receivedMessage).getText());
         System.out.println("Group id: " + receivedMessage.getStringProperty("JMSXGroupID"));
         System.out.println("Message deduplication id: " + receivedMessage.getStringProperty("JMS_SQS_DeduplicationId"));
         System.out.println("Message sequence number: " + receivedMessage.getStringProperty("JMS_SQS_SequenceNumber"));
     }
     ```

1. Feche a conexão e a sessão.

   ```
   // Close the connection (and the session).
   connection.close();
   ```

A saída será semelhante à seguinte:

```
JMS Message ID:8example-588b-44e5-bbcf-d816example2
Received: Hello World!
```

**nota**  
Você pode usar o Spring Framework para inicializar esses objetos.  
Para obter mais informações, consulte `SpringExampleConfiguration.xml`, `SpringExample.java` e as outras classes auxiliares em `ExampleConfiguration.java` e `ExampleCommon.java` na seção [Exemplos de Java funcionais para usar o JMS com filas padrão do Amazon SQS](sqs-jms-code-examples.md).

Para exemplos completos de envio e recebimento de objetos, consulte [TextMessageSender.java](sqs-jms-code-examples.md#example-sender) e [SyncMessageReceiver.java](sqs-jms-code-examples.md#example-synchronous-message-receiver).

## Recebimento de mensagens de forma assíncrona
<a name="receive-messages-asynchronously"></a>

No exemplo em [Usar a Biblioteca de Mensagens Java do Amazon SQS](#getting-started), uma mensagem é enviada para `MyQueue` e recebida de forma síncrona.

O exemplo a seguir mostra como receber as mensagens de forma assíncrona por meio de um listener.

1. Implemente a interface `MessageListener`.

   ```
   class MyListener implements MessageListener {
    
       @Override
       public void onMessage(Message message) {
           try {
               // Cast the received message as TextMessage and print the text to screen.
               System.out.println("Received: " + ((TextMessage) message).getText());
           } catch (JMSException e) {
               e.printStackTrace();
           }
       }
   }
   ```

   O método `onMessage` da interface `MessageListener` é chamado quando você recebe uma mensagem. Nesta implementação de listener, o texto armazenado na mensagem é impresso.

1. Em vez de explicitamente chamar o método `receive` no consumidor, defina o listener da mensagem do consumidor como uma instância da implementação `MyListener`. O thread principal aguarda um segundo.

   ```
   // Create a consumer for the 'MyQueue'.
   MessageConsumer consumer = session.createConsumer(queue);
    
   // Instantiate and set the message listener for the consumer.
   consumer.setMessageListener(new MyListener());
    
   // Start receiving incoming messages.
   connection.start();
    
   // Wait for 1 second. The listener onMessage() method is invoked when a message is received.
   Thread.sleep(1000);
   ```

As demais etapas são idênticas às do exemplo [Usar a Biblioteca de Mensagens Java do Amazon SQS](#getting-started). Para um exemplo completo de um consumidor assíncrono, consulte `AsyncMessageReceiver.java` em [Exemplos de Java funcionais para usar o JMS com filas padrão do Amazon SQS](sqs-jms-code-examples.md).

A saída deste exemplo é similar ao seguinte:

```
JMS Message ID:8example-588b-44e5-bbcf-d816example2
Received: Hello World!
```

## Uso do modo de reconhecimento do cliente
<a name="using-client-acknowledge-mode"></a>

O exemplo em [Usar a Biblioteca de Mensagens Java do Amazon SQS](#getting-started) usa o modo `AUTO_ACKNOWLEDGE` em que cada mensagem recebida é confirmada automaticamente (e, portanto, excluída da fila do Amazon SQS subjacente).

1. Para explicitamente reconhecer as mensagens depois de processadas, você deve criar a sessão com o modo `CLIENT_ACKNOWLEDGE`.

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

1. Quando a mensagem é recebida, exiba-a e confirme-a explicitamente.

   ```
   // Cast the received message as TextMessage and print the text to screen. Also acknowledge the message.
   if (receivedMessage != null) {
       System.out.println("Received: " + ((TextMessage) receivedMessage).getText());
       receivedMessage.acknowledge();
       System.out.println("Acknowledged: " + message.getJMSMessageID());
   }
   ```
**nota**  
Nesse modo, quando uma mensagem é confirmada, todas as mensagens recebidas antes desta mensagem são implicitamente confirmadas. Por exemplo, se 10 mensagens são recebidas e apenas a 10ª mensagem é reconhecida (na ordem em que as mensagens são recebidas), todas as nove mensagens anteriores também são reconhecidas.

As demais etapas são idênticas às do exemplo [Usar a Biblioteca de Mensagens Java do Amazon SQS](#getting-started). Para um exemplo completo de um consumidor síncrono com modo de reconhecimento do cliente, consulte `SyncMessageReceiverClientAcknowledge.java` em [Exemplos de Java funcionais para usar o JMS com filas padrão do Amazon SQS](sqs-jms-code-examples.md).

A saída deste exemplo é similar ao seguinte:

```
JMS Message ID:4example-aa0e-403f-b6df-5e02example5
Received: Hello World!
Acknowledged: ID:4example-aa0e-403f-b6df-5e02example5
```

## Uso do modo de reconhecimento não ordenado
<a name="using-unordered-acknowledge-mode"></a>

Ao usar o modo `CLIENT_ACKNOWLEDGE`, todas as mensagens recebidas antes de uma mensagem explicitamente reconhecida são automaticamente reconhecidas. Para obter mais informações, consulte [Uso do modo de reconhecimento do cliente](#using-client-acknowledge-mode).

A biblioteca de mensagens Java do Amazon SQS fornece outro modo de confirmação. Ao usar o modo `UNORDERED_ACKNOWLEDGE`, todas as mensagens recebidas devem ser individual e explicitamente reconhecidas pelo cliente, independentemente de sua ordem de recebimento. Para fazer isso, cria uma sessão com o modo `UNORDERED_ACKNOWLEDGE`.

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

As etapas restantes são idênticas às do exemplo [Uso do modo de reconhecimento do cliente](#using-client-acknowledge-mode). Para um exemplo completo de um consumidor síncrono com o modo `UNORDERED_ACKNOWLEDGE`, consulte `SyncMessageReceiverUnorderedAcknowledge.java`.

Neste exemplo, a saída é similar ao seguinte:

```
JMS Message ID:dexample-73ad-4adb-bc6c-4357example7
Received: Hello World!
Acknowledged: ID:dexample-73ad-4adb-bc6c-4357example7
```

# Usar o Serviço de Mensagens Java com outros clientes do Amazon SQS
<a name="sqs-jms-client-with-sqs-clients"></a>

O uso do cliente Amazon SQS Java Message Service (JMS) com o AWS SDK limita o tamanho da mensagem do Amazon SQS a 256 KB. No entanto, você pode criar um provedor JMS usando qualquer cliente do Amazon SQS. Por exemplo, você pode usar o cliente JMS com a biblioteca cliente Java estendida para o Amazon SQS para enviar uma mensagem do Amazon SQS que contenha uma referência à carga útil da mensagem (até 2 GB) no Amazon S3. Para obter mais informações, consulte [Gerenciar mensagens grandes do Amazon SQS usando Java e Amazon S3](sqs-s3-messages.md).

O exemplo de código Java a seguir cria o provedor do JMS para a biblioteca do cliente em versão ampliada.

Veja os pré-requisitos em [Pré-requisitos para trabalhar com o JMS e o Amazon SQS](prerequisites.md) antes de testar este exemplo.

```
AmazonS3 s3 = new AmazonS3Client(credentials);
Region s3Region = Region.getRegion(Regions.US_WEST_2);
s3.setRegion(s3Region);
 
// Set the Amazon S3 bucket name, and set a lifecycle rule on the bucket to
// permanently delete objects a certain number of days after each object's creation date.
// Next, create the bucket, and enable message objects to be stored in the bucket.
BucketLifecycleConfiguration.Rule expirationRule = new BucketLifecycleConfiguration.Rule();
expirationRule.withExpirationInDays(14).withStatus("Enabled");
BucketLifecycleConfiguration lifecycleConfig = new BucketLifecycleConfiguration().withRules(expirationRule);
 
s3.createBucket(s3BucketName);
s3.setBucketLifecycleConfiguration(s3BucketName, lifecycleConfig);
System.out.println("Bucket created and configured.");

// Set the SQS extended client configuration with large payload support enabled.
ExtendedClientConfiguration extendedClientConfig = new ExtendedClientConfiguration()
    .withLargePayloadSupportEnabled(s3, s3BucketName);
 
AmazonSQS sqsExtended = new AmazonSQSExtendedClient(new AmazonSQSClient(credentials), extendedClientConfig);
Region sqsRegion = Region.getRegion(Regions.US_WEST_2);
sqsExtended.setRegion(sqsRegion);
```

O exemplo de código Java a seguir cria a connection factory:

```
// Create the connection factory using the environment variable credential provider.
// Pass the configured Amazon SQS Extended Client to the JMS connection factory.
SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
        new ProviderConfiguration(),
        sqsExtended
        );
 
// Create the connection.
SQSConnection connection = connectionFactory.createConnection();
```

# Exemplos de Java funcionais para usar o JMS com filas padrão do Amazon SQS
<a name="sqs-jms-code-examples"></a>

Veja a seguir exemplos de código que mostram como usar o JMS (Java Message Service) com filas padrão do Amazon SQS. Para obter mais informações sobre como trabalhar com filas FIFO, consulte [Para criar uma fila FIFO](getting-started.md#creating-queue-FIFO), [Envio de mensagens de forma síncrona](getting-started.md#send-messages-synchronously) e [Recebimento de mensagens de forma síncrona](getting-started.md#receive-messages-synchronously). (O recebimento de mensagens de forma síncrona é igual para filas padrão e FIFO. No entanto, as mensagens em filas FIFO contêm mais atributos).

Veja os pré-requisitos em [Pré-requisitos para trabalhar com o JMS e o Amazon SQS](prerequisites.md) antes de testar os exemplos a seguir.

## ExampleConfiguration.java
<a name="example-configuration"></a>

O exemplo a seguir de código Java do SDK v 1.x define o nome de fila padrão, a região e as credenciais a serem usadas com outros exemplos de Java.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

public class ExampleConfiguration {
    public static final String DEFAULT_QUEUE_NAME = "SQSJMSClientExampleQueue";
    
    public static final Region DEFAULT_REGION = Region.getRegion(Regions.US_EAST_2);
    
    private static String getParameter( String args[], int i ) {
        if( i + 1 >= args.length ) {
            throw new IllegalArgumentException( "Missing parameter for " + args[i] );
        }
        return args[i+1];
    }
    
    /**
     * Parse the command line and return the resulting config. If the config parsing fails
     * print the error and the usage message and then call System.exit
     * 
     * @param app the app to use when printing the usage string
     * @param args the command line arguments
     * @return the parsed config
     */
    public static ExampleConfiguration parseConfig(String app, String args[]) {
        try {
            return new ExampleConfiguration(args);
        } catch (IllegalArgumentException e) {
            System.err.println( "ERROR: " + e.getMessage() );
            System.err.println();
            System.err.println( "Usage: " + app + " [--queue <queue>] [--region <region>] [--credentials <credentials>] ");
            System.err.println( "  or" );
            System.err.println( "       " + app + " <spring.xml>" );
            System.exit(-1);
            return null;
        }
    }
    
    private ExampleConfiguration(String args[]) {
        for( int i = 0; i < args.length; ++i ) {
            String arg = args[i];
            if( arg.equals( "--queue" ) ) {
                setQueueName(getParameter(args, i));
                i++;
            } else if( arg.equals( "--region" ) ) {
                String regionName = getParameter(args, i);
                try {
                    setRegion(Region.getRegion(Regions.fromName(regionName)));
                } catch( IllegalArgumentException e ) {
                    throw new IllegalArgumentException( "Unrecognized region " + regionName );  
                }
                i++;
            } else if( arg.equals( "--credentials" ) ) {
                String credsFile = getParameter(args, i);
                try {
                    setCredentialsProvider( new PropertiesFileCredentialsProvider(credsFile) );
                } catch (AmazonClientException e) {
                    throw new IllegalArgumentException("Error reading credentials from " + credsFile, e );
                }
                i++;
            } else {
                throw new IllegalArgumentException("Unrecognized option " + arg);
            }
        }
    }
    
    private String queueName = DEFAULT_QUEUE_NAME;
    private Region region = DEFAULT_REGION;
    private AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
    
    public String getQueueName() {
        return queueName;
    }
    
    public void setQueueName(String queueName) {
        this.queueName = queueName;
    }
    
    public Region getRegion() {
        return region;
    }
    
    public void setRegion(Region region) {
        this.region = region;
    }
 
    public AWSCredentialsProvider getCredentialsProvider() {
        return credentialsProvider;
    }
    
    public void setCredentialsProvider(AWSCredentialsProvider credentialsProvider) {
        // Make sure they're usable first
        credentialsProvider.getCredentials();
        this.credentialsProvider = credentialsProvider;
    }
}
```

## TextMessageSender.java
<a name="example-sender"></a>

O seguinte exemplo de código Java cria um produtor de mensagem de texto.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

public class TextMessageSender {
    public static void main(String args[]) throws JMSException {
        ExampleConfiguration config = ExampleConfiguration.parseConfig("TextMessageSender", args);
        
        ExampleCommon.setupLogging();
        
        // Create the connection factory based on the config       
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                AmazonSQSClientBuilder.standard()
                        .withRegion(config.getRegion().getName())
                        .withCredentials(config.getCredentialsProvider())
                );
        
        // Create the connection
        SQSConnection connection = connectionFactory.createConnection();
        
        // Create the queue if needed
        ExampleCommon.ensureQueueExists(connection, config.getQueueName());
            
        // Create the session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer( session.createQueue( config.getQueueName() ) );
        
        sendMessages(session, producer);
 
        // Close the connection. This closes the session automatically
        connection.close();
        System.out.println( "Connection closed" );
    }
 
    private static void sendMessages( Session session, MessageProducer producer ) {
        BufferedReader inputReader = new BufferedReader(
            new InputStreamReader( System.in, Charset.defaultCharset() ) );
        
        try {
            String input;
            while( true ) { 
                System.out.print( "Enter message to send (leave empty to exit): " );
                input = inputReader.readLine();
                if( input == null || input.equals("" ) ) break;
                
                TextMessage message = session.createTextMessage(input);
                producer.send(message);
                System.out.println( "Send message " + message.getJMSMessageID() );
            }
        } catch (EOFException e) {
            // Just return on EOF
        } catch (IOException e) {
            System.err.println( "Failed reading input: " + e.getMessage() );
        } catch (JMSException e) {
            System.err.println( "Failed sending message: " + e.getMessage() );
            e.printStackTrace();
        }
    }
}
```

## SyncMessageReceiver.java
<a name="example-synchronous-message-receiver"></a>

O seguinte exemplo de código Java cria um consumidor de mensagem síncrona.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

public class SyncMessageReceiver {
public static void main(String args[]) throws JMSException {
    ExampleConfiguration config = ExampleConfiguration.parseConfig("SyncMessageReceiver", args);
    
    ExampleCommon.setupLogging();
    
    // Create the connection factory based on the config
    SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
            new ProviderConfiguration(),
            AmazonSQSClientBuilder.standard()
                    .withRegion(config.getRegion().getName())
                    .withCredentials(config.getCredentialsProvider())
            );
    
    // Create the connection
    SQSConnection connection = connectionFactory.createConnection();
    
    // Create the queue if needed
    ExampleCommon.ensureQueueExists(connection, config.getQueueName());
        
    // Create the session
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer( session.createQueue( config.getQueueName() ) );

    connection.start();
    
    receiveMessages(session, consumer);

    // Close the connection. This closes the session automatically
    connection.close();
    System.out.println( "Connection closed" );
}

private static void receiveMessages( Session session, MessageConsumer consumer ) {
    try {
        while( true ) {
            System.out.println( "Waiting for messages");
            // Wait 1 minute for a message
            Message message = consumer.receive(TimeUnit.MINUTES.toMillis(1));
            if( message == null ) {
                System.out.println( "Shutting down after 1 minute of silence" );
                break;
            }
            ExampleCommon.handleMessage(message);
            message.acknowledge();
            System.out.println( "Acknowledged message " + message.getJMSMessageID() );
        }
    } catch (JMSException e) {
        System.err.println( "Error receiving from SQS: " + e.getMessage() );
        e.printStackTrace();
    }
}
}
```

## AsyncMessageReceiver.java
<a name="example-asynchronous-message-receiver"></a>

O seguinte exemplo de código Java cria um consumidor de mensagem assíncrona.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

public class AsyncMessageReceiver {
    public static void main(String args[]) throws JMSException, InterruptedException {
        ExampleConfiguration config = ExampleConfiguration.parseConfig("AsyncMessageReceiver", args);
         
        ExampleCommon.setupLogging();          
         
        // Create the connection factory based on the config
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                AmazonSQSClientBuilder.standard()
                        .withRegion(config.getRegion().getName())
                        .withCredentials(config.getCredentialsProvider())
                );
         
        // Create the connection
        SQSConnection connection = connectionFactory.createConnection();
         
        // Create the queue if needed
        ExampleCommon.ensureQueueExists(connection, config.getQueueName());
             
        // Create the session
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer( session.createQueue( config.getQueueName() ) );
         
        // No messages are processed until this is called
        connection.start();

        ReceiverCallback callback = new ReceiverCallback();
        consumer.setMessageListener( callback );
         
        callback.waitForOneMinuteOfSilence();
        System.out.println( "Returning after one minute of silence" );

        // Close the connection. This closes the session automatically
        connection.close();
        System.out.println( "Connection closed" );
    }
    
    
    private static class ReceiverCallback implements MessageListener {
        // Used to listen for message silence
        private volatile long timeOfLastMessage = System.nanoTime();
         
        public void waitForOneMinuteOfSilence() throws InterruptedException {
            for(;;) {
                long timeSinceLastMessage = System.nanoTime() - timeOfLastMessage;
                long remainingTillOneMinuteOfSilence = 
                    TimeUnit.MINUTES.toNanos(1) - timeSinceLastMessage;
                if( remainingTillOneMinuteOfSilence < 0 ) {
                    break;
                }
                TimeUnit.NANOSECONDS.sleep(remainingTillOneMinuteOfSilence);
            }
        }
         

        @Override
        public void onMessage(Message message) {
            try {
                ExampleCommon.handleMessage(message);
                message.acknowledge();
                System.out.println( "Acknowledged message " + message.getJMSMessageID() );
                timeOfLastMessage = System.nanoTime();
            } catch (JMSException e) {
                System.err.println( "Error processing message: " + e.getMessage() );
                e.printStackTrace();
            }
        }
    }
}
```

## SyncMessageReceiverClientAcknowledge.java
<a name="example-synchronous-receiver-client-acknowledge-mode"></a>

O seguinte exemplo de código Java cria um consumidor síncrono com modo de reconhecimento do cliente.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

/**
 * An example class to demonstrate the behavior of CLIENT_ACKNOWLEDGE mode for received messages. This example
 * complements the example given in {@link SyncMessageReceiverUnorderedAcknowledge} for UNORDERED_ACKNOWLEDGE mode.
 *
 * First, a session, a message producer, and a message consumer are created. Then, two messages are sent. Next, two messages
 * are received but only the second one is acknowledged. After waiting for the visibility time out period, an attempt to
 * receive another message is made. It's shown that no message is returned for this attempt since in CLIENT_ACKNOWLEDGE mode,
 * as expected, all the messages prior to the acknowledged messages are also acknowledged.
 *
 * This ISN'T the behavior for UNORDERED_ACKNOWLEDGE mode. Please see {@link SyncMessageReceiverUnorderedAcknowledge}
 * for an example.
 */
public class SyncMessageReceiverClientAcknowledge {
 
    // Visibility time-out for the queue. It must match to the one set for the queue for this example to work.
    private static final long TIME_OUT_SECONDS = 1;
 
    public static void main(String args[]) throws JMSException, InterruptedException {
        // Create the configuration for the example
        ExampleConfiguration config = ExampleConfiguration.parseConfig("SyncMessageReceiverClientAcknowledge", args);
 
        // Setup logging for the example
        ExampleCommon.setupLogging();
 
        // Create the connection factory based on the config
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                AmazonSQSClientBuilder.standard()
                        .withRegion(config.getRegion().getName())
                        .withCredentials(config.getCredentialsProvider())
                );
 
        // Create the connection
        SQSConnection connection = connectionFactory.createConnection();
 
        // Create the queue if needed
        ExampleCommon.ensureQueueExists(connection, config.getQueueName());
 
        // Create the session  with client acknowledge mode
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
 
        // Create the producer and consume
        MessageProducer producer = session.createProducer(session.createQueue(config.getQueueName()));
        MessageConsumer consumer = session.createConsumer(session.createQueue(config.getQueueName()));
 
        // Open the connection
        connection.start();
 
        // Send two text messages
        sendMessage(producer, session, "Message 1");
        sendMessage(producer, session, "Message 2");
 
        // Receive a message and don't acknowledge it
        receiveMessage(consumer, false);
 
        // Receive another message and acknowledge it
        receiveMessage(consumer, true);
 
        // Wait for the visibility time out, so that unacknowledged messages reappear in the queue
        System.out.println("Waiting for visibility timeout...");
        Thread.sleep(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS));
 
        // Attempt to receive another message and acknowledge it. This results in receiving no messages since
        // we have acknowledged the second message. Although we didn't explicitly acknowledge the first message,
        // in the CLIENT_ACKNOWLEDGE mode, all the messages received prior to the explicitly acknowledged message
        // are also acknowledged. Therefore, we have implicitly acknowledged the first message.
        receiveMessage(consumer, true);
 
        // Close the connection. This closes the session automatically
        connection.close();
        System.out.println("Connection closed.");
    }
 
    /**
     * Sends a message through the producer.
     *
     * @param producer Message producer
     * @param session Session
     * @param messageText Text for the message to be sent
     * @throws JMSException
     */
    private static void sendMessage(MessageProducer producer, Session session, String messageText) throws JMSException {
        // Create a text message and send it
        producer.send(session.createTextMessage(messageText));
    }
 
    /**
     * Receives a message through the consumer synchronously with the default timeout (TIME_OUT_SECONDS).
     * If a message is received, the message is printed. If no message is received, "Queue is empty!" is
     * printed.
     *
     * @param consumer Message consumer
     * @param acknowledge If true and a message is received, the received message is acknowledged.
     * @throws JMSException
     */
    private static void receiveMessage(MessageConsumer consumer, boolean acknowledge) throws JMSException {
        // Receive a message
        Message message = consumer.receive(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS));
 
        if (message == null) {
            System.out.println("Queue is empty!");
        } else {
            // Since this queue has only text messages, cast the message object and print the text
            System.out.println("Received: " + ((TextMessage) message).getText());
 
            // Acknowledge the message if asked
            if (acknowledge) message.acknowledge();
        }
    }
}
```

## SyncMessageReceiverUnorderedAcknowledge.java
<a name="example-synchronous-receiver-unordered-acknowledge-mode"></a>

O seguinte exemplo de código Java cria um consumidor síncrono com modo de reconhecimento não ordenado.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

/**
 * An example class to demonstrate the behavior of UNORDERED_ACKNOWLEDGE mode for received messages. This example
 * complements the example given in {@link SyncMessageReceiverClientAcknowledge} for CLIENT_ACKNOWLEDGE mode.
 *
 * First, a session, a message producer, and a message consumer are created. Then, two messages are sent. Next, two messages
 * are received but only the second one is acknowledged. After waiting for the visibility time out period, an attempt to
 * receive another message is made. It's shown that the first message received in the prior attempt is returned again
 * for the second attempt. In UNORDERED_ACKNOWLEDGE mode, all the messages must be explicitly acknowledged no matter what
 * the order they're received.
 *
 * This ISN'T the behavior for CLIENT_ACKNOWLEDGE mode. Please see {@link SyncMessageReceiverClientAcknowledge}
 * for an example.
 */
public class SyncMessageReceiverUnorderedAcknowledge {
 
    // Visibility time-out for the queue. It must match to the one set for the queue for this example to work.
    private static final long TIME_OUT_SECONDS = 1;
 
    public static void main(String args[]) throws JMSException, InterruptedException {
        // Create the configuration for the example
        ExampleConfiguration config = ExampleConfiguration.parseConfig("SyncMessageReceiverUnorderedAcknowledge", args);
 
        // Setup logging for the example
        ExampleCommon.setupLogging();
 
        // Create the connection factory based on the config
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                AmazonSQSClientBuilder.standard()
                        .withRegion(config.getRegion().getName())
                        .withCredentials(config.getCredentialsProvider())
                );
 
        // Create the connection
        SQSConnection connection = connectionFactory.createConnection();
 
        // Create the queue if needed
        ExampleCommon.ensureQueueExists(connection, config.getQueueName());
 
        // Create the session  with unordered acknowledge mode
        Session session = connection.createSession(false, SQSSession.UNORDERED_ACKNOWLEDGE);
 
        // Create the producer and consume
        MessageProducer producer = session.createProducer(session.createQueue(config.getQueueName()));
        MessageConsumer consumer = session.createConsumer(session.createQueue(config.getQueueName()));
 
        // Open the connection
        connection.start();
 
        // Send two text messages
        sendMessage(producer, session, "Message 1");
        sendMessage(producer, session, "Message 2");
 
        // Receive a message and don't acknowledge it
        receiveMessage(consumer, false);
 
        // Receive another message and acknowledge it
        receiveMessage(consumer, true);
 
        // Wait for the visibility time out, so that unacknowledged messages reappear in the queue
        System.out.println("Waiting for visibility timeout...");
        Thread.sleep(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS));
 
        // Attempt to receive another message and acknowledge it. This results in receiving the first message since
        // we have acknowledged only the second message. In the UNORDERED_ACKNOWLEDGE mode, all the messages must
        // be explicitly acknowledged.
        receiveMessage(consumer, true);
 
        // Close the connection. This closes the session automatically
        connection.close();
        System.out.println("Connection closed.");
    }
 
    /**
     * Sends a message through the producer.
     *
     * @param producer Message producer
     * @param session Session
     * @param messageText Text for the message to be sent
     * @throws JMSException
     */
    private static void sendMessage(MessageProducer producer, Session session, String messageText) throws JMSException {
        // Create a text message and send it
        producer.send(session.createTextMessage(messageText));
    }
 
    /**
     * Receives a message through the consumer synchronously with the default timeout (TIME_OUT_SECONDS).
     * If a message is received, the message is printed. If no message is received, "Queue is empty!" is
     * printed.
     *
     * @param consumer Message consumer
     * @param acknowledge If true and a message is received, the received message is acknowledged.
     * @throws JMSException
     */
    private static void receiveMessage(MessageConsumer consumer, boolean acknowledge) throws JMSException {
        // Receive a message
        Message message = consumer.receive(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS));
 
        if (message == null) {
            System.out.println("Queue is empty!");
        } else {
            // Since this queue has only text messages, cast the message object and print the text
            System.out.println("Received: " + ((TextMessage) message).getText());
 
            // Acknowledge the message if asked
            if (acknowledge) message.acknowledge();
        }
    }
}
```

## SpringExampleConfiguration.xml
<a name="example-spring-configuration"></a>

O seguinte exemplo de código XML é um arquivo de configuração bean para [SpringExample.java](#example-spring).

```
<!--
    Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.

    Licensed under the Apache License, Version 2.0 (the "License").
    You may not use this file except in compliance with the License.
    A copy of the License is located at

    https://aws.amazon.com/apache2.0

    or in the "license" file accompanying this file. This file is distributed
    on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
    express or implied. See the License for the specific language governing
    permissions and limitations under the License.
-->

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
    ">
    
    <bean id="CredentialsProviderBean" class="com.amazonaws.auth.DefaultAWSCredentialsProviderChain"/>
    
    <bean id="ClientBuilder" class="com.amazonaws.services.sqs.AmazonSQSClientBuilder" factory-method="standard">
        <property name="region" value="us-east-2"/>
        <property name="credentials" ref="CredentialsProviderBean"/>               
    </bean>
    
    <bean id="ProviderConfiguration" class="com.amazon.sqs.javamessaging.ProviderConfiguration">
        <property name="numberOfMessagesToPrefetch" value="5"/>
    </bean>
    
    <bean id="ConnectionFactory" class="com.amazon.sqs.javamessaging.SQSConnectionFactory">
        <constructor-arg ref="ProviderConfiguration" />
        <constructor-arg ref="ClientBuilder" />
    </bean>
    
    <bean id="Connection" class="javax.jms.Connection"
        factory-bean="ConnectionFactory"
        factory-method="createConnection"
        init-method="start"
        destroy-method="close" />
    
    <bean id="QueueName" class="java.lang.String">
        <constructor-arg value="SQSJMSClientExampleQueue"/>
    </bean>
</beans>
```

## SpringExample.java
<a name="example-spring"></a>

O seguinte exemplo de código Java usa o arquivo de configuração bean para inicializar seus objetos.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */
                
public class SpringExample {
    public static void main(String args[]) throws JMSException {
        if( args.length != 1 || !args[0].endsWith(".xml")) {
            System.err.println( "Usage: " + SpringExample.class.getName() + " <spring config.xml>" );
            System.exit(1);
        }
        
        File springFile = new File( args[0] );
        if( !springFile.exists() || !springFile.canRead() ) {
            System.err.println( "File " + args[0] + " doesn't exist or isn't readable.");
            System.exit(2);
        }
        
        ExampleCommon.setupLogging();
        
        FileSystemXmlApplicationContext context = 
            new FileSystemXmlApplicationContext( "file://" + springFile.getAbsolutePath() );
        
        Connection connection;
        try {
            connection = context.getBean(Connection.class);
        } catch( NoSuchBeanDefinitionException e ) {
            System.err.println( "Can't find the JMS connection to use: " + e.getMessage() );
            System.exit(3);
            return;
        }
        
        String queueName;
        try {
            queueName = context.getBean("QueueName", String.class);
        } catch( NoSuchBeanDefinitionException e ) {
            System.err.println( "Can't find the name of the queue to use: " + e.getMessage() );
            System.exit(3);
            return;
        }
        
        if( connection instanceof SQSConnection ) {
            ExampleCommon.ensureQueueExists( (SQSConnection) connection, queueName );
        }
        
        // Create the session
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer( session.createQueue( queueName) );
        
        receiveMessages(session, consumer);
 
        // The context can be setup to close the connection for us
        context.close();
        System.out.println( "Context closed" );
    }
 
    private static void receiveMessages( Session session, MessageConsumer consumer ) {
        try {
            while( true ) {
                System.out.println( "Waiting for messages");
                // Wait 1 minute for a message
                Message message = consumer.receive(TimeUnit.MINUTES.toMillis(1));
                if( message == null ) {
                    System.out.println( "Shutting down after 1 minute of silence" );
                    break;
                }
                ExampleCommon.handleMessage(message);
                message.acknowledge();
                System.out.println( "Acknowledged message" );
            }
        } catch (JMSException e) {
            System.err.println( "Error receiving from SQS: " + e.getMessage() );
            e.printStackTrace();
        }
    }
}
```

## ExampleCommon.java
<a name="example-common"></a>

O código de exemplo Java a seguir verifica se existe uma fila do Amazon SQS e, se não existir, cria uma. Ele também inclui código de registro de exemplo.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

public class ExampleCommon {
    /**
     * A utility function to check the queue exists and create it if needed. For most  
     * use cases this is usually done by an administrator before the application is run. 
     */
    public static void ensureQueueExists(SQSConnection connection, String queueName) throws JMSException {
        AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient();
        
        /**
         * In most cases, you can do this with just a createQueue call, but GetQueueUrl 
         * (called by queueExists) is a faster operation for the common case where the queue 
         * already exists. Also many users and roles have permission to call GetQueueUrl
         * but don't have permission to call CreateQueue.
         */
        if( !client.queueExists(queueName) ) {
            client.createQueue( queueName );
        }
    }
 
    public static void setupLogging() {
        // Setup logging
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.WARN);
    }
 
    public static void handleMessage(Message message) throws JMSException {
        System.out.println( "Got message " + message.getJMSMessageID() );
        System.out.println( "Content: ");
        if( message instanceof TextMessage ) {
            TextMessage txtMessage = ( TextMessage ) message;
            System.out.println( "\t" + txtMessage.getText() );
        } else if( message instanceof BytesMessage ){
            BytesMessage byteMessage = ( BytesMessage ) message;
            // Assume the length fits in an int - SQS only supports sizes up to 256k so that
            // should be true
            byte[] bytes = new byte[(int)byteMessage.getBodyLength()];
            byteMessage.readBytes(bytes);
            System.out.println( "\t" +  Base64.encodeAsString( bytes ) );
        } else if( message instanceof ObjectMessage ) {
            ObjectMessage objMessage = (ObjectMessage) message;
            System.out.println( "\t" + objMessage.getObject() );
        }
    }
}
```

# Implementações do Amazon SQS compatíveis com o JMS 1.1
<a name="supported-implementations"></a>

A biblioteca de mensagens Java do Amazon SQS oferece suporte às seguintes [implantações do JMS 1.1](http://docs.oracle.com/javaee/6/api/javax/jms/package-summary.html). Para mais informações sobre os recursos compatíveis e capacidade da biblioteca de mensagens Java do Amazon SQS, consulte as [Perguntas frequentes do Amazon SQS](https://aws.amazon.com/sqs/faqs/).

## Interfaces comuns com suporte
<a name="supported-common-interfaces"></a>
+ `Connection`
+ `ConnectionFactory`
+ `Destination`
+ `Session`
+ `MessageConsumer`
+ `MessageProducer`

## Tipos de mensagens com suporte
<a name="supported-message-types"></a>
+ `ByteMessage`
+ `ObjectMessage`
+ `TextMessage`

## Modos de reconhecimento de mensagens com suporte
<a name="supported-message-acknowledgement-modes"></a>
+ `AUTO_ACKNOWLEDGE`
+ `CLIENT_ACKNOWLEDGE`
+ `DUPS_OK_ACKNOWLEDGE`
+ `UNORDERED_ACKNOWLEDGE`

**nota**  
O modo `UNORDERED_ACKNOWLEDGE` não faz parte da especificação JMS 1.1. Esse modo ajuda o Amazon SQS a permitir que um cliente JMS reconheça explicitamente uma mensagem.

## Cabeçalhos definidos pelo JMS e propriedades reservadas
<a name="jms-defined-headers-reserved-properties"></a>

### Para enviar mensagens
<a name="for-sending-messages"></a>

Ao enviar mensagens, você pode definir os seguintes cabeçalhos e propriedades para cada mensagem:
+ `JMSXGroupID` (obrigatório para filas FIFO, não permitido para filas padrão)
+ `JMS_SQS_DeduplicationId` (opcional para filas FIFO, não permitido para filas padrão)

Quando você envia mensagens, o Amazon SQS define os seguintes cabeçalhos e propriedades para cada uma:
+ `JMSMessageID`
+ `JMS_SQS_SequenceNumber` (somente para filas FIFO)

### Para receber mensagens
<a name="for-receiving-messages"></a>

Quando você recebe mensagens, o Amazon SQS define os seguintes cabeçalhos e propriedades para cada uma:
+ `JMSDestination`
+ `JMSMessageID`
+ `JMSRedelivered`
+ `JMSXDeliveryCount`
+ `JMSXGroupID` (somente para filas FIFO)
+ `JMS_SQS_DeduplicationId` (somente para filas FIFO)
+ `JMS_SQS_SequenceNumber` (somente para filas FIFO)