

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

# Uso de JMS con Amazon SQS
<a name="sqs-java-message-service-jms-client"></a>

La Biblioteca de mensajes Java de Amazon SQS es una interfaz de Servicio de mensajes de Java (JMS) para Amazon SQS que le permite aprovechar las ventajas de Amazon SQS en aplicaciones que ya utilizan JMS. La interfaz le permite utilizar Amazon SQS como proveedor JMS sin tener que realizar apenas cambios en el código. Junto con AWS SDK para Java, la Biblioteca de mensajes Java de Amazon SQS le permite crear conexiones y sesiones de JMS, así como productores y consumidores que envían y reciben mensajes hacia colas de Amazon SQS y desde ellas.

La biblioteca es compatible con el envío y la recepción de mensajes en una cola (el modelo punto a punto de JMS) de acuerdo con la [especificación JMS 1.1](http://docs.oracle.com/javaee/6/api/javax/jms/package-summary.html). La biblioteca permite enviar mensajes de texto, bytes u objetos de forma sincrónica a colas de Amazon SQS. La biblioteca también admite la recepción de objetos de forma sincrónica o asincrónica.

Para obtener más información acerca de las características de la Biblioteca de mensajes Java de Amazon SQS que admiten la especificación JMS 1.1, consulte [Implementaciones de JMS 1.1 admitidas por Amazon SQS](supported-implementations.md) y las [preguntas frecuentes de Amazon SQS](https://aws.amazon.com/sqs/faqs/).

# Requisitos previos para trabajar con JMS y Amazon SQS
<a name="prerequisites"></a>

Antes de empezar, debe disponer de los siguientes requisitos previos:
+ **SDK para Java**

  Hay dos formas de incluir el SDK para Java en su proyecto:
  + Descargue e instale el SDK para Java.
  + Utilice Maven para obtener la Biblioteca de mensajes Java de Amazon SQS.
**nota**  
El SDK para Java se incluye como dependencia.  
El [SDK para Java](https://aws.amazon.com/sdkforjava/) y la biblioteca de clientes ampliada de Amazon SQS para Java requieren J2SE Development Kit 8.0 o una versión posterior.

    Para obtener información acerca de la descarga de SDK para Java, consulte [SDK para Java](https://aws.amazon.com/sdkforjava/).
+ **Biblioteca de mensajes Java de Amazon SQS** 

  Si no utiliza Maven, debe añadir el paquete `amazon-sqs-java-messaging-lib.jar` a la ruta de clases de Java. Para obtener información sobre la descarga de la biblioteca, consulte [Biblioteca de mensajes Java de Amazon SQS](https://github.com/awslabs/amazon-sqs-java-messaging-lib).
**nota**  
La Biblioteca de mensajes Java de Amazon SQS incluye compatibilidad con [Maven](http://maven.apache.org/) y [Spring Framework](http://projects.spring.io/spring-framework/).  
Para obtener ejemplos de código en los que se utiliza Maven, el marco Spring y la Biblioteca de mensajes Java de Amazon SQS, consulte [Ejemplos funcionales en Java del uso de JMS con colas estándar de 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>
  ```
+ **Cola de Amazon SQS**

  Cree una cola mediante la Consola de administración de AWS de para Amazon SQS, la API `CreateQueue` o el cliente de Amazon SQS encapsulado que se incluye en la Biblioteca de mensajes Java de Amazon SQS.
  + Para obtener información acerca de cómo crear una cola con Amazon SQS a través de la Consola de administración de AWS o la API `CreateQueue`, consulte [Creación de colas](creating-sqs-standard-queues.md#step-create-standard-queue).
  + Para obtener información acerca del uso de la Biblioteca de mensajes Java de Amazon SQS, consulte [Uso de la Biblioteca de mensajes Java de Amazon SQS](getting-started.md).

# Uso de la Biblioteca de mensajes Java de Amazon SQS
<a name="getting-started"></a>

Para comenzar a utilizar el Servicio de mensajes de Java (JMS) con Amazon SQS, utilice los ejemplos de código de esta sección. En las próximas secciones se muestra cómo crear una conexión JMS y una sesión y cómo enviar y recibir un mensaje.

El objeto cliente de Amazon SQS encapsulado incluido en la Biblioteca de mensajes Java de Amazon SQS comprueba si existe una cola de Amazon SQS. Si la cola no existe, el cliente la crea.

## Creación de una conexión JMS
<a name="creating-connection"></a>

Antes de comenzar, consulte los requisitos previos de [Requisitos previos para trabajar con JMS y Amazon SQS](prerequisites.md).

1. Cree una fábrica de conexiones y llame al método `createConnection` de la fábrica.

   ```
   // 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();
   ```

   La clase `SQSConnection` amplía `javax.jms.Connection`. Junto con los métodos de conexión estándar de JMS, `SQSConnection` ofrece métodos adicionales como, por ejemplo, `getAmazonSQSClient` y `getWrappedAmazonSQSClient`. Ambos métodos le permiten llevar a cabo operaciones administrativas no incluidas en la especificación JMS, como la creación de nuevas colas. Sin embargo, el método `getWrappedAmazonSQSClient` también ofrece una versión encapsulada del cliente de Amazon SQS que utiliza la conexión actual. El contenedor transforma cada excepción del cliente en una `JMSException`, por lo que es más fácil que la utilice el código existente, que espera encontrar `JMSException`.

1. Puede utilizar los objetos de cliente devueltos por `getAmazonSQSClient` y `getWrappedAmazonSQSClient` para realizar operaciones administrativas que no están incluidas en la especificación JMS (por ejemplo, puede crear una cola de Amazon SQS).

    Si dispone de código que espera encontrar excepciones de JMS, debería utilizar `getWrappedAmazonSQSClient`:
   + Si utiliza `getWrappedAmazonSQSClient`, el objeto de cliente devuelto transforma todas las excepciones en las excepciones de JMS.
   + Si utiliza `getAmazonSQSClient`, todas las excepciones serán excepciones de Amazon SQS.

## Creación de una cola de Amazon SQS
<a name="creating-queue"></a>

El objeto de cliente encapsulado comprueba si existe una cola de Amazon SQS.

Si no existe una cola, el cliente la crea. Si la cola existe, la función no devuelve nada. Para obtener más información, consulte la sección "Create the queue if needed" en el ejemplo [TextMessageSender.java](sqs-jms-code-examples.md#example-sender).

### Para crear una cola estándar
<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");
}
```

### Creación de una cola 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**  
La cola FIFO debe finalizar con el sufijo `.fifo`.  
Para obtener más información acerca del atributo `ContentBasedDeduplication`, consulte [Procesamiento una sola vez en Amazon SQS](FIFO-queues-exactly-once-processing.md).

## Envío de mensajes de forma sincrónica
<a name="send-messages-synchronously"></a>

1. Cuando la conexión y la cola de Amazon SQS subyacente estén listas, cree una sesión de JMS sin transacciones con el modo `AUTO_ACKNOWLEDGE`.

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

1. Para enviar un mensaje de texto a la cola, cree una identidad de cola de JMS y un productor de mensajes.

   ```
   // 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. Cree un mensaje de texto y envíelo a la cola.
   + Para enviar un mensaje a una cola estándar, no es necesario configurar ningún parámetro adicional.

     ```
     // 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 un mensaje a una cola FIFO, debe establecer el ID de grupo de mensajes. También puede establecer un ID de desduplicación de mensajes. Para obtener más información, consulte [Términos clave de cola FIFO de 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"));
     ```

## Recepción de mensajes de forma sincrónica
<a name="receive-messages-synchronously"></a>

1. Para recibir mensajes, cree un consumidor para la misma cola e invoque el método `start`.

   Puede llamar al método `start` de la conexión en cualquier momento. Sin embargo, el consumidor no empieza a recibir mensajes hasta que no se le llama.

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

1. Llame al método `receive` del consumidor con un tiempo de espera establecido en 1 segundo y, a continuación, imprima el contenido del mensaje recibido.
   + Cuando se recibe un mensaje de una cola estándar, se puede obtener acceso al contenido del mensaje.

     ```
     // 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());
     }
     ```
   + Tras recibir un mensaje de una cola FIFO, puede obtener acceso al contenido del mensaje y otros atributos del mensaje específicos de FIFO, como el ID del grupo de mensajes, el ID de desduplicación de mensajes y el número de secuencia. Para obtener más información, consulte [Términos clave de cola FIFO de 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. Cierre la conexión y la sesión.

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

El resultado tiene un aspecto similar al siguiente:

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

**nota**  
Puede utilizar el marco Spring para inicializar estos objetos.  
Para obtener más información, consulte `SpringExampleConfiguration.xml`, `SpringExample.java` y el resto de clases auxiliares en `ExampleConfiguration.java` y `ExampleCommon.java` en la sección [Ejemplos funcionales en Java del uso de JMS con colas estándar de Amazon SQS](sqs-jms-code-examples.md).

Para obtener ejemplos completos del envío y la recepción de objetos, consulte [TextMessageSender.java](sqs-jms-code-examples.md#example-sender) y [SyncMessageReceiver.java](sqs-jms-code-examples.md#example-synchronous-message-receiver).

## Recepción de mensajes de forma asincrónica
<a name="receive-messages-asynchronously"></a>

En el ejemplo de [Uso de la Biblioteca de mensajes Java de Amazon SQS](#getting-started), se envía un mensaje a `MyQueue` y se recibe de forma sincrónica.

El siguiente ejemplo muestra cómo recibir los mensajes de forma asíncrona a través de un agente de escucha.

1. Implemente la interfaz `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();
           }
       }
   }
   ```

   Se llama al método `onMessage` de la interfaz `MessageListener` cuando recibe un mensaje. En esta implementación del agente de escucha, se imprime el texto almacenados en el mensaje.

1. En lugar de llamar explícitamente al método `receive` del consumidor, establezca el agente de escucha de mensajes del consumidor en una instancia de la implementación de `MyListener`. El subproceso principal espera un 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);
   ```

Los pasos restantes son idénticos a los del ejemplo [Uso de la Biblioteca de mensajes Java de Amazon SQS](#getting-started). Para obtener un ejemplo completo de un consumidor asíncrono, consulte `AsyncMessageReceiver.java` [Ejemplos funcionales en Java del uso de JMS con colas estándar de Amazon SQS](sqs-jms-code-examples.md).

El resultado de este ejemplo tiene un aspecto similar al siguiente:

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

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

En el ejemplo de [Uso de la Biblioteca de mensajes Java de Amazon SQS](#getting-started), se utiliza el modo `AUTO_ACKNOWLEDGE`, en el que cada mensaje recibido se confirma automáticamente (y, por tanto, se elimina de la cola subyacente de Amazon SQS).

1. Para reconocer explícitamente los mensajes una vez procesados, debe crear la sesión con el modo `CLIENT_ACKNOWLEDGE`.

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

1. Cuando se reciba el mensaje, muéstrelo y acéptelo explícitamente.

   ```
   // 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**  
En este modo, cuando un mensaje se reconoce, todos los mensajes recibidos antes que este mensaje también se reconocen implícitamente. Por ejemplo, si se reciben 10 mensajes y solo se reconoce el décimo mensaje (en el orden en que los mensajes se reciben), los nueve mensajes anteriores también se reconocen.

Los pasos restantes son idénticos a los del ejemplo [Uso de la Biblioteca de mensajes Java de Amazon SQS](#getting-started). Para ver un ejemplo completo de un consumidor sincrónico con el modo de reconocimiento del cliente, consulte `SyncMessageReceiverClientAcknowledge.java` en [Ejemplos funcionales en Java del uso de JMS con colas estándar de Amazon SQS](sqs-jms-code-examples.md).

El resultado de este ejemplo tiene un aspecto similar al siguiente:

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

## Uso del modo de reconocimiento sin orden
<a name="using-unordered-acknowledge-mode"></a>

Cuando se utiliza el modo `CLIENT_ACKNOWLEDGE`, todos los mensajes recibidos antes que un mensaje reconocido explícitamente se reconocen automáticamente. Para obtener más información, consulte [Uso del modo de reconocimiento del cliente](#using-client-acknowledge-mode).

La Biblioteca de mensajes Java de Amazon SQS proporciona otro modo de confirmación. Cuando se utiliza el modo `UNORDERED_ACKNOWLEDGE`, el cliente debe reconocer individualmente y de forma explícita todos los mensajes recibidos, independientemente del orden de recepción. Para ello, cree una sesión con el modo `UNORDERED_ACKNOWLEDGE`.

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

Los pasos restantes son idénticos a los del ejemplo [Uso del modo de reconocimiento del cliente](#using-client-acknowledge-mode). Para obtener un ejemplo completo de un consumidor síncrono con el modo `UNORDERED_ACKNOWLEDGE`, consulte `SyncMessageReceiverUnorderedAcknowledge.java`.

En este ejemplo, el resultado tiene un aspecto similar al siguiente:

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

# Uso del Servicio de mensajes de Java con otros clientes de Amazon SQS
<a name="sqs-jms-client-with-sqs-clients"></a>

El uso del cliente Java Message Service (JMS) de Amazon SQS con el AWS SDK limita el tamaño de los mensajes de Amazon SQS a 256 KB. No obstante, puede crear un proveedor de JMS mediante cualquier cliente de Amazon SQS. Por ejemplo, puede utilizar el cliente de JMS con la biblioteca de clientes ampliada de Amazon SQS para Java a fin de enviar un mensaje de Amazon SQS que contenga una referencia a una carga de mensaje (de hasta 2 GB) en Amazon S3. Para obtener más información, consulte [Administración de mensajes de Amazon SQS grandes mediante Java y Amazon S3](sqs-s3-messages.md).

En el siguiente ejemplo de código Java se crea el proveedor de JMS para la biblioteca de clientes ampliada.

Consulte los requisitos previos en [Requisitos previos para trabajar con JMS y Amazon SQS](prerequisites.md) antes de probar este ejemplo.

```
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);
```

El siguiente ejemplo de código de Java crea la fábrica de conexiones:

```
// 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();
```

# Ejemplos funcionales en Java del uso de JMS con colas estándar de Amazon SQS
<a name="sqs-jms-code-examples"></a>

En los siguientes ejemplos de código se muestra cómo utilizar el Servicio de mensajes de Java (JMS) con las colas estándar de Amazon SQS. Para obtener más información sobre cómo trabajar con colas FIFO, consulte [Creación de una cola FIFO](getting-started.md#creating-queue-FIFO), [Envío de mensajes de forma sincrónica](getting-started.md#send-messages-synchronously) y [Recepción de mensajes de forma sincrónica](getting-started.md#receive-messages-synchronously). (La recepción de mensajes de forma sincrónica es la misma para las colas estándar y FIFO. No obstante, los mensajes de las colas FIFO contienen más atributos).

Consulte los requisitos previos en [Requisitos previos para trabajar con JMS y Amazon SQS](prerequisites.md) antes de probar los siguientes ejemplos.

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

El siguiente ejemplo de código de Java SDK v 1.x establece el nombre de cola predeterminado, la región y las credenciales que se van a utilizar con los demás ejemplos 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>

El siguiente ejemplo de código de Java crea un productor de mensajes 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>

El siguiente ejemplo de código de Java crea un consumidor de mensajes sincrónico.

```
/*
 * 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>

El siguiente ejemplo de código de Java crea un consumidor de mensajes asincrónico.

```
/*
 * 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>

El siguiente ejemplo de código de Java crea un consumidor sincrónico con el modo de reconocimiento del 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>

El siguiente ejemplo de código de Java crea un consumidor sincrónico con el modo de reconocimiento sin orden.

```
/*
 * 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>

El siguiente ejemplo de código XML es un archivo de configuración 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>

El siguiente ejemplo de código Java utiliza el archivo de configuración bean para inicializar sus 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>

En el siguiente ejemplo de código Java, se comprueba si existe una cola de Amazon SQS y, si no existe, se crea. También incluye ejemplos de código de registro.

```
/*
 * 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() );
        }
    }
}
```

# Implementaciones de JMS 1.1 admitidas por Amazon SQS
<a name="supported-implementations"></a>

La Biblioteca de mensajes Java de Amazon SQS es compatible con las siguientes [implementaciones de JMS 1.1](http://docs.oracle.com/javaee/6/api/javax/jms/package-summary.html). Para obtener más información sobre las características y capacidades compatibles de la Biblioteca de mensajes Java de Amazon SQS, consulte las [preguntas frecuentes de Amazon SQS](https://aws.amazon.com/sqs/faqs/).

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

## Tipos de mensajes admitidos
<a name="supported-message-types"></a>
+ `ByteMessage`
+ `ObjectMessage`
+ `TextMessage`

## Modos de confirmación de mensajes admitidos
<a name="supported-message-acknowledgement-modes"></a>
+ `AUTO_ACKNOWLEDGE`
+ `CLIENT_ACKNOWLEDGE`
+ `DUPS_OK_ACKNOWLEDGE`
+ `UNORDERED_ACKNOWLEDGE`

**nota**  
El modo `UNORDERED_ACKNOWLEDGE` no forma parte de la especificación JMS 1.1. Este modo ayuda a Amazon SQS a permitir que un cliente de JMS confirme explícitamente un mensaje.

## Propiedades reservadas y encabezados definidos por JMS
<a name="jms-defined-headers-reserved-properties"></a>

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

Al enviar mensajes, puede definir los siguientes encabezados y propiedades para cada mensaje:
+ `JMSXGroupID` (necesario para las colas FIFO, no permitido para las colas estándar)
+ `JMS_SQS_DeduplicationId` (opcional para las colas FIFO, no permitido para las colas estándar)

Después de enviar mensajes, Amazon SQS establece los siguientes encabezados y propiedades para cada mensaje:
+ `JMSMessageID`
+ `JMS_SQS_SequenceNumber` (solo para colas FIFO)

### Para recibir mensajes
<a name="for-receiving-messages"></a>

Después de recibir mensajes, Amazon SQS establece los siguientes encabezados y propiedades para cada mensaje:
+ `JMSDestination`
+ `JMSMessageID`
+ `JMSRedelivered`
+ `JMSXDeliveryCount`
+ `JMSXGroupID` (solo para colas FIFO)
+ `JMS_SQS_DeduplicationId` (solo para colas FIFO)
+ `JMS_SQS_SequenceNumber` (solo para colas FIFO)