

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon SQS での JMS の使用
<a name="sqs-java-message-service-jms-client"></a>

Amazon SQS Java Messaging Library は、Amazon SQS 用の Java Message Service (JMS) インターフェイスで、既に JMS を使用しているアプリケーションで Amazon SQS を利用できます。このインターフェイスにより、最小限のコードの変更で、 Amazon SQS をJMSプロバイダーとして使用できます。AWS SDK for Javaと一緒に Amazon SQS Java Messaging Library を使用すると、JMS 接続およびセッション、Amazon SQS キューとの間でメッセージを送受信するプロデューサーおよびコンシューマーを作成することができます。

ライブラリは、[JMS1.1の仕様](http://docs.oracle.com/javaee/6/api/javax/jms/package-summary.html)に規定されている、キューとのメッセージの送受信 (JMSポイントツーポイントモデル) をサポートしています。ライブラリは、テキスト、バイト、または Amazon SQSキューへのオブジェクトメッセージの同期的な送信をサポートしています。また、オブジェクトの同期的または非同期的な受信もサポートしています。

JMS 1.1 仕様をサポートする Amazon SQS Java Messaging Library の機能の詳細については、「[Amazon SQS でサポートされている JMS 1.1 実装](supported-implementations.md)」および「[Amazon SQS に関するよくある質問](https://aws.amazon.com/sqs/faqs/)」を参照してください。

# JMS と Amazon SQS を使用するための前提条件
<a name="prerequisites"></a>

始めるには以下の前提条件を満たす必要があります:
+ ** SDK for Java**

  プロジェクトにSDK for Javaを含めるには以下の2つの方法があります:
  + SDK for Java をダウンロードしてインストールします。
  + Maven を使用して Amazon SQS Java Messaging Library を入手します。
**注記**  
SDK for Javaは依存関係として含められます。  
[SDK for Java](https://aws.amazon.com/sdkforjava/) と Java 用 Amazon SQS 拡張クライアントライブラリには、J2SE Development Kit 8.0 以降が必要です。

    SDK for Java のダウンロードの詳細については、「[ SDK for Java](https://aws.amazon.com/sdkforjava/)」を参照してください。
+ **Amazon SQS Java Messaging Library** 

  Mavenを使用しない場合は、`amazon-sqs-java-messaging-lib.jar`パッケージをJavaクラスパスに追加する必要があります。ライブラリのダウンロードの詳細については、「[Amazon SQS Java Messaging Library](https://github.com/awslabs/amazon-sqs-java-messaging-lib)」を参照してください。
**注記**  
Amazon SQS Java Messaging Library には、[Maven](http://maven.apache.org/)と [Spring フレームワーク](http://projects.spring.io/spring-framework/)のサポートが含まれます。  
Maven、Spring フレームワーク、Amazon SQS Java Messaging Library を使用するサンプルコードについては、「[Amazon SQS 標準キューで JMS を使用するための実用的な Java の例](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>
  ```
+ **Amazon SQS キュー**

  Amazon SQS 用のAWS マネジメントコンソール、`CreateQueue` API、または Amazon SQS Java Messaging Library に含まれているラップされた Amazon SQS クライアントを使用してキューを作成します。
  + Amazon SQS AWS マネジメントコンソールまたは`CreateQueue`の APIを使用してキューを作成する方法については、「[キューの作成](creating-sqs-standard-queues.md#step-create-standard-queue)」を参照してください。
  + Amazon SQS Java Messaging Library の使用の詳細については、「[Amazon SQS Java Messaging Library の使用](getting-started.md)」を参照してください。

# Amazon SQS Java Messaging Library の使用
<a name="getting-started"></a>

Amazon SQSでJava Message Service (JMS)の使用を開始するには、このセクションのコード例を使用します。以降のセクションでは、JMS接続およびセッションの作成方法や、メッセージの送受信方法を説明します。

Amazon SQS Java Messaging Library に含まれるラップされた Amazon SQS クライアントオブジェクトは、Amazon SQS キューが存在するかどうかをチェックします。キューが存在しない場合は、クライアントがキューを作成します。

## JMS接続の作成
<a name="creating-connection"></a>

開始する前に、「[JMS と Amazon SQS を使用するための前提条件](prerequisites.md)」の前提条件を参照してください。

1. 接続ファクトリを作成し、そのファクトリに対して`createConnection` メソッドを呼び出します。

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

   `SQSConnection`クラスは `javax.jms.Connection` を拡張します。JMSのスタンダード接続メソッドと共に、`SQSConnection`は、`getAmazonSQSClient`や `getWrappedAmazonSQSClient`などの追加のメソッドも提供します。どちらのメッソドでも、新しいキューの作成などのJMS仕様には含まれていない管理操作を実行できます。ただし、`getWrappedAmazonSQSClient`メソッドは現在接続で使用されているAmazon SQSクライアントのラップされたバージョンも提供します。ラッパーはクライアントからのすべての例外を `JMSException` に変換するので、`JMSException` を想定する既存のコードでより容易に使用できます。

1. `getAmazonSQSClient`や`getWrappedAmazonSQSClient`から返されるクライアントオブジェクトを使用して、JMS 仕様には含まれていない管理操作 (Amazon SQS キューの作成など) を実行できます。

    既存のコードで JMS 例外を想定している場合は、`getWrappedAmazonSQSClient` を使用する必要があります:
   + `getWrappedAmazonSQSClient`を使用する場合、返されるクライアントオブジェクトはすべての例外をJMS例外に変換します。
   + `getAmazonSQSClient`を使用する場合、例外はすべてAmazon SQS例外になります。

## Amazon SQSキューを作成する
<a name="creating-queue"></a>

ラップされたクライアントオブジェクトは、 Amazon SQSキューが存在するかどうかを確認します。

キューが存在しない場合は、クライアントがキューを作成します。キューが存在する場合、関数からは何も返されません。詳細については、[TextMessageSender.java](sqs-jms-code-examples.md#example-sender) にある「必要に応じてキューを作成する」セクションを参照してください。

### 標準キューを作成するには
<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");
}
```

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

**注記**  
FIFO キュー名は`.fifo`のサフィックスで終わる必要があります。  
`ContentBasedDeduplication`属性の詳細については、「[Amazon SQS の 1 回のみ処理](FIFO-queues-exactly-once-processing.md)」を参照してください。

## 同期的なメッセージの送信
<a name="send-messages-synchronously"></a>

1. 接続と基になる Amazon SQS キューの準備ができたら、 `AUTO_ACKNOWLEDGE`モードで非トランザクションJMSセッションを作成します。

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

1. テキストメッセージをキューに送信するには、JMS キュー ID とメッセージプロデューサーを作成します。

   ```
   // 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. テキストメッセージを作成し、キューに送信します。
   + メッセージを標準キューに送信するために、追加のパラメータを設定する必要はありません。

     ```
     // Create the text message
     TextMessage message = session.createTextMessage("Hello World!");
      
     // Send the message
     producer.send(message);
     System.out.println("JMS Message " + message.getJMSMessageID());
     ```
   + メッセージをFIFOキューに送信するには、メッセージのグループ IDを設定する必要があります。メッセージ重複排除IDを設定することもできます。詳細については、「[Amazon SQS の FIFO キューの主要な用語](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"));
     ```

## 同期的なメッセージの受信
<a name="receive-messages-synchronously"></a>

1. メッセージを受信するには、同じキューにコンシューマーを作成し、`start`メソッドを呼び出します。

   接続での`start`メソッドはいつでも呼び出すことができます。ただし、コンシューマーは呼び出されるまでメッセージの受信を開始しません。

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

1. コンシューマーで、タイムアウトを1秒に設定して`receive`メソッドを呼び出し、受信メッセージの内容を出力します。
   + 標準キューからメッセージを受信したら、メッセージの内容にアクセスできます。

     ```
     // 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());
     }
     ```
   + FIFOキューからメッセージを受信したら、メッセージの内容や、その他のFIFO 固有のメッセージ属性 (メッセージグループ ID、メッセージ重複排除 ID、シーケンス番号など) にアクセスできます。詳細については、「[Amazon SQS の FIFO キューの主要な用語](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. 接続とセッションを閉じます。

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

出力は次の例のようになります:

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

**注記**  
Spring Framework を使用してこれらのオブジェクトを初期化できます。  
追加情報については、「`SpringExampleConfiguration.xml`」、`SpringExample.java`、および`ExampleConfiguration.java`のほか、`ExampleCommon.java`および[Amazon SQS 標準キューで JMS を使用するための実用的な Java の例](sqs-jms-code-examples.md) に含まれる他のヘルパークラスを参照してください。

オブジェクトの送受信の完全な例については、[TextMessageSender.java](sqs-jms-code-examples.md#example-sender)および[SyncMessageReceiver.java](sqs-jms-code-examples.md#example-synchronous-message-receiver)を参照してください。

## 非同期的なメッセージの受信
<a name="receive-messages-asynchronously"></a>

「[Amazon SQS Java Messaging Library の使用](#getting-started)」の例では、メッセージは`MyQueue`に送信され、同期的に受信されます。

以下の例では、リスナーを介してメッセージを非同期的に受信する方法を示します。

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

   `onMessage`インターフェイスの`MessageListener`メソッドは、メッセージを受信すると呼び出されます。このリスナーの実装内で、メッセージに格納されたテキストが出力されます。

1. コンシューマーで明示的に`receive`メソッドを呼び出す代わりに、コンシューマーのメッセージリスナーを`MyListener`実装のインスタンスに設定します。メインスレッドは1秒間待機します。

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

残りの手順は、「[Amazon SQS Java Messaging Library の使用](#getting-started)」の例の手順と同じです。非同期コンシューマーの完全な例については、「`AsyncMessageReceiver.java`」の[Amazon SQS 標準キューで JMS を使用するための実用的な Java の例](sqs-jms-code-examples.md)を参照してください。

この例の出力は以下の例のようになります:

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

## クライアント確認モードの使用
<a name="using-client-acknowledge-mode"></a>

「[Amazon SQS Java Messaging Library の使用](#getting-started)」の例では`AUTO_ACKNOWLEDGE` モードを使用しています。この場合、受信したすべてのメッセージは自動的に確認されます (このため、基になるAmazon SQSキューから削除されます)。

1. メッセージが処理された後にメッセージを明示的に確認するには、`CLIENT_ACKNOWLEDGE`モードでセッションを作成する必要があります。

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

1. メッセージが受信されたら、メッセージを表示して、その後明示的に確認します。

   ```
   // 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());
   }
   ```
**注記**  
このモードでは、メッセージが確認されると、そのメッセージ以前に受信されたすべてのメッセージも暗黙的に確認されます。たとえば、10通のメッセージが受信され、(受信した順序で)10番目のメッセージのみが確認された場合、前の9通のメッセージもすべて確認されます。

残りの手順は、「[Amazon SQS Java Messaging Library の使用](#getting-started)」の例の手順と同じです。クライアント確認モードの同期コンシューマーの完全な例については、「`SyncMessageReceiverClientAcknowledge.java`」の[Amazon SQS 標準キューで JMS を使用するための実用的な Java の例](sqs-jms-code-examples.md)を参照してください。

この例の出力は以下の例のようになります:

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

## 順不同確認モードの使用
<a name="using-unordered-acknowledge-mode"></a>

`CLIENT_ACKNOWLEDGE`モードを使用すると、明示的に確認されたメッセージの前に受信されたすべてのメッセージが自動的に確認されます。詳細については、「[クライアント確認モードの使用](#using-client-acknowledge-mode)」を参照してください。

Amazon SQS Java Messaging Library には別の確認モードも用意されています。`UNORDERED_ACKNOWLEDGE` モードを使用する場合は、受信した順序に関係なく、すべての受信メッセージを個別かつ明示的にクライアントが確認する必要があります。これには、`UNORDERED_ACKNOWLEDGE`モードでセッションを作成します。

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

残りの手順は、「[クライアント確認モードの使用](#using-client-acknowledge-mode)」の例の手順と同じです。`UNORDERED_ACKNOWLEDGE`モードの同期コンシューマーの完全な例については、`SyncMessageReceiverUnorderedAcknowledge.java`を参照してください。

この例の出力は以下のようになります:

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

# Java Message Service を他の Amazon SQS クライアントで使用する
<a name="sqs-jms-client-with-sqs-clients"></a>

 AWS SDK で Amazon SQS Java Message Service (JMS) クライアントを使用すると、Amazon SQS メッセージサイズは 256 KB に制限されます。ただし、任意のAmazon SQSクライアントを使用してJMSプロバイダを作成することができます。たとえば、Java用の Amazon SQS 拡張クライアントライブラリ とJMSクライアントを使用する場合、Amazon S3内のメッセージペイロード (最大2GB)への参照を含むAmazon SQSメッセージを送信することができます。詳細については、「[Java と Amazon S3 を使用した大量の Amazon SQS メッセージの管理](sqs-s3-messages.md)」を参照してください。

次の Java コード例では、拡張クライアントライブラリの JMS プロバイダーを作成します。

この例をテストする前に、「[JMS と Amazon SQS を使用するための前提条件](prerequisites.md)」の前提条件を参照してください。

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

次のJavaコード例は、接続ファクトリを作成しています:

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

# Amazon SQS 標準キューで JMS を使用するための実用的な Java の例
<a name="sqs-jms-code-examples"></a>

以下のコード例では、Java Message Service (JMS) を Amazon SQS の標準キューで使用する方法を示します。FIFO キューの操作方法の詳細については、「[FIFOキューを作成するには](getting-started.md#creating-queue-FIFO)」 、「[同期的なメッセージの送信](getting-started.md#send-messages-synchronously)」、および「[同期的なメッセージの受信](getting-started.md#receive-messages-synchronously)」を参照してください。(メッセージを同期して受信することは、標準キューでも FIFO キューでも同じです。ただし、FIFO キューのメッセージには、より多くの属性が含まれます)。

以下の例をテストする前に、「[JMS と Amazon SQS を使用するための前提条件](prerequisites.md)」の前提条件を参照してください。

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

次の Java コード例では、他の 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>

次の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 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>

次の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 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>

次の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 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>

次の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.
 *
 */

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

次の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.
 *
 */

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

次のXMLコード例は、[SpringExample.java](#example-spring)のBean構成ファイルです。

```
<!--
    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>

次のJavaコード例では、Bean構成ファイルを使用してオブジェクトを初期化しています。

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

次のJavaコード例では、Amazon SQSキューが存在するかどうかを確認し、存在しない場合はキューを作成します。このコード例にはログ記録コードの例も含まれています。

```
/*
 * 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 でサポートされている JMS 1.1 実装
<a name="supported-implementations"></a>

Amazon SQS Java Messaging Library は、以下の [JMS 1.1 実装](http://docs.oracle.com/javaee/6/api/javax/jms/package-summary.html)をサポートしています。Amazon SQS Java Messaging Library でサポートされている機能と性能の詳細については、「[Amazon SQS に関するよくある質問](https://aws.amazon.com/sqs/faqs/)」を参照してください。

## サポートされている共通インターフェース
<a name="supported-common-interfaces"></a>
+ `Connection`
+ `ConnectionFactory`
+ `Destination`
+ `Session`
+ `MessageConsumer`
+ `MessageProducer`

## サポートされているメッセージタイプ
<a name="supported-message-types"></a>
+ `ByteMessage`
+ `ObjectMessage`
+ `TextMessage`

## サポートされているメッセージ確認モード
<a name="supported-message-acknowledgement-modes"></a>
+ `AUTO_ACKNOWLEDGE`
+ `CLIENT_ACKNOWLEDGE`
+ `DUPS_OK_ACKNOWLEDGE`
+ `UNORDERED_ACKNOWLEDGE`

**注記**  
`UNORDERED_ACKNOWLEDGE`モードはJMS1.1仕様パートには含まれていません。このモードにより、JMSクライアントによるメッセージの明示的な確認を Amazon SQS が許可できるようになります。

## JMS定義ヘッダーと予約プロパティ
<a name="jms-defined-headers-reserved-properties"></a>

### メッセージの送信用
<a name="for-sending-messages"></a>

メッセージを送信する場合は、各メッセージに以下のヘッダーおよびプロパティを設定できます:
+ `JMSXGroupID` (FIFOキューの場合は必須で、スタンドダードキューには許可されません)
+ `JMS_SQS_DeduplicationId`(FIFO キューではオプション、標準キューでは許可されません)

メッセージを送信すると、Amazon SQSにより各メッセージに以下のヘッダーおよびプロパティが設定されます:
+ `JMSMessageID`
+ `JMS_SQS_SequenceNumber`(FIFO キューの場合のみ)

### メッセージの受信用
<a name="for-receiving-messages"></a>

メッセージを受信すると、Amazon SQSにより各メッセージに以下のヘッダーおよびプロパティが設定されます:
+ `JMSDestination`
+ `JMSMessageID`
+ `JMSRedelivered`
+ `JMSXDeliveryCount`
+ `JMSXGroupID`(FIFO キューの場合のみ)
+ `JMS_SQS_DeduplicationId`(FIFO キューの場合のみ)
+ `JMS_SQS_SequenceNumber`(FIFO キューの場合のみ)