

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

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

Amazon SQS Java Messaging Library è un'interfaccia Java Message Service (JMS) per Amazon SQS che consente di sfruttare Amazon SQS in applicazioni che già utilizzano JMS. L'interfaccia consente di usare Amazon SQS come provider JMS, riducendo al minimo le modifiche al codice. Insieme a AWS SDK per Java, la raccolta di messaggistica Amazon SQS Java ti consente di creare connessioni e sessioni JMS, nonché produttori e consumatori in grado di inviare e ricevere messaggi da e verso code Amazon SQS.

La libreria supporta l'invio e la ricezione di messaggi in una coda (il point-to-point modello JMS) secondo la specifica [JMS 1.1](http://docs.oracle.com/javaee/6/api/javax/jms/package-summary.html). La libreria supporta l'invio di testo, byte o messaggi oggetto in modo sincrono a code Amazon SQS. La libreria supporta anche la ricezione di oggetti in modo sincrono o asincrono.

[Per informazioni sulle funzionalità della libreria di messaggistica Java di Amazon SQS che supportano la specifica JMS 1.1, consulta [Amazon SQS supportava le implementazioni di JMS 1.1](supported-implementations.md) Amazon SQS. FAQs](https://aws.amazon.com/sqs/faqs/)

# Prerequisiti per lavorare con JMS e Amazon SQS
<a name="prerequisites"></a>

Prima di iniziare, devi disporre dei seguenti requisiti preliminari:
+ **SDK per Java**

  Ci sono due modi per includere l’SDL per Java nel tuo progetto:
  + Scarica e installa l’SDK per Java.
  + Utilizza Maven per ottenere la raccolta di messaggistica Amazon SQS Java.
**Nota**  
SDK per Java è incluso come una dipendenza.  
Gli [SDK per Java](https://aws.amazon.com/sdkforjava/) e la libreria client ampia Amazon SQS per Java richiedono J2SE Development Kit 8.0 o versioni successive.

    Per informazioni su come scaricare il kit SDK AWS per Java, consulta [SDK per Java](https://aws.amazon.com/sdkforjava/).
+ **Raccolta di messaggistica Amazon SQS Java** 

  Se non utilizzi Maven, devi aggiungere il file del pacchetto `amazon-sqs-java-messaging-lib.jar` al percorso di classe Java. Per informazioni su come scaricare la libreria, consulta [raccolta di messaggistica Amazon SQS Java](https://github.com/awslabs/amazon-sqs-java-messaging-lib).
**Nota**  
La raccolta di messaggistica Amazon SQS Java include il supporto per [Maven](http://maven.apache.org/) e [Spring Framework](http://projects.spring.io/spring-framework/).  
Per esempi di codice che utilizzano Maven, Spring Framework e la raccolta di messaggistica Amazon SQS Java, consulta [Esempi Java funzionanti per l'utilizzo di JMS con le code standard di 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>
  ```
+ **Coda Amazon SQS**

  Crea una coda utilizzando Console di gestione AWS per Amazon SQS, l'API o `CreateQueue` il client Amazon SQS wrappato incluso nella Amazon SQS Java Messaging Library.
  + Per ulteriori informazioni su come creare una coda con Amazon SQS utilizzando Console di gestione AWS oppure l'API `CreateQueue`, consulta [Creazione di una coda](creating-sqs-standard-queues.md#step-create-standard-queue).
  + Per informazioni su come utilizzare la raccolta di messaggistica Amazon SQS Java, consulta [Utilizzo della libreria di messaggistica Java di Amazon SQS](getting-started.md).

# Utilizzo della libreria di messaggistica Java di Amazon SQS
<a name="getting-started"></a>

Per iniziare a utilizzare il Servizio messaggi Java (JMS) con Amazon SQS, utilizza gli esempi di codice in questa sezione. Le seguenti sezioni illustrano come creare una connessione e una sessione JMS e come inviare e ricevere un messaggio.

L'oggetto client Amazon SQS incluso nella raccolta di messaggistica Amazon SQS Java verifica se esiste una coda Amazon SQS. Se la coda non esiste, il client la crea.

## Creazione di una connessione JMS
<a name="creating-connection"></a>

Prima di iniziare, consulta i prerequisiti in. [Prerequisiti per lavorare con JMS e Amazon SQS](prerequisites.md)

1. Creare una connection factory e chiamare il metodo `createConnection` rispetto allo stesso.

   ```
   // 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 classe `SQSConnection` estende `javax.jms.Connection`. Insieme ai metodi di connessione JMS standard, `SQSConnection` offre ulteriori metodi, ad esempio `getAmazonSQSClient` e `getWrappedAmazonSQSClient`. Entrambi i metodi consentono di eseguire operazioni di amministrazione non incluse nella specifica JMS, ad esempio la creazione di nuove code. Tuttavia, il metodo `getWrappedAmazonSQSClient` fornisce inoltre una versione integrata del client Amazon SQS utilizzato dalla connessione corrente. Il wrapper trasforma ogni eccezione dal client in una `JMSException`, che può essere utilizzata più facilmente dal codice esistente che si aspetta occorrenze `JMSException`.

1. Puoi utilizzare gli oggetti client restituiti da `getAmazonSQSClient` e `getWrappedAmazonSQSClient` per eseguire operazioni amministrative non incluse nella specifica JMS (ad esempio, è possibile creare una coda Amazon SQS).

    Se disponi di codice esistente che si aspetta eccezioni JMS, devi utilizzare `getWrappedAmazonSQSClient`:
   + Se utilizzi `getWrappedAmazonSQSClient`, l'oggetto client restituito trasforma tutte le eccezioni in eccezioni JMS.
   + Se utilizzi `getAmazonSQSClient`, le eccezioni sono tutte eccezioni Amazon SQS.

## Creazione di una coda Amazon SQS
<a name="creating-queue"></a>

L'oggetto client integrato verifica se esiste una coda Amazon SQS.

Se la coda non esiste, il client la crea. Se la coda esiste, la funzione non restituisce nulla. Per ulteriori informazioni, consulta la sezione "Creare la coda se necessario" nell'esempio [TextMessageSender.java](sqs-jms-code-examples.md#example-sender).

### Per creare una coda standard
<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");
}
```

### Per creare una coda 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**  
Il nome di una coda FIFO deve terminare con il suffisso `.fifo`.  
Per ulteriori informazioni sull'attributo `ContentBasedDeduplication`, consulta [Elaborazione una sola volta in Amazon SQS](FIFO-queues-exactly-once-processing.md).

## Invio di messaggi in modo sincrono
<a name="send-messages-synchronously"></a>

1. Quando la connessione e la coda Amazon SQS sottostante sono pronte, creare una sessione JMS nontransacted con la modalità `AUTO_ACKNOWLEDGE`.

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

1. Per inviare un messaggio di testo alla coda, creare una coda di identità JMS e un produttore del messaggio.

   ```
   // 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. Creare un messaggio di testo e inviarlo alla coda.
   + Per inviare un messaggio a una coda standard, non è necessario impostare parametri aggiuntivi.

     ```
     // Create the text message
     TextMessage message = session.createTextMessage("Hello World!");
      
     // Send the message
     producer.send(message);
     System.out.println("JMS Message " + message.getJMSMessageID());
     ```
   + Per inviare un messaggio a una coda FIFO, è necessario impostare l'ID del gruppo messaggi. Puoi anche impostare un ID di deduplicazione messaggio. Per ulteriori informazioni, consulta [Termini chiave della coda FIFO di 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"));
     ```

## Ricezione di messaggi in modo sincrono
<a name="receive-messages-synchronously"></a>

1. Per ricevere messaggi, creare un consumatore per la stessa coda e chiamare il metodo `start`.

   Puoi chiamare il metodo `start` sulla connessione in qualsiasi momento. Tuttavia, il consumatore non inizia a ricevere messaggi finché non lo chiami.

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

1. Chiamare il metodo `receive` sul consumatore con un timeout impostati su 1 secondo, quindi stampare i contenuti del messaggio ricevuto.
   + Dopo aver ricevuto un messaggio da una coda standard, puoi accedere al contenuto del messaggio.

     ```
     // 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());
     }
     ```
   + Dopo aver ricevuto un messaggio da una coda FIFO puoi accedere al contenuto del messaggio e ad altri attributi di messaggio specifici FIFO, ad esempio l'ID gruppo di messaggi, l'ID di deduplicazione messaggio e il numero di sequenza. Per ulteriori informazioni, consulta [Termini chiave della coda FIFO di 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. Chiudere la connessione e la sessione.

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

L'esito si presenta in maniera analoga all'immagine riportata di seguito.

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

**Nota**  
Puoi utilizzare Spring Framework per inizializzare questi oggetti.  
Per ulteriori informazioni, consulta `SpringExampleConfiguration.xml`, `SpringExample.java` e le altre classi di supporto `ExampleConfiguration.java` e `ExampleCommon.java` nella sezione [Esempi Java funzionanti per l'utilizzo di JMS con le code standard di Amazon SQS](sqs-jms-code-examples.md).

Per completare esempi di invio e ricezione di oggetti, consulta [TextMessageSender.java](sqs-jms-code-examples.md#example-sender) e [SyncMessageReceiver.java](sqs-jms-code-examples.md#example-synchronous-message-receiver).

## Ricezione di messaggi in modo asincrono
<a name="receive-messages-asynchronously"></a>

In questo esempio in [Utilizzo della libreria di messaggistica Java di Amazon SQS](#getting-started), viene inviato un messaggio a `MyQueue` e ricevuto in modo sincrono.

L'esempio seguente mostra come ricevere i messaggi in modo asincrono tramite un listener.

1. Implementare l'interfaccia `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();
           }
       }
   }
   ```

   Il metodo `onMessage` dell'interfaccia `MessageListener` viene chiamato quando si riceve un messaggio. In questa implementazione listener, il testo memorizzato nel messaggio è stampato.

1. Invece di chiamare esplicitamente il metodo `receive` sul consumatore, impostare il listener del messaggio del consumatore a un'istanza dell'implementazione `MyListener`. Il thread principale attende per un secondo.

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

Gli altri passaggi sono identici a quelli dell'esempio [Utilizzo della libreria di messaggistica Java di Amazon SQS](#getting-started). Per un esempio completo di consumatore asincrono, consulta `AsyncMessageReceiver.java` [Esempi Java funzionanti per l'utilizzo di JMS con le code standard di Amazon SQS](sqs-jms-code-examples.md).

L'output per questo esempio appare simile al seguente:

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

## Utilizzo della modalità di riconoscimento client
<a name="using-client-acknowledge-mode"></a>

L'esempio in [Utilizzo della libreria di messaggistica Java di Amazon SQS](#getting-started) utilizza la modalità `AUTO_ACKNOWLEDGE` in cui ogni messaggio ricevuto viene confermato automaticamente (e quindi eliminato dalla coda Amazon SQS sottostante).

1. Per riconoscere i messaggi esplicitamente dopo l'elaborazione, è necessario creare la sessione con la modalità `CLIENT_ACKNOWLEDGE`.

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

1. Quando il messaggio viene ricevuto, visualizzarlo e quindi dichiararlo esplicitamente.

   ```
   // 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**  
In questo modo, quando un messaggio viene confermato, tutti i messaggi ricevuti prima di esso sono implicitamente riconosciuti. Ad esempio, se 10 messaggi vengono ricevuti e solo il decimo messaggio viene confermato (nell'ordine in cui i messaggi vengono ricevuti), anche tutti i nove messaggi precedenti vengono riconosciuti.

Gli altri passaggi sono identici a quelli dell'esempio [Utilizzo della libreria di messaggistica Java di Amazon SQS](#getting-started). Per un esempio completo di un consumatore sincrono con modalità di riconoscimento client, consulta `SyncMessageReceiverClientAcknowledge.java` [Esempi Java funzionanti per l'utilizzo di JMS con le code standard di Amazon SQS](sqs-jms-code-examples.md).

L'output per questo esempio appare simile al seguente:

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

## Utilizzo della modalità di riconoscimento non ordinata
<a name="using-unordered-acknowledge-mode"></a>

Quando utilizzi la modalità `CLIENT_ACKNOWLEDGE`, tutti i messaggi ricevuti prima di un messaggio esplicitamente riconosciuto sono riconosciuti automaticamente. Per ulteriori informazioni, consulta [Utilizzo della modalità di riconoscimento client](#using-client-acknowledge-mode).

La raccolta di messaggistica Amazon SQS Java fornisce un'altra modalità di conferma. Quando utilizzi la modalità `UNORDERED_ACKNOWLEDGE`, tutti i messaggi ricevuti devono essere individualmente ed esplicitamente riconosciuti dal client, indipendentemente dall'ordine di ricezione. Per eseguire questa operazione, è necessario creare una sessione con la modalità `UNORDERED_ACKNOWLEDGE`.

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

Gli altri passaggi sono identici a quelli dell'esempio [Utilizzo della modalità di riconoscimento client](#using-client-acknowledge-mode). Per un esempio completo di consumatore sincrono con la modalità `UNORDERED_ACKNOWLEDGE`, consulta `SyncMessageReceiverUnorderedAcknowledge.java`.

In questo esempio, l'output appare simile al seguente:

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

# Utilizzo di Java Message Service con altri client Amazon SQS
<a name="sqs-jms-client-with-sqs-clients"></a>

L'utilizzo del client Amazon SQS Java Message Service (JMS) con l' AWS SDK limita la dimensione dei messaggi Amazon SQS a 256 KB. Tuttavia, è possibile creare un provider JMS utilizzando qualsiasi client Amazon SQS. Ad esempio, puoi utilizzare il client JMS con la libreria client ampia di Amazon SQS per Java per inviare un messaggio Amazon SQS che contiene un riferimento a un payload del messaggio (fino a 2 GB) in Amazon S3. Per ulteriori informazioni, consulta [Gestione di messaggi Amazon SQS di grandi dimensioni con Java e Amazon S3](sqs-s3-messages.md).

Il seguente esempio di codice Java crea il provider JMS per la Extended Client Library.

Consultate i prerequisiti [Prerequisiti per lavorare con JMS e Amazon SQS](prerequisites.md) prima di testare questo esempio.

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

Il seguente codice Java di esempio crea la 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();
```

# Esempi Java funzionanti per l'utilizzo di JMS con le code standard di Amazon SQS
<a name="sqs-jms-code-examples"></a>

Negli esempi di codice seguenti viene illustrato come utilizzare Servizio messaggi Java (JMS) con le code standard Amazon SQS. Per ulteriori informazioni sull'utilizzo delle code FIFO, consulta [Per creare una coda FIFO](getting-started.md#creating-queue-FIFO), [Invio di messaggi in modo sincrono](getting-started.md#send-messages-synchronously) e [Ricezione di messaggi in modo sincrono](getting-started.md#receive-messages-synchronously). (La ricezione sincrona dei messaggi è la stessa per le code standard e FIFO. Tuttavia, i messaggi nelle code FIFO contengono più attributi).

[Prerequisiti per lavorare con JMS e Amazon SQS](prerequisites.md)Prima di testare i seguenti esempi, consulta i prerequisiti.

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

Il seguente esempio di codice Java SDK v 1.x imposta il nome di coda predefinito, la regione e le credenziali da utilizzare con gli altri esempi 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>

Il seguente codice Java crea un produttore del messaggio di testo.

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

Il seguente codice Java crea un consumatore del messaggio di testo sincrono.

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

Il seguente codice Java crea un consumatore del messaggio di testo asincrono.

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

Il seguente esempio di codice Java crea un consumatore asincrono con modalità di riconoscimento client.

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

Il seguente esempio di codice Java crea un consumatore asincrono con modalità di riconoscimento non ordinato.

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

L'esempio di codice XML riportato di seguito è un file di configurazione bean per [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>

Il seguente codice di esempio Java utilizza il file di configurazione bean per inizializzare i tuoi oggetti.

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

Il seguente codice di esempio Java verifica se una coda Amazon SQS esiste e quindi ne crea una se non esiste. Include anche il codice di registrazione di esempio.

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

# Amazon SQS supportava le implementazioni di JMS 1.1
<a name="supported-implementations"></a>

La raccolta di messaggistica Amazon SQS Java supporta le seguenti [implementazioni JMS 1.1](http://docs.oracle.com/javaee/6/api/javax/jms/package-summary.html). Per ulteriori informazioni sulle caratteristiche e le funzionalità supportate dalla raccolta di messaggistica Amazon SQS Java, consulta le [domande frequenti su Amazon SQS](https://aws.amazon.com/sqs/faqs/).

## Interfacce comuni supportate
<a name="supported-common-interfaces"></a>
+ `Connection`
+ `ConnectionFactory`
+ `Destination`
+ `Session`
+ `MessageConsumer`
+ `MessageProducer`

## Tipi di messaggi supportati
<a name="supported-message-types"></a>
+ `ByteMessage`
+ `ObjectMessage`
+ `TextMessage`

## Modalità di riconoscimento del messaggio supportate
<a name="supported-message-acknowledgement-modes"></a>
+ `AUTO_ACKNOWLEDGE`
+ `CLIENT_ACKNOWLEDGE`
+ `DUPS_OK_ACKNOWLEDGE`
+ `UNORDERED_ACKNOWLEDGE`

**Nota**  
La modalità `UNORDERED_ACKNOWLEDGE` non fa parte della specifica JMS 1.1. Grazie a questa modalità, Amazon SQS può consentire a un client JMS di dichiarare esplicitamente un messaggio.

## Intestazioni definite da JMS e proprietà riservate
<a name="jms-defined-headers-reserved-properties"></a>

### Per l'invio di messaggi
<a name="for-sending-messages"></a>

Quando invii messaggi, puoi impostare le seguenti intestazioni e proprietà per ogni messaggio:
+ `JMSXGroupID` (necessaria per le code FIFO, non consentita per le code standard)
+ `JMS_SQS_DeduplicationId` (opzionale per le code FIFO, non consentita per le code standard)

Dopo che invii messaggi, Amazon SQS imposta le seguenti intestazioni e proprietà per ogni messaggio:
+ `JMSMessageID`
+ `JMS_SQS_SequenceNumber` (solo per code FIFO)

### Per la ricezione di messaggi
<a name="for-receiving-messages"></a>

Quando ricevi messaggi, Amazon SQS imposta le seguenti intestazioni e proprietà per ogni messaggio:
+ `JMSDestination`
+ `JMSMessageID`
+ `JMSRedelivered`
+ `JMSXDeliveryCount`
+ `JMSXGroupID` (solo per code FIFO)
+ `JMS_SQS_DeduplicationId` (solo per code FIFO)
+ `JMS_SQS_SequenceNumber` (solo per code FIFO)