Skip to content

Add base java samples #316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 142 additions & 0 deletions base-java/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
# IBM MQ Base Java Samples
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like base-java as a name. Lead with Java eg. Java-MQ


This project provides a set of base Java samples for interacting with IBM MQ using the IBM MQ classes for Java (non-JMS). These include basic examples for put/get, publish/subscribe, and request/response messaging patterns.

## Samples Included

Each sample is located under:

```
src/main/java/com/ibm/mq/samples/java/
```

- `BasicPut.java` – Puts a message onto a queue
- `BasicGet.java` – Gets a message from a queue
- `BasicPub.java` – Publishes a message to a topic
- `BasicSub.java` – Subscribes and receives messages from a topic
- `BasicRequest.java` – Sends a message with a dynamic reply-to queue
- `BasicResponse.java` – Responds to requests received from a queue

## Prerequisites

- Java 8 or higher
- Apache Maven
- IBM MQ installed and running (locally or remotely)

## Project Setup

This is a standard Maven project. All dependencies and build instructions are managed through `pom.xml`.

### Building the Project

To build the project and download dependencies:

```bash
mvn clean package
```
## Running the Samples

Ensure that your environment configuration file (`env.json`) is properly set up. Example:

```json
{
"MQ_ENDPOINTS": [
{
"QMGR": "QM1",
"HOST": "localhost",
"PORT": 1414,
"CHANNEL": "DEV.APP.SVRCONN",
"APP_USER": "app",
"APP_PASSWORD": "passw0rd",
"QUEUE_NAME": "DEV.QUEUE.1",
"BACKOUT_QUEUE": "DEV.QUEUE.2",
"MODEL_QUEUE_NAME": "DEV.APP.MODEL.QUEUE",
"DYNAMIC_QUEUE_PREFIX": "APP.REPLIES.*",
"TOPIC_NAME": "dev/"
}
]
}
```
## Using a CCDT File

Instead of manually specifying connection parameters in `env.json`, you can use a **Client Channel Definition Table (CCDT)** JSON file to define connection configurations. This is useful when connecting to IBM MQ instances in cloud or enterprise environments.

Set the environment variable `MQCCDTURL` to point to the CCDT file:

```bash
export MQCCDTURL=file:/absolute/path/to/ccdt.json
```

> **Note (Windows):** Use `set` instead of `export`:
>
> ```cmd
> set MQCCDTURL=file:C:\path\to\ccdt.json
> ```

The sample will detect `MQCCDTURL` and automatically use it for connection settings. When `MQCCDTURL` is set and starts with `file://`, the program prioritizes CCDT-based configuration and skips `host`, `channel`, and `port` in `env.json`.

Make sure your CCDT file defines the appropriate connection information such as **channel name**, **queue manager**, and **connection name list**.


## Run Instructions

### Put/Get

```bash
mvn exec:java -Dexec.mainClass="com.ibm.mq.samples.java.BasicPut" -Dexec.args="env.json"
mvn exec:java -Dexec.mainClass="com.ibm.mq.samples.java.BasicGet" -Dexec.args="env.json"
```

### Publish/Subscribe

In the **first terminal (subscriber)**:

```bash
mvn exec:java -Dexec.mainClass="com.ibm.mq.samples.java.BasicSub" -Dexec.args="env.json"
```

In the **second terminal (publisher)**:

```bash
mvn exec:java -Dexec.mainClass="com.ibm.mq.samples.java.BasicPub" -Dexec.args="env.json"
```

### Request/Response

In the **first terminal (response)**:

```bash
mvn exec:java -Dexec.mainClass="com.ibm.mq.samples.java.BasicResponse" -Dexec.args="env.json"
```

In the **second terminal (request)**:

```bash
mvn exec:java -Dexec.mainClass="com.ibm.mq.samples.java.BasicRequest" -Dexec.args="env.json"
```
### Terminal 1: Run the Request Sample

1. **Compile** the `BasicRequest.java` file using the required JAR dependencies.
2. **Run** the `BasicRequest` class.
3. The requester sends a message and waits for a response.
4. If `REPLY_QUEUE_NAME` is set, that queue is used for replies; otherwise, a temporary queue is created.
5. Optionally, set the `REQUEST_MESSAGE_EXPIRY` environment variable to define how long the request is valid.

---

### Terminal 2: Run the Response Sample

1. **Compile** the `BasicResponse.java` file with the same JAR dependencies.
2. **Run** the `BasicResponse` class.
3. The responder listens on a queue, processes incoming messages, and sends replies to the specified reply-to queue.
4. It continues running until manually stopped or it times out.
5. You can set the `RESPONDER_INACTIVITY_TIMEOUT` environment variable to control how long it waits for new messages before exiting.

---
## Notes

- The environment can be configured using either `env.json` or a CCDT file via the `MQCCDTURL` environment variable.
- Each sample reads from the provided `env.json` to extract connection information for the queue manager.
- Samples like `BasicResponse` and `BasicSub` are long-running and wait for messages indefinitely until stopped.
- Make sure all relevant queues and topics are pre-created in your IBM MQ queue manager.

55 changes: 55 additions & 0 deletions base-java/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

file is missing copyright

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.ibm.mq.samples</groupId>
<artifactId>mq-java-base-consumer</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>

<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
<!-- MQ Classes for Java (Base Java MQ API) -->
<dependency>
<groupId>com.ibm.mq</groupId>
<artifactId>com.ibm.mq.allclient</artifactId>
<version>9.4.3.0</version>
</dependency>

