Skip to content

Instantly share code, notes, and snippets.

@MarkBluemel
Last active December 7, 2016 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkBluemel/60ede78af84cb5de213a0c8bac94c3b7 to your computer and use it in GitHub Desktop.
Save MarkBluemel/60ede78af84cb5de213a0c8bac94c3b7 to your computer and use it in GitHub Desktop.
The three Java source files included illustrate how to use the new REST API to retrieve information about MQ installations and MQ queue managers. The AbstractQuerySample is the common superclass to QmgrQuerySample and InstallationQuerySample.
The samples are purely illustrative and are not examples of recommended practice.
The samples parse the "application:json" formatted data using the "org.json" classes which will need to be installed, otherwise the code is "vanilla" J2SE code which was built and tested using Java 8.
The code is currently expected to be in the Java package "com.ibm.mq.restapi.samples", but can of course be moved.
The code currently expects to connect using http, as that simplifies setup! (Like I said this is not recommended practice).
The samples are controlled by System Properties
-Dhost=name specifies the host to connect to (default is "localhost")
-Dport=#### specifies the port number to connect to (default is 9080)
-Dextended=true|false specifies whether extended data is to be retrieved (default is false)
-Dinstallation=name requests InstallationQuerySample to retrieve data about a specific installation
-DqueueManager=name requests QmgrQuerySample to retrieve data about a specific queue manager
package com.ibm.mq.restapi.samples;
import java.io.*;
import java.net.*;
import java.util.*;
import org.json.*;
/**
* <p>
* Common elements for all Rest API query samples
* </p>
* <p>
* Very simple example of accessing the MQ Rest API to get information about all
* entities of a specific type - error handling in particular is skimped on
* </p>
* <p>
* Operation is controlled by optional System properties:-
* </p>
* <ul>
* <li>-Dhost=name</li>
* <li>-Dport=port</li>
* <li>-Dextended=true|false</li>
* </ul>
*/
public abstract class AbstractQuerySample {
/* Formats for URLs */
private static final String ALL_BASIC_URL_PATTERN = "http://%s:%s/ibmmq/rest/v1/%s";
private static final String ONE_BASIC_URL_PATTERN = "http://%s:%s/ibmmq/rest/v1/%s/%s";
protected String hostName; // Host where the API is exposed
protected String port; // Port on which the API is exposed
protected boolean extended; // Whether we want "extended" data retrieved
protected String entityType;
protected String specificEntity;
/**
* Constructor for an "all entities" query
*/
public AbstractQuerySample(String requestedHost, String requestedPort, boolean extendedRequired,
String entityType) {
hostName = requestedHost;
port = requestedPort;
extended = extendedRequired;
this.entityType = entityType;
}
/**
* Constructor for a "specific entity" query
*/
public AbstractQuerySample(String requestedHost, String requestedPort, boolean extendedRequired, String entityType,
String specificEntity) {
this(requestedHost, requestedPort, extendedRequired, entityType);
this.specificEntity = specificEntity;
}
/**
* Subclasses must implement this to identify the basic attributes expected
* in responses
*
* @return an array of attribute names
*/
abstract protected String[] getBasicAttributeList();
/**
* Actually performs the query
*/
protected void retrieveAndReport() throws MalformedURLException, IOException, JSONException {
String url = (specificEntity != null)
? String.format(ONE_BASIC_URL_PATTERN, hostName, port, entityType, specificEntity)
: String.format(ALL_BASIC_URL_PATTERN, hostName, port, entityType);
if (extended) {
url += "?attributes=extended";
}
System.out.format("Opening URL '%s'%n", url);
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setRequestProperty("Accept-Charset", java.nio.charset.StandardCharsets.UTF_8.name());
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
reportSuccess(urlConnection);
} else {
System.out.format("Retrieval failed with HTTP response code %d%n", urlConnection.getResponseCode());
reportFailure(urlConnection);
}
}
/**
* Report failures on the query
*/
private void reportFailure(HttpURLConnection urlConnection) throws IOException, JSONException {
// get the error response string
InputStream responseStream = urlConnection.getErrorStream();
String responseString = null;
try (Scanner scanner = new Scanner(responseStream)) {
responseString = scanner.useDelimiter("\\A").next();
}
JSONObject fullResponse = new JSONObject(responseString);
JSONArray allErrors = fullResponse.getJSONArray("error");
if (allErrors != null) {
int errorCount = allErrors.length(); // almost certainly 1!
for (int i = 0; i < errorCount; i++) {
System.out.println("REST API Reported error:");
JSONObject currentError = allErrors.getJSONObject(i);
for (String attribute : new String[] { "type", "msgId", "message", "explanation", "action" }) {
String value = currentError.optString(attribute, null);
if (value != null) {
System.out.format("\t%-12.12s : %s%n", attribute, value);
}
}
}
}
}
/**
* Report results of the query
*/
private void reportSuccess(HttpURLConnection urlConnection) throws IOException, JSONException {
// Get the response string
InputStream responseStream = urlConnection.getInputStream();
String responseString = null;
try (Scanner scanner = new Scanner(responseStream)) {
responseString = scanner.useDelimiter("\\A").next();
}
// Try to get it as a JSONObject
JSONObject fullResponse = new JSONObject(responseString);
// Results are be a JSONArray of JSONObjects named by entity type
JSONArray allEntities = fullResponse.getJSONArray(entityType);
int entityCount = allEntities.length();
for (int i = 0; i < entityCount; i++) {
JSONObject currentEntity = allEntities.getJSONObject(i);
// Dump out the basic attributes - listed by the subclass
for (String attribute : getBasicAttributeList()) {
String value = currentEntity.optString(attribute, null);
if (value != null) {
System.out.format("%-8.8s : %s%n", attribute, value);
}
}
// If we have extended data, report that
JSONObject extended = currentEntity.optJSONObject("extended");
if (extended != null) {
Iterator<String> allExtendedAttributes = extended.keys(); // Unordered!
while (allExtendedAttributes.hasNext()) {
String attribute = allExtendedAttributes.next();
String value = extended.optString(attribute, null);
if (value != null) {
System.out.format("\t%-20.20s : %s%n", attribute, value);
/* 20 is a little arbitrary! */
}
}
}
System.out.println();
}
}
}
package com.ibm.mq.restapi.samples;
/*
* Copyright (c) 2016 IBM Corp.
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software
* and associated documentation files (the "Software"),
* to deal in the Software without restriction,
* including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice
* shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
* ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
* SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
/**
* <p>
* Operation is controlled by optional System properties:-
* </p>
* <dl>
* <dt>-Dhost=name</dt>
* <dd>Host name to which to connect - defaults to "localhost"</dd>
* <dt>-Dport=port</dt>
* <dd>Port number on which the api is exposed - defaults to "9080"</dd>
* <dt>-Dextended=true|false</dt>
* <dd>Whether or not to retrieve extended data - defaults to false</dd>
* <dt>-Dinstallation=name</dt>
* <dd>A specific installation against which to enquire</dd>
* </dl>
*/
public class InstallationQuerySample extends AbstractQuerySample {
public InstallationQuerySample(String requestedHost, String requestedPort, boolean extendedRequired) {
super(requestedHost, requestedPort, extendedRequired, "installation");
}
public InstallationQuerySample(String requestedHost, String requestedPort, boolean extendedRequired,
String installation) {
super(requestedHost, requestedPort, extendedRequired, "installation", installation);
}
public static void main(String[] arg) throws MalformedURLException, IOException, JSONException {
String requestedHost = System.getProperty("host", "localhost");
String requestedPort = System.getProperty("port", "9080");
boolean extendedRequired = Boolean.getBoolean("extended");
String installation = System.getProperty("installation");
if (installation != null) {
new InstallationQuerySample(requestedHost, requestedPort, extendedRequired, installation)
.retrieveAndReport();
} else {
new InstallationQuerySample(requestedHost, requestedPort, extendedRequired).retrieveAndReport();
}
}
@Override
protected String[] getBasicAttributeList() {
return new String[] { "name", "platform", "version" };
}
}
Copyright (c) 2016 IBM Corp.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package com.ibm.mq.restapi.samples;
/*
* Copyright (c) 2016 IBM Corp.
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software
* and associated documentation files (the "Software"),
* to deal in the Software without restriction,
* including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice
* shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
* ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
* SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
public class QmgrQuerySample extends AbstractQuerySample {
public QmgrQuerySample(String requestedHost, String requestedPort, boolean extendedRequired) {
super(requestedHost, requestedPort, extendedRequired, "qmgr");
}
public QmgrQuerySample(String requestedHost, String requestedPort, boolean extendedRequired, String qmName) {
super(requestedHost, requestedPort, extendedRequired, "qmgr", qmName);
}
public static void main(String[] arg) throws MalformedURLException, IOException, JSONException {
String requestedHost = System.getProperty("host", "localhost");
String requestedPort = System.getProperty("port", "9080");
boolean extendedRequired = Boolean.getBoolean("extended");
String qmName = System.getProperty("queueManager");
if (qmName != null) {
new QmgrQuerySample(requestedHost, requestedPort, extendedRequired, qmName).retrieveAndReport();
} else {
new QmgrQuerySample(requestedHost, requestedPort, extendedRequired).retrieveAndReport();
}
}
@Override
protected String[] getBasicAttributeList() {
return new String[] { "name", "status" }; // status will become "state"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment