How to set MQ headers using JSR223 sampler in Jmeter - jmeter

I am working on IBM MQ testing. I able to inject my payloads request in MQ destination. I need to put the headers values in MQ to get the correct response. I used various option but still i am unable to put headers values in MQ server. Kindly let me know how can i solve this in JMeter.
Option 1 :
sendmsg = new MQMessage();
sendmsg.setStringProperty("QueryName", "GetPortfolio");
sendmsg.setStringProperty("Country", "LV");
Option 2:
rfh2.setFieldValue('usr', 'QueryName=', 'GetPortfolio')
Option 3:
SampleResult.setRequestHeaders("QueryName=GetPortfolio")

Option # 1 is the correct way of doing it.
Option # 2 could be used but why? And the parameter should not include the equals sign ( i.e. "=").
I have no idea what option # 3 is.
Here is a sample Java/MQ program that puts a message on a queue with named properties .
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import com.ibm.mq.MQException;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.CMQC;
/**
* Program Name
* MQTest11P
*
* Description
* This java class will connect to a remote queue manager with the
* MQ setting stored in a HashTable and put a message on a queue.
*
* Sample Command Line Parameters
* -m MQA1 -h 127.0.0.1 -p 1414 -c TEST.CHL -q TEST.Q1 -u UserID -x Password
*
* #author Roger Lacroix
*/
public class MQTest11P
{
private static final SimpleDateFormat LOGGER_TIMESTAMP = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
private Hashtable<String,String> params;
private Hashtable<String,Object> mqht;
private String qMgrName;
private String outputQName;
/**
* The constructor
*/
public MQTest11P()
{
super();
params = new Hashtable<String,String>();
mqht = new Hashtable<String,Object>();
}
/**
* Make sure the required parameters are present.
* #return true/false
*/
private boolean allParamsPresent()
{
boolean b = params.containsKey("-h") && params.containsKey("-p") &&
params.containsKey("-c") && params.containsKey("-m") &&
params.containsKey("-q") &&
params.containsKey("-u") && params.containsKey("-x");
if (b)
{
try
{
Integer.parseInt((String) params.get("-p"));
}
catch (NumberFormatException e)
{
b = false;
}
}
return b;
}
/**
* Extract the command-line parameters and initialize the MQ HashTable.
* #param args
* #throws IllegalArgumentException
*/
private void init(String[] args) throws IllegalArgumentException
{
int port = 1414;
if (args.length > 0 && (args.length % 2) == 0)
{
for (int i = 0; i < args.length; i += 2)
{
params.put(args[i], args[i + 1]);
}
}
else
{
throw new IllegalArgumentException();
}
if (allParamsPresent())
{
qMgrName = (String) params.get("-m");
outputQName = (String) params.get("-q");
try
{
port = Integer.parseInt((String) params.get("-p"));
}
catch (NumberFormatException e)
{
port = 1414;
}
mqht.put(CMQC.CHANNEL_PROPERTY, params.get("-c"));
mqht.put(CMQC.HOST_NAME_PROPERTY, params.get("-h"));
mqht.put(CMQC.PORT_PROPERTY, new Integer(port));
mqht.put(CMQC.USER_ID_PROPERTY, params.get("-u"));
mqht.put(CMQC.PASSWORD_PROPERTY, params.get("-x"));
// I don't want to see MQ exceptions at the console.
MQException.log = null;
}
else
{
throw new IllegalArgumentException();
}
}
/**
* Connect, open queue, write a message, close queue and disconnect.
*
*/
private void testSend()
{
MQQueueManager qMgr = null;
MQQueue queue = null;
String msgData = "This is a test message from MQTest11P";
int openOptions = CMQC.MQOO_OUTPUT + CMQC.MQOO_FAIL_IF_QUIESCING;
MQPutMessageOptions pmo = new MQPutMessageOptions();
try
{
qMgr = new MQQueueManager(qMgrName, mqht);
MQTest11P.logger("successfully connected to "+ qMgrName);
queue = qMgr.accessQueue(outputQName, openOptions);
MQTest11P.logger("successfully opened "+ outputQName);
// Define a simple MQ message, and write some text
MQMessage sendmsg = new MQMessage();
sendmsg.format = CMQC.MQFMT_STRING;
sendmsg.feedback = CMQC.MQFB_NONE;
sendmsg.messageType = CMQC.MQMT_DATAGRAM;
sendmsg.messageId = CMQC.MQMI_NONE;
sendmsg.correlationId = CMQC.MQCI_NONE;
// Write message data
sendmsg.writeString(msgData);
/**
* Set named properties aka message properties
* that will create a JMS message.
*/
// sendmsg.setStringProperty("mcd.Msd", "jms_text");
// sendmsg.setStringProperty("jms.Dst", "queue:///"+outputQName);
// sendmsg.setStringProperty("jms.Pri", "0");
sendmsg.setStringProperty("QueryName", "GetPortfolio");
sendmsg.setStringProperty("Country", "LV");
// put the message on the queue
queue.put(sendmsg, pmo);
MQTest11P.logger("Message Data>>>" + msgData);
}
catch (MQException e)
{
MQTest11P.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
catch (IOException e)
{
MQTest11P.logger("IOException:" +e.getLocalizedMessage());
}
finally
{
try
{
if (queue != null)
{
queue.close();
MQTest11P.logger("closed: "+ outputQName);
}
}
catch (MQException e)
{
MQTest11P.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
try
{
if (qMgr != null)
{
qMgr.disconnect();
MQTest11P.logger("disconnected from "+ qMgrName);
}
}
catch (MQException e)
{
MQTest11P.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
}
}
/**
* A simple logger method
* #param data
*/
public static void logger(String data)
{
String className = Thread.currentThread().getStackTrace()[2].getClassName();
// Remove the package info.
if ( (className != null) && (className.lastIndexOf('.') != -1) )
className = className.substring(className.lastIndexOf('.')+1);
System.out.println(LOGGER_TIMESTAMP.format(new Date())+" "+className+": "+Thread.currentThread().getStackTrace()[2].getMethodName()+": "+data);
}
/**
* main line
* #param args
*/
public static void main(String[] args)
{
MQTest11P write = new MQTest11P();
try
{
write.init(args);
write.testSend();
}
catch (IllegalArgumentException e)
{
MQTest11P.logger("Usage: java MQTest11P -m QueueManagerName -h host -p port -c channel -q QueueName -u UserID -x Password");
System.exit(1);
}
System.exit(0);
}
}
When I look at the message in the queue with MQ Visual Edit, I see:
So, your 2 named properties are with the message.
The question becomes do you want JUST named properties attached to the message or are you really looking to create a JMS message with named properties?
Note: A JMS message is internally defined as an MQRFH2 message. i.e. JMS message ==> MQRFH2 message but the opposite may not be true.
Hence, if you want a JMS message with named properties then you need to uncomment those 3 lines in MQTest11P.java above.
i.e.
sendmsg.setStringProperty("mcd.Msd", "jms_text");
sendmsg.setStringProperty("jms.Dst", "queue:///"+outputQName);
sendmsg.setStringProperty("jms.Pri", "0");

Related

How to display local queues where curdepth reached its maxdepth in ibm mq

I want to display all local queues where curdepth reached its maxdepth.
I understand that the below where condition in runmqsc will not work.
DIS QL(*) WHERE(CURDEPTH EQ MAXDEPTH)
I am trying to parse it with sed and awk but not even close as I am no expert in scripting
Please help in getting desired output. Thanks
Isn't this like trying to squeeze a fully blown up balloon into a wine bottle?
It would seem far, far simpler to just run a Java/MQ/PCF application to get both the current and maximum depths and compare the values.
Here is a simple (complete) Java/MQ/PCF application to do that:
Note: It has a filter on the PCF command to only return queues with a current depth greater than zero. Hence, the queue manager's command server will return less data and make over all processing faster.
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import com.ibm.mq.MQException;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.CMQC;
import com.ibm.mq.constants.CMQCFC;
import com.ibm.mq.headers.MQDataException;
import com.ibm.mq.headers.pcf.PCFMessage;
import com.ibm.mq.headers.pcf.PCFMessageAgent;
/**
* Program Name
* MQCurrentDepthMonitor01
*
* Description
* This java class issues a PCF "inquire queue" request message for all ("*") local queues
* with a queue depth greater than 0 (zero) of a remote queue manager and
* (1) output an error message if current depth is the same as max depth or
* (2) output a warning message if current depth is within 90% of max depth.
*
* Sample Command Line Parameters
* -m MQA1 -h 127.0.0.1 -p 1414 -c TEST.CHL -u UserID -x Password
*
* #author Roger Lacroix
*/
public class MQCurrentDepthMonitor01
{
private static final SimpleDateFormat LOGGER_TIMESTAMP = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
private Hashtable<String,String> params;
private Hashtable<String,Object> mqht;
private String qMgrName;
public MQCurrentDepthMonitor01()
{
super();
params = new Hashtable<String,String>();
mqht = new Hashtable<String,Object>();
}
/**
* Make sure the required parameters are present.
* #return true/false
*/
private boolean allParamsPresent()
{
boolean b = params.containsKey("-h") && params.containsKey("-p") &&
params.containsKey("-c") && params.containsKey("-m") &&
params.containsKey("-u") && params.containsKey("-x");
if (b)
{
try
{
Integer.parseInt((String) params.get("-p"));
}
catch (NumberFormatException e)
{
b = false;
}
}
return b;
}
/**
* Extract the command-line parameters and initialize the MQ HashTable.
* #param args
* #throws IllegalArgumentException
*/
private void init(String[] args) throws IllegalArgumentException
{
int port = 1414;
if (args.length > 0 && (args.length % 2) == 0)
{
for (int i = 0; i < args.length; i += 2)
{
params.put(args[i], args[i + 1]);
}
}
else
{
throw new IllegalArgumentException();
}
if (allParamsPresent())
{
qMgrName = (String) params.get("-m");
try
{
port = Integer.parseInt((String) params.get("-p"));
}
catch (NumberFormatException e)
{
port = 1414;
}
mqht.put(CMQC.CHANNEL_PROPERTY, params.get("-c"));
mqht.put(CMQC.HOST_NAME_PROPERTY, params.get("-h"));
mqht.put(CMQC.PORT_PROPERTY, new Integer(port));
mqht.put(CMQC.USER_ID_PROPERTY, params.get("-u"));
mqht.put(CMQC.PASSWORD_PROPERTY, params.get("-x"));
// I don't want to see MQ exceptions at the console.
MQException.log = null;
}
else
{
throw new IllegalArgumentException();
}
}
/**
* Handle connecting to the queue manager, issuing PCF command then
* looping through PCF response messages and disconnecting from
* the queue manager.
*/
private void doPCF()
{
MQQueueManager qMgr = null;
PCFMessageAgent agent = null;
PCFMessage request = null;
PCFMessage[] responses = null;
try
{
qMgr = new MQQueueManager(qMgrName, mqht);
MQCurrentDepthMonitor01.logger("successfully connected to "+ qMgrName);
agent = new PCFMessageAgent(qMgr);
MQCurrentDepthMonitor01.logger("successfully created agent");
// https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_9.1.0/com.ibm.mq.ref.adm.doc/q087800_.htm
request = new PCFMessage(CMQCFC.MQCMD_INQUIRE_Q);
/**
* You can explicitly set a queue name like "TEST.Q1" or
* use a wild card like "TEST.*"
*/
request.addParameter(CMQC.MQCA_Q_NAME, "*");
// Add parameter to request only local queues
request.addParameter(CMQC.MQIA_Q_TYPE, CMQC.MQQT_LOCAL);
// Add parameter to request only queue name, current depth and max depth
request.addParameter(CMQCFC.MQIACF_Q_ATTRS, new int [] {
CMQC.MQCA_Q_NAME,
CMQC.MQIA_CURRENT_Q_DEPTH,
CMQC.MQIA_MAX_Q_DEPTH
});
// Add filter to only return responses with a queue depth greater than 0 (zero)
// i.e. non-zero queue depth
request.addFilterParameter(CMQC.MQIA_CURRENT_Q_DEPTH, CMQCFC.MQCFOP_GREATER, 0);
responses = agent.send(request);
// MQCurrentDepthMonitor01.logger("responses.length="+responses.length);
int curDepth = -1;
int maxDepth = -1;
for (int i = 0; i < responses.length; i++)
{
if ( ((responses[i]).getCompCode() == CMQC.MQCC_OK) &&
((responses[i]).getParameterValue(CMQC.MQCA_Q_NAME) != null) )
{
String name = responses[i].getStringParameterValue(CMQC.MQCA_Q_NAME);
if (name != null)
name = name.trim();
curDepth = responses[i].getIntParameterValue(CMQC.MQIA_CURRENT_Q_DEPTH);
maxDepth = responses[i].getIntParameterValue(CMQC.MQIA_MAX_Q_DEPTH);
// MQCurrentDepthMonitor01.logger("Name="+name + " : curDepth="+curDepth + " : maxDepth="+maxDepth);
if (curDepth == maxDepth)
MQCurrentDepthMonitor01.logger("ERROR: Name="+name + " : current depth equals max depth ["+maxDepth+"]");
else if (curDepth >= (maxDepth * 0.9))
MQCurrentDepthMonitor01.logger("Warning: Name="+name + " : current depth ["+curDepth+"] is within 90% of max depth ["+maxDepth+"]");
}
}
}
catch (MQException e)
{
MQCurrentDepthMonitor01.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
catch (IOException e)
{
MQCurrentDepthMonitor01.logger("IOException:" +e.getLocalizedMessage());
}
catch (MQDataException e)
{
MQCurrentDepthMonitor01.logger("MQDataException:" +e.getLocalizedMessage());
}
finally
{
try
{
if (agent != null)
{
agent.disconnect();
MQCurrentDepthMonitor01.logger("disconnected from agent");
}
}
catch (MQDataException e)
{
MQCurrentDepthMonitor01.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
try
{
if (qMgr != null)
{
qMgr.disconnect();
MQCurrentDepthMonitor01.logger("disconnected from "+ qMgrName);
}
}
catch (MQException e)
{
MQCurrentDepthMonitor01.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
}
}
/**
* A simple logger method
* #param data
*/
public static void logger(String data)
{
String className = Thread.currentThread().getStackTrace()[2].getClassName();
// Remove the package info.
if ( (className != null) && (className.lastIndexOf('.') != -1) )
className = className.substring(className.lastIndexOf('.')+1);
System.out.println(LOGGER_TIMESTAMP.format(new Date())+" "+className+": "+Thread.currentThread().getStackTrace()[2].getMethodName()+": "+data);
}
public static void main(String[] args)
{
MQCurrentDepthMonitor01 mqlqs = new MQCurrentDepthMonitor01();
try
{
mqlqs.init(args);
mqlqs.doPCF();
}
catch (IllegalArgumentException e)
{
MQCurrentDepthMonitor01.logger("Usage: java MQCurrentDepthMonitor01 -m QueueManagerName -h host -p port -c channel -u UserID -x Password");
System.exit(1);
}
System.exit(0);
}
}

JPOS testing (Functional and Perf ) using Apache Jmeter

I want to perform functional test of JPOS based ISO message and response(TPS) using Jmeter.Can anyone guide me on this?Do I need to install any plugin in Jmeter.As I have tried to install the Jmeter in my system.But Can't see any Jpos plugin in listeners to start with.Dev is Using Socket connection in Jpos.
I don't think you will be able to find any plugin, however you should be able to use jPOS client library from the JSR223 Sampler
Download the jPOS and build it using Gradle
Copy jpos/build/libs/jpos-x.x.x.jar to JMeter Classpath (along with dependencies, if you don't have them yet)
Restart JMeter to pick the library up
Add JSR223 Sampler to your Test Plan and put the code, implementing your test scenario into "Script" area, an example would be something like:
import org.jpos.iso.ISOMsg
import org.jpos.iso.channel.ASCIIChannel
import org.jpos.iso.packager.ISO87APackager
def host = 'your_host'
def port = 1234
def channel = new ASCIIChannel(host, port, new ISO87APackager())
channel.connect()
def message = new ISOMsg()
message.setMTI("0800")
message.set(3, "000000")
message.set(41, "00000001")
message.set(70, "301")
channel.send(message)
ISOMsg response = channel.receive()
channel.disconnect()
More information:
jPOS Programmer’s Guide
Apache Groovy - Why and How You Should Use It
We can send a XML or rawMessage to jpos server from the Jmeter TCPSampler
You can also add TPS listeners
enter image description here
And JPosTCPClient can be implemented
public class JPosTCPClient extends TCPClientImpl {
private static final Logger log = LoggingManager.getLoggerForClass();
private String containsString = "</isomsg>";
private boolean filterEnabled = true;
public JPosTCPClient() {
filterEnabled = Boolean.parseBoolean(JMeterUtils.getPropDefault("jpos.tcp.use", "true"));
containsString = JMeterUtils.getPropDefault("jpos.tcp.contains", "</isomsg>");
}
/**
* Reads data until the defined EOL byte is reached.
* If there is no EOL byte defined, then reads until
* the end of the stream is reached.
*/
#Override
public String read(InputStream is) {
byte[] buffer = new byte[4096];
ByteArrayOutputStream w = new ByteArrayOutputStream();
int x = 0;
boolean contains = false;
try {
while ((x = is.read(buffer)) > -1) {
w.write(buffer, 0, x);
if(filterEnabled){
String response = new String(buffer);
if(response.contains(containsString)){
contains = true;
break;
} else {
System.out.println("Contents: " + response);
}
}
}
if(filterEnabled && !contains){
System.out.println("Skipped containsString checking, x length:" + x);
}
} catch (SocketTimeoutException e) {
// drop out to handle buffer
System.out.println(e.getMessage());
} catch (InterruptedIOException e) {
// drop out to handle buffer
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
log.warn("Read error:" + e);
return "";
}
// do we need to close byte array (or flush it?)
log.debug("Read: " + w.size() + "\n" + w.toString());
return w.toString();
}
}

Sending message on IBM MQ: Hangs on AccessQueue

We're trying to send a message on an IBM MQ Message Queue.
We can contact the Queue Manager, but as soon as we call the MQMessage constructor, the process hangs. We suspect that this is actually because whatever AccessQueue is doing is failing.
using (MQQueueManager qMgr = new MQQueueManager(queueManagerName, connectionProperties))
{
// Set up the options on the queue we want to open
int openOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;
// Now specify the queue that we want to open,and the open options
MQQueue system_default_local_queue =
qMgr.AccessQueue(sendQueueName, openOptions); // we suspect this is actually where things are wrong
// Define a WebSphere MQ message, writing some text in UTF format
MQMessage mqMessage = new MQMessage(); // ** THIS HANGS
mqMessage.WriteUTF(text);
// Specify the message options
MQPutMessageOptions pmo = new MQPutMessageOptions(); // accept the defaults,
// same as MQPMO_DEFAULT
// Put the message on the queue
system_default_local_queue.Put(mqMessage, pmo);
system_default_local_queue.Close();
// Disconnect from the queue manager
qMgr.Disconnect();
}
Is there an option we're not including or something we're missing?
We're using the the NuGet package WebSphereMqClient v8.0.0.7.
Update:
I'll include our connection properties for completeness based on feedback.
Hashtable connectionProperties = new Hashtable();
connectionProperties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
connectionProperties.Add(MQC.USE_MQCSP_AUTHENTICATION_PROPERTY, true);
// Set up the rest of the connection properties, based on the
// connection type requested
// this is all for MQC.TRANSPORT_MQSERIES_MANAGED
connectionProperties.Add(MQC.HOST_NAME_PROPERTY, "myserver.com");
connectionProperties.Add(MQC.CHANNEL_PROPERTY, "MY.CHANNEL");
connectionProperties.Add(MQC.PORT_PROPERTY, 3223);
connectionProperties.Add(MQC.CONNECT_OPTIONS_PROPERTY, MQC.MQCNO_RECONNECT_Q_MGR);
In answer to a question from Roger, this is a Managed Queue.
You don't show us your connection properties, so I don't know if you set everything correctly. Did you make sure you set 'managed mode'? Also, why aren't you doing any print-outs of what the code has completed?
Here is a complete and working C# .NET/MQ program that uses 'managed mode' connection.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using IBM.WMQ;
/// <summary> Program Name
/// MQTest51
///
/// Description
/// This C# class will connect to a remote queue manager
/// and put a message to a queue under a managed .NET environment.
///
/// Sample Command Line Parameters
/// -h 127.0.0.1 -p 1414 -c TEST.CHL -m MQWT1 -q TEST.Q1
///
/// </summary>
namespace MQTest51
{
class MQTest51
{
private Hashtable inParms = null;
private Hashtable qMgrProp = null;
private System.String qManager;
private System.String outputQName;
/*
* The constructor
*/
public MQTest51()
: base()
{
}
/// <summary> Make sure the required parameters are present.</summary>
/// <returns> true/false
/// </returns>
private bool allParamsPresent()
{
bool b = inParms.ContainsKey("-h") && inParms.ContainsKey("-p") &&
inParms.ContainsKey("-c") && inParms.ContainsKey("-m") &&
inParms.ContainsKey("-q");
if (b)
{
try
{
System.Int32.Parse((System.String)inParms["-p"]);
}
catch (System.FormatException e)
{
b = false;
}
}
return b;
}
/// <summary> Extract the command-line parameters and initialize the MQ variables.</summary>
/// <param name="args">
/// </param>
/// <throws> IllegalArgumentException </throws>
private void init(System.String[] args)
{
inParms = Hashtable.Synchronized(new Hashtable());
if (args.Length > 0 && (args.Length % 2) == 0)
{
for (int i = 0; i < args.Length; i += 2)
{
inParms[args[i]] = args[i + 1];
}
}
else
{
throw new System.ArgumentException();
}
if (allParamsPresent())
{
qManager = ((System.String)inParms["-m"]);
outputQName = ((System.String)inParms["-q"]);
qMgrProp = new Hashtable();
qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ((System.String)inParms["-h"]));
qMgrProp.Add(MQC.CHANNEL_PROPERTY, ((System.String)inParms["-c"]));
try
{
qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse((System.String)inParms["-p"]));
}
catch (System.FormatException e)
{
qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
}
if (inParms.ContainsKey("-u"))
qMgrProp.Add(MQC.USER_ID_PROPERTY, ((System.String)inParms["-u"]));
if (inParms.ContainsKey("-x"))
qMgrProp.Add(MQC.PASSWORD_PROPERTY, ((System.String)inParms["-x"]));
if ( (inParms.ContainsKey("-u")) && (inParms.ContainsKey("-x")) )
qMgrProp.Add(MQC.USE_MQCSP_AUTHENTICATION_PROPERTY, true);
}
else
{
throw new System.ArgumentException();
}
}
/// <summary> Connect, open queue, write a message, close queue and disconnect.
///
/// </summary>
/// <throws> MQException </throws>
private void testSend()
{
MQQueueManager qMgr = null;
MQQueue outQ = null;
System.String line = "This is a test message embedded in the MQTest51 program.";
int openOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;
MQPutMessageOptions pmo = new MQPutMessageOptions();
try
{
qMgr = new MQQueueManager(qManager, qMgrProp);
System.Console.Out.WriteLine("MQTest51 successfully connected to " + qManager);
outQ = qMgr.AccessQueue(outputQName, openOptions);
System.Console.Out.WriteLine("MQTest51 successfully opened " + outputQName);
// Define a simple MQ message, and write some text in UTF format..
MQMessage sendmsg = new MQMessage();
sendmsg.Format = MQC.MQFMT_STRING;
sendmsg.MessageType = MQC.MQMT_DATAGRAM;
sendmsg.MessageId = MQC.MQMI_NONE;
sendmsg.CorrelationId = MQC.MQCI_NONE;
sendmsg.WriteString(line);
// put the message on the outQ
outQ.Put(sendmsg, pmo);
System.Console.Out.WriteLine("Message Data>>>" + line);
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest51 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
catch (System.IO.IOException ioex)
{
System.Console.Out.WriteLine("MQTest51 ioex=" + ioex);
}
finally
{
try
{
if (outQ != null)
{
outQ.Close();
System.Console.Out.WriteLine("MQTest51 closed: " + outputQName);
}
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest51 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
try
{
if (qMgr != null)
{
qMgr.Disconnect();
System.Console.Out.WriteLine("MQTest51 disconnected from " + qManager);
}
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest51 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
}
}
/// <summary> main line</summary>
/// <param name="args">
/// </param>
// [STAThread]
public static void Main(System.String[] args)
{
MQTest51 write = new MQTest51();
try
{
write.init(args);
write.testSend();
}
catch (System.ArgumentException e)
{
System.Console.Out.WriteLine("Usage: MQTest51 -h host -p port -c channel -m QueueManagerName -q QueueName [-u userID] [-x passwd]");
System.Environment.Exit(1);
}
catch (MQException e)
{
System.Console.Out.WriteLine(e);
System.Environment.Exit(1);
}
System.Environment.Exit(0);
}
}
}

Sms not receiving from java web application

I have written java code which is used to send sms using sms gateway. JAVA OpenSMPP API is used to implement the logic for sending SMPP request. I have needed below information which is used to connect to the sms gateway and which is used to send sms :
SMS_GATEWAY_USERNAME 906o2portt02
SMS_GATEWAY_PORT 9205 S
SMS_GATEWAY_IP_2 34.22.91.166
SMS_GATEWAY_IP_1 80.77.67.145
I am able to send sms but i dont understand for what reason i am not receiving sms. I have also put the debug statement in my code to check for any error. When i checked the log file i am getting below information which says sms has been send. Previously I had different port number,username and password and i was able to send and recieve sms using the same java code. But now i have the requirement to send sms on this gateway and its also sending an sms. but for some reason i am not receiving sms. Is there any way to check what happened to my sms which has been send ?
Below is my code :
public class SMSClient
{
private static final Logger logger = LoggerFactory
.getLogger(SMSClient.class);
#Autowired
private SMSSettings smsSettings;
#Autowired
private OracleSettings oracleSettings;
/**
* If the application is bound to the SMSC.
*/
boolean _bound = false;
public boolean send(String text,
List<AlertCommunicationAddress> toAddressesSMS)
{
List<String> toAddressesSMSString = new ArrayList<String>();
for (AlertCommunicationAddress alertComAddr : toAddressesSMS)
{
List<AlertRecpGrpMember> recpMembers = alertComAddr
.getAlertRecipientsGroup().getAlertRecpGrpMembers();
for (AlertRecpGrpMember recpMem : recpMembers)
{
// check here if the member belongs to the same environment on
// which SMS is being sent.
if ((recpMem.getIsDefault() != null && recpMem.getIsDefault()
.equalsIgnoreCase("Y"))
|| (recpMem.getRunEnvironment() != null && recpMem
.getRunEnvironment().equalsIgnoreCase(
oracleSettings.getRunEnv())))
{
toAddressesSMSString.add(recpMem.getMember());
}
}
}
logger.debug("Original SMS to be sent : " + text);
String smscHost1 = smsSettings.getHost1();
Integer smscPort = smsSettings.getPort();
if (toAddressesSMSString.isEmpty())
{
return false;
}
for (String phoneNumber : toAddressesSMSString)
{
try
{
Session session = getSession(smscHost1, smscPort,
smsSettings.getUsername(), smsSettings.getPassword());
if (session == null)
{
String smscHost2 = smsSettings.getHost2();
logger.error("SMS --- Unable to get the session with Host 1 (" + smscHost1 + ":" + smscPort + ") , will try Host 2 (" + smscHost2 + ") now.");
session = getSession(smscHost2, smscPort,
smsSettings.getUsername(),
smsSettings.getPassword());
if (session == null)
{
logger.error("SMS --- Unable to get the session with Host 1 (" + smscHost1 + ") and Host 2 (" + smscHost2 + "). Please check with the SMS Gateway.");
return false;
}
}
logger.debug("SMS --- Created Session object " + session);
SubmitSM request = new SubmitSM();
request.setSourceAddr(new Address((byte) 5, (byte) 0,
"RM2Support"));
request.setDestAddr(createAddress(phoneNumber));
request.setProtocolId((byte) 0);
request.setPriorityFlag((byte) 0);
request.setRegisteredDelivery((byte) 1); // we want delivery
// reports
request.setDataCoding((byte) 0);
request.setSmDefaultMsgId((byte) 0);
// request.setScheduleDeliveryTime(deliveryTime); // you can
// skip
// this
request.setReplaceIfPresentFlag((byte) 0);
// Send the request
request.assignSequenceNumber(true);
// this is to send long messages
request.setEsmClass((byte) Data.SM_UDH_GSM);
String[] splittedMsg = splitMessage(text, 153);
int totalSegments = splittedMsg.length;
logger.debug("SMS : Number of splitted segments :: "
+ totalSegments);
// iterating on splittedMsg array. Only Sequence Number and
// short
// message text will change each time
Random random = new Random();
int randomInt = random.nextInt();
logger.debug("SMS---- Reference Number : " + randomInt);
for (int i = 0; i < totalSegments; i++)
{
ByteBuffer ed = new ByteBuffer();
ed.appendByte((byte) 5); // UDH Length
ed.appendByte((byte) 0x00); // IE Identifier
ed.appendByte((byte) 3); // IE Data Length
ed.appendByte((byte) randomInt); // Reference Number
ed.appendByte((byte) totalSegments); // Number of pieces
ed.appendByte((byte) (i + 1)); // Sequence number
ed.appendString(splittedMsg[i], Data.ENC_ASCII);
request.setShortMessageData(ed);
logger.debug("Hello...reached here...now about the submit the request::::");
SubmitSMResp response = session.submit(request);
logger.debug("SMS --- Submit response "
+ response.getCommandStatus());
// response = smsSession.submitMulti(request);
logger.debug("SMS --- Submit response "
+ response.getCommandStatus());
String messageId = response.getMessageId();
logger.debug("SMS --- Message ID = " + messageId);
}
enquireLink(session);
unbind(session);
} catch (Exception e)
{
logger.debug("Exception while sending SMS with Phone number :::" + phoneNumber + "::::" + e);
continue;
}
}
return true;
}
private Session getSession(String smscHost, int smscPort,
String smscUsername, String smscPassword) throws Exception
{
try
{
TCPIPConnection connection = new TCPIPConnection(smscHost, smscPort);
connection.setReceiveTimeout(6000);
connection.setIOBufferSize(8188);
connection.setReceiveBufferSize(8188);
Session session = new Session(connection);
// bind now
if (_bound)
{
logger.debug("Already bound, unbind first.");
return session;
}
BindRequest request = new BindTransmitter();
request.setSystemId(smscUsername);
request.setPassword(smscPassword);
// request.setSystemType(systemType);
// request.setAddressRange(addressRange);
request.setInterfaceVersion((byte) 0x34); // SMPP protocol version
logger.debug("SMS --- Bind request :: " + request.debugString());
logger.debug("SMS --- Created Session object :: " + session);
BindResponse response = session.bind(request);
logger.debug("Bind response " + response.debugString());
if (response.getCommandStatus() == Data.ESME_ROK)
{
logger.debug("SMS --- Binded with SMSC Server");
_bound = true;
} else
{
logger.error("SMS --- Unable to bind with SMSC Server :: Code :: "
+ response.getCommandStatus());
}
Integer respCode = new Integer(response.getCommandStatus());
logger.debug("SMS -- Response Code ::" + respCode);
response.setCommandStatus(respCode);
Integer comLength = new Integer(response.getCommandLength());
logger.debug("SMS -- CommandLength ::" + comLength);
response.setCommandLength(comLength);
logger.debug("SMS --- Response from SMSC" + response.toString());
return session;
} catch (WrongLengthOfStringException e)
{
logger.error("SMS -- Wrong length string exception"
+ e.getMessage());
} catch (ValueNotSetException e)
{
logger.error("SMS -- Value not set exception" + e.getMessage());
} catch (TimeoutException e)
{
logger.error("SMS -- Timeout exception " + e.getMessage());
} catch (PDUException e)
{
logger.error("SMS -- PDU exception " + e.getMessage());
} catch (WrongSessionStateException e)
{
logger.error("SMS -- Wrong Session exception " + e.getMessage());
} catch (IOException e)
{
logger.error("SMS --- Could not able to connect the host/port or Check the Username/Password for connection ::"
+ e.getMessage());
} catch (Exception e)
{
logger.error("SMS -- Error while sending SMS :: " + e.getMessage());
}
return null;
}
private Address createAddress(String address)
throws WrongLengthOfStringException
{
Address addressInst = new Address();
addressInst.setTon((byte) 5); // national ton
addressInst.setNpi((byte) 0); // numeric plan indicator
addressInst.setAddress(address, Data.SM_ADDR_LEN);
logger.debug("SMS -------- Address :: " + addressInst);
return addressInst;
}
private Session unbind(Session session)
{
try
{
if (!_bound)
{
System.out.println("Not bound, cannot unbind.");
return session;
}
// send the request
logger.debug("Going to unbind.");
if (session.getReceiver().isReceiver())
{
logger.debug("SMS --- Unbinding --- It can take a while to stop the receiver.");
}
UnbindResp response = session.unbind();
logger.debug("Unbind response " + response.debugString());
_bound = false;
} catch (Exception e)
{
logger.debug("Unbind operation failed. " + e);
}
return session;
}
/**
* Creates a new instance of <code>EnquireSM</code> class. This PDU is used
* to check that application level of the other party is alive. It can be
* sent both by SMSC and ESME.
*
* See "SMPP Protocol Specification 3.4, 4.11 ENQUIRE_LINK Operation."
*
* #see Session#enquireLink(EnquireLink)
* #see EnquireLink
* #see EnquireLinkResp
*/
private void enquireLink(Session session)
{
try
{
EnquireLink request = new EnquireLink();
EnquireLinkResp response;
logger.debug("SMS ---- Enquire Link request "
+ request.debugString());
response = session.enquireLink(request);
logger.debug("SMS --- Enquire Link response "
+ response.debugString());
} catch (Exception e)
{
logger.debug("SMS ---- Enquire Link operation failed :: " + e);
}
}
private String[] splitMessage(String s, int size)
{
if (s == null || size <= 0)
return null;
int chunks = s.length() / size + ((s.length() % size > 0) ? 1 : 0);
String[] arr = new String[chunks];
for (int i = 0, j = 0, l = s.length(); i < l; i += size, j++)
arr[j] = s.substring(i, Math.min(l, i + size));
return arr;
}
}
Below is the parameter i need to consider while send/receive sms. But i really dont know whetherJAVA OpenSMPP APIuses this settings:
You can use the following code to query SMPP server to check what happend to you message (from https://github.com/OpenSmpp/opensmpp/blob/master/client/src/main/java/org/smpp/test/SMPPTest.java):
/**
* Creates a new instance of <code>QuerySM</code> class, lets you set
* subset of fields of it. This PDU is used to fetch information
* about status of already submitted message providing that you 'remember'
* message id of the submitted message. The message id is assigned
* by SMSC and is returned to you with the response to the submision
* PDU (SubmitSM, DataSM etc.).
*
* See "SMPP Protocol Specification 3.4, 4.8 QUERY_SM Operation."
* #see Session#query(QuerySM)
* #see QuerySM
* #see QuerySMResp
*/
private void query() {
debug.enter(this, "SMPPTest.query()");
try {
QuerySM request = new QuerySM();
QuerySMResp response;
// input values
messageId = getParam("Message id", messageId);
sourceAddress = getAddress("Source", sourceAddress);
// set values
request.setMessageId(messageId);
request.setSourceAddr(sourceAddress);
// send the request
System.out.println("Query request " + request.debugString());
if (asynchronous) {
session.query(request);
} else {
response = session.query(request);
System.out.println("Query response " + response.debugString());
messageId = response.getMessageId();
}
} catch (Exception e) {
event.write(e, "");
debug.write("Query operation failed. " + e);
System.out.println("Query operation failed. " + e);
} finally {
debug.exit(this);
}
}

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException on click on JButton to Create Database

I am new to java and JDBC usage. I am writing my first java application that connects to database. But i am getting this error when i click on th JButton that performs database creation. But i get this error:
$run:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at data.eceunnrecords.com.DBOptions.executeNonQuery(DBOptions.java:70)
at portal.eceunnrecords.com.CreateDatabase.createButtonActionPerformed(CreateDatabase.java:81)
at portal.eceunnrecords.com.CreateDatabase.access$000(CreateDatabase.java:13)
at portal.eceunnrecords.com.CreateDatabase$1.actionPerformed(CreateDatabase.java:42)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
here is my code:
$/** To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package portal.eceunnrecords.com;
import portal.eceunnrecords.com.*;
import data.eceunnrecords.com.*;
/**
*
* #author OPTHINKERS
*/
public class CreateDatabase extends javax.swing.JFrame {
/**
* Creates new form CreateDatabase
*/
public CreateDatabase() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
createdbtf = new javax.swing.JTextField();
createButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Database Name:");
createButton.setText("Create");
createButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(78, 78, 78)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(createButton)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(createdbtf, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(144, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(110, 110, 110)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(createdbtf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(createButton)
.addContainerGap(129, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String query = "Create Table "+this.createdbtf.getText()+"(REG_NO VARCHAR (10)"
+ "NOT NULL PRIMARY KEY, SURNAME VARCHAR (45) NOT NULL, FIRSTNAME VARCHAR (45) "
+ "NOT NULL, MIDDLENAME VARCHAR (45) NOT NULL, LEVEL INT NOT NULL, STATE_OF_ORIGIN "
+ "VARCHAR (25) NOT NULL, PHONE_NO INT NOT NULL, EMAIL VARCHAR (50) NOT NULL);";
DBOptions.executeNonQuery(query);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CreateDatabase().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton createButton;
private javax.swing.JTextField createdbtf;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
And here is the class DBOptions that communicates with my database:
$package data.eceunnrecords.com;
import java.sql.*;
import javax.swing.*;
public class DBOptions {
/**
* static variable con is used to hold the active connection information.
*/
public static Connection con = null;
/**
*This method is used to make a connection with the database
* #param strHost holds host name or ip address
* #param iPort holds port number
* #param strDBName holds the database name
* #param strUserName holds username to connect to server
* #param strPassword holds password to connect to server
* #return true for establishing connection and false for failure.
*/
public static boolean connect(String strHost, int iPort,String strDBName, String strUserName, String strPassword)
{
try
{
//loading mysql jdbc driver
Class.forName("com.mysql.jdbc.Driver");
//connection string
String url="jdbc:mysql://"+strHost+":"+iPort+"/"+strDBName;
//establishing connection
con=DriverManager.getConnection(url, strUserName,strPassword);
return true; //successfully connected
}
catch(Exception e)
{
return false; //connection failed
}
}
/**
* This method is used to close the database connection
* #param dbCon holds the active connection information
*/
public static void closeConnection(Connection dbCon)
{
try
{
dbCon.close(); //close connection
}
catch(Exception e)
{
}
}
/**
* This method is used to execute an sql non query
* #param sqlString holds the sql non query to be executed
* #return the number of rows affected
*/
public static int executeNonQuery(String sqlString)
{
try
{
Statement stmt = con.createStatement();
return stmt.executeUpdate(sqlString);
//return the number of rows affected
}
catch(SQLException e)
{
//display error message
//JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Non Query Execution Failure", 1);
return -1;
}
}
/**
* This method is used to execute an sql query
* #param sqlQuery holds the sql query
* #return the ResultSet if successful. Return null on failure
*/
public static ResultSet executeSQLQuery(String sqlQuery)
{
try
{
Statement stmt = con.createStatement();
return stmt.executeQuery(sqlQuery); //query successfully executed
}
catch(SQLException e)
{
//display error message
//JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Query Execution Failure", 1);
return null; //sql query execution failed
}
}
}
please help me...
It seems that the line that is throwing the NullPointerException is this line:
Statement stmt = con.createStatement();
If this is throwing a NullPointerException, then your static variable con must be null.
I can't see anywhere where you are creating your database connection function connect(). As far as I can see, you're getting the error because you're trying to create a table in a database when you're not connected to the database.
Alternatively, perhaps you are calling connect() in some code you've chosen not to share with us. In which case, I'd guess that you are failing to connect to the database. However, the following code within your connect() method is extremely unhelpful when it comes to finding out what went wrong:
catch(Exception e)
{
return false; //connection failed
}
There are numerous different reasons why your database connection might be failing, but silently swallowing all exceptions makes it incredibly difficult to find out what is going wrong. Add a line e.printStackTrace(); to this catch block (before the return line) and that will print out the exception that is causing the database connection to fail.

Resources