<!-- JSON library -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240303</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>1.8</release>
</configuration>
</plugin>
</plugins>
</build>

</project>










133 changes: 133 additions & 0 deletions base-java/src/main/java/com/ibm/mq/samples/java/BasicGet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package com.ibm.mq.samples.java;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing copyright


import com.ibm.mq.*;
import com.ibm.mq.constants.MQConstants;
import org.json.*;

import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Hashtable;

public class BasicGet {

private static class MQDetails {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This class is repeated in all these samples, best to have a separate .java file for it.

Or to create a base class that BasicGet etc inherit from.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

String QMGR;
String QUEUE_NAME;
String HOST;
String PORT;
String CHANNEL;
String USER;
String PASSWORD;
String KEY_REPOSITORY;
String CIPHER;
}

private static JSONArray endpoints;

public static void main(String[] args) {
loadEnv("env.json");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

loadEnv, everything to do with env.json is common to all these files - needs to be in a separate file - used by the base class.

This main should

BasicGet bg = new BasicGet()

which in turn would new BasicBase()
which should load the endpoints as a class instance, and provide getter methods to read and manipulate them.


for (int i = 0; i < endpoints.length(); i++) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This for loop is common - should be a private method in the base class.

System.out.println("Processing endpoint " + i);
JSONObject point = endpoints.getJSONObject(i);
MQDetails details = buildMQDetails(point);
processEndpoint(details);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need a more meaningful name than processEndpoint

}

System.out.println("Sample MQ GET application ending");
}

private static void loadEnv(String path) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

repeated code - should be in a private class method (ie not static) in the shared base class.

try {
String content = new String(Files.readAllBytes(Paths.get(path)));
JSONObject env = new JSONObject(content);
endpoints = env.getJSONArray("MQ_ENDPOINTS");
} catch (Exception e) {
e.printStackTrace();
}
}

private static MQDetails buildMQDetails(JSONObject endpoint) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

repeated code - etc.

MQDetails mq = new MQDetails();
mq.QMGR = endpoint.getString("QMGR");
mq.QUEUE_NAME = endpoint.getString("QUEUE_NAME");
mq.HOST = endpoint.getString("HOST");
mq.PORT = String.valueOf(endpoint.getInt("PORT"));
mq.CHANNEL = endpoint.getString("CHANNEL");
mq.USER = endpoint.getString("APP_USER");
mq.PASSWORD = endpoint.getString("APP_PASSWORD");
mq.KEY_REPOSITORY = endpoint.optString("KEY_REPOSITORY", "");
mq.CIPHER = endpoint.optString("CIPHER", "");
return mq;
}

private static void processEndpoint(MQDetails details) {
MQQueueManager qMgr = null;
MQQueue queue = null;

try {
Hashtable<String, Object> props = new Hashtable<>();
String ccdtUrl = System.getenv("MQCCDTURL");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Common shared check - should be a public method in the base class which all subclasses can invoke.


if (ccdtUrl != null && ccdtUrl.startsWith("file://")) {
String ccdtPath = ccdtUrl.replace("file://", "");
System.setProperty("MQCCDTURL", ccdtPath);
System.out.println("Using CCDT at: " + ccdtPath);
} else {
props.put(MQConstants.HOST_NAME_PROPERTY, details.HOST);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shared code - pubic method in shared base class.

props.put(MQConstants.PORT_PROPERTY, Integer.parseInt(details.PORT));
props.put(MQConstants.CHANNEL_PROPERTY, details.CHANNEL);
}

props.put(MQConstants.USER_ID_PROPERTY, details.USER);
props.put(MQConstants.PASSWORD_PROPERTY, details.PASSWORD);
props.put(MQConstants.TRANSPORT_PROPERTY, MQConstants.TRANSPORT_MQSERIES_CLIENT);

if (!details.KEY_REPOSITORY.isEmpty()) {
props.put(MQConstants.SSL_CIPHER_SUITE_PROPERTY, details.CIPHER);
System.setProperty("com.ibm.mq.ssl.keyStore", details.KEY_REPOSITORY);
System.setProperty("com.ibm.mq.ssl.keyStorePassword", "");
}

qMgr = new MQQueueManager(details.QMGR, props);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shared code - paramatized pubic method in base class.

System.out.println("Connected to queue manager: " + details.QMGR);

int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF;
queue = qMgr.accessQueue(details.QUEUE_NAME, openOptions);

boolean keepReading = true;
while (keepReading) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finally code that belongs in the BasicGet

MQMessage msg = new MQMessage();
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.options = MQConstants.MQGMO_NO_WAIT |
MQConstants.MQGMO_CONVERT |
MQConstants.MQGMO_FAIL_IF_QUIESCING;

try {
queue.get(msg, gmo);
String str = msg.readStringOfByteLength(msg.getDataLength());
System.out.println("Received message: " + str);
} catch (MQException mqe) {
if (mqe.reasonCode == MQConstants.MQRC_NO_MSG_AVAILABLE) {
keepReading = false;
System.out.println("No more messages.");
} else {
System.err.println("Error retrieving message: " + mqe);
keepReading = false;
}
}
}

} catch (Exception e) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

best to have a common method - in base class - to handle the displaying of exceptions, so can show nested exceptions.

e.printStackTrace();
} finally {
try {
if (queue != null) queue.close();
if (qMgr != null) qMgr.disconnect();
} catch (MQException me) {
me.printStackTrace();
}
}
}
}
Loading