JMS-Loadtest using Gatling: unable to initialize ContextFactory of IBM MQ - ibm-mq

I'm implementing a load test scenario against a IBM MQ with Gatling.
The setup is basically the same as mentioned here
Problem: I'm not able to initialize the required ContextFactory with IBM MQ - which should be com.ibm.mq.jms.context.WMQInitialContextFactory.
The WMQInitialContextFactory cannot be found.
But my build.sbt is containing the IBM MQ dependency correctly (being successfully retrieved by our internal Nexus :
"com.ibm.mq" % "com.ibm.mq" % "8.0.0.3"
My gatling scenario:
package com.myawesomecompany.loadtest
import com.ibm.mq._
import com.ibm.mq.jms.MQConnectionFactory
import com.ibm.mq.jms.JMSMQ_Messages
import com.ibm.msg.client.wmq.common.CommonConstants
import io.gatling.core.Predef._
import io.gatling.core.scenario.Simulation
import io.gatling.jms.Predef._
import javax.jms._
import scala.concurrent.duration._
class JMSLoadTest extends Simulation {
val jmsConfiguration = jms
.connectionFactoryName("ConnectionFactory")
.url("devmq01.company.dmz")
.credentials("mqm", "mqm")
.contextFactory(classOf[com.ibm.mq.jms.context.WMQInitialContrextFactory].getName)
.listenerCount(1)
.usePersistentDeliveryMode
val scn = scenario("Load testing GPRSForwarder").repeat(1) {
exec(jms("testing GPRSForwarder...").reqreply
.queue("COMPANY.TEST.QUEUE")
.textMessage("00001404020611100E033102C20EBB51CC1C036EFFFF00010002323802000200FE05001400000000FFFFFFFFFFFFFFFFFF040010038B0D6912EB10CE070206110F37298C")
.jmsType("test_jms_type")
)
}
setUp(scn.inject(rampUsersPerSec(10) to 1000 during (2 minutes)))
.protocols(jmsConfiguration)
}
The setup is equivalent to this one - but instead of using ActiveMQInitalContextFactory, I'm forced to use the "counterpart" of IBM MQ.
According to official docks the WMQInitialContextFactory should be in com.ibm.mq.jms.context but it is not. Ore is there some constant in CommonConstants which I can use to initialize a ContextFactory ?
Thanks a lot in advance.

Problem: I'm not able to initialize the required ContextFactory with
IBM MQ - which should be
com.ibm.mq.jms.context.WMQInitialContextFactory. The
WMQInitialContextFactory cannot be found.
Do not use WMQInitialContextFactory. It was an MQ SupportPac someone created where they wanted to use MQ as the JNDI repository. It is not a good idea plus the SupportPac does not support any form of security (i.e. SSL/TLS or security exit).
You should use a file based MQ JNDI. Here's a basic example:
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.ibm.mq.MQException;
/**
* Program Name
* TestJMS01
*
* Description
* This java JMS class will connect to a remote queue manager
* using JNDI and put a message to a queue.
*
* Sample Command Line Parameters
* -x myQCF -q dev.test.q -f C:\JNDI-Directory\roger\mqjndi
*
* Sample MQ JNDI Commands:
* DEFINE QCF(myQCF) QMANAGER(MQA1) CHANNEL(TEST.CHL) HOSTNAME(127.0.0.1) PORT(1415) TRANSPORT(CLIENT) FAILIFQUIESCE(YES)
* DEFINE Q(dev.test.q) QUEUE(TEST1) QMANAGER(MQA1) TARGCLIENT(JMS) FAILIFQUIESCE(YES)
*
* #author Roger Lacroix, Capitalware Inc.
*/
public class TestJMS01
{
private static final String JNDI_CONTEXT = "com.sun.jndi.fscontext.RefFSContextFactory";
private QueueConnectionFactory cf;
private Queue q;
private Hashtable<String,String> params = null;
private String userID = "tester";
private String password = "mypwd";
public TestJMS01() throws NamingException
{
super();
}
/**
* Make sure the required parameters are present.
* #return true/false
*/
private boolean allParamsPresent()
{
return (params.containsKey("-x") && params.containsKey("-q") && params.containsKey("-f"));
}
/**
* Extract the command-line parameters and initialize the MQ variables.
* #param args
* #throws IllegalArgumentException
*/
private void init(String[] args) throws IllegalArgumentException
{
params = new Hashtable<String,String>(10);
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())
{
Hashtable<String,Object> env = new Hashtable<String,Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_CONTEXT);
env.put(Context.PROVIDER_URL, "file:/"+(String) params.get("-f"));
try
{
Context ctx = new InitialContext(env);
cf = (QueueConnectionFactory) ctx.lookup((String) params.get("-x"));
q = (Queue) ctx.lookup((String) params.get("-q"));
}
catch (NamingException e)
{
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
throw new IllegalArgumentException();
}
}
else
{
throw new IllegalArgumentException();
}
}
/**
* Test the connection to the queue manager.
* #throws MQException
*/
private void testConn() throws JMSException
{
QueueConnection connection = null;
QueueSession session = null;
try
{
connection = cf.createQueueConnection(userID, password);
connection.start();
session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
sendMsg(session);
}
catch (JMSException e)
{
System.err.println("getLinkedException()=" + e.getLinkedException());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
}
finally
{
try
{
session.close();
}
catch (Exception ex)
{
System.err.println("session.close() : " + ex.getLocalizedMessage());
}
try
{
connection.stop();
}
catch (Exception ex)
{
System.err.println("connection.stop() : " + ex.getLocalizedMessage());
}
try
{
connection.close();
}
catch (Exception ex)
{
System.err.println("connection.close() : " + ex.getLocalizedMessage());
}
}
}
/**
* Send a message to a queue.
* #throws MQException
*/
private void sendMsg(QueueSession session) throws JMSException
{
QueueSender sender = null;
try
{
TextMessage msg = session.createTextMessage();
msg.setText("Nice simple test. Time in 'ms' is -> " + System.currentTimeMillis());
// msg.setJMSReplyTo(tq);
// msg.setJMSDeliveryMode( DeliveryMode.NON_PERSISTENT);
System.out.println("Sending request to " + q.getQueueName());
System.out.println();
sender = session.createSender(q);
sender.send(msg);
}
catch (JMSException e)
{
System.err.println("getLinkedException()=" + e.getLinkedException());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
}
finally
{
try
{
sender.close();
}
catch (Exception ex)
{
System.err.println("sender.close() : " + ex.getLocalizedMessage());
}
}
}
/**
* main line
* #param args
*/
public static void main(String[] args)
{
try
{
TestJMS01 tj = new TestJMS01();
tj.init(args);
tj.testConn();
}
catch (IllegalArgumentException e)
{
System.err.println("Usage: java TestJMS01 -x QueueConnectionFactoryName -q JMS_Queue_Name -f path_to_MQ_JNDI");
System.exit(1);
}
catch (NamingException ex)
{
System.err.println(ex.getLocalizedMessage());
ex.printStackTrace();
}
catch (JMSException e)
{
System.err.println("getLinkedException()=" + e.getLinkedException());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
}
catch (Exception ex)
{
System.err.println(ex.getLocalizedMessage());
ex.printStackTrace();
}
}
}

Not directly related to your problem, but JMSToolBox with its scripting feature, is a tool that allows to perform bulk/load test on IBM MQ.
With it you can define a script, composed of steps, that will read a template with variable placeholders and repeatedly put messages in one or multiple destinations. It can also directly read saved messages from a directory etc.
You can download it from SourceForge here
Documentation of the script feature is here

Related

IBM MQ JMSWMQ0018: Failed to connect to queue manager 'MY_LOCAL_QM' with connection mode 'Client' and host name 'MY_LOCAL_QM(1401)'

I created a queue manager, queue, channel(Server-connection).
When I try to send a message, see this error:
com.ibm.msg.client.jms.DetailedIllegalStateException: JMSWMQ0018: Failed to connect to queue manager 'MY_LOCAL_QM' with connection mode 'Client' and host name 'epspa(1401)'.
Check the queue manager is started and if running in client mode, check there is a listener running. Please see the linked exception for more information.
Maybe I need to set a user to queue manager? Because I use the same java code, but try to connect to another queue manager, and it works fine. But it doesn't work with my queue manager.
IBM MQ installed on another PC.
private static final String HOST = "epspa";
private static final int PORT = 1401;
private static final String CHANNEL = "API.SVRCONN_LOCAL";
private static final String QMN = "MY_LOCAL_QM";
private static final String QUEUE_NAME = "API.QUEUE_NAME";
private static final String message ="message";
public static String sendMessage(String message) {
String result = "Error";
try {
MQQueueConnectionFactory cf = new MQQueueConnectionFactory();
cf.setHostName(HOST);
cf.setChannel(CHANNEL);
cf.setPort(PORT);
cf.setQueueManager(QMN);
cf.setTransportType(WMQConstants.WMQ_MESSAGE_BODY_MQ);
Destination destination = null;
MessageProducer producer = null;
Connection c = cf.createConnection();
Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = s.createQueue(QUEUE_NAME);
producer = s.createProducer(destination);
TextMessage tmo = s.createTextMessage();
((MQDestination) destination).setMessageBodyStyle
(WMQConstants.WMQ_MESSAGE_BODY_MQ);
tmo.setIntProperty(WMQConstants.JMS_IBM_CHARACTER_SET, 1208);
tmo.setIntProperty(WMQConstants.JMS_IBM_ENCODING,546);
tmo.setText(message);
producer.send(tmo);
result = "Success!";
} catch (JMSException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
cf.setTransportType(WMQConstants.WMQ_MESSAGE_BODY_MQ);
Well, that's not correct. It should be:
cf.setTransportType(WMQConstants.WMQ_CM_CLIENT);
JMSWMQ0018: Failed to connect to queue manager
A JMS error does not give enough details about what MQ is complaining about. You need to output the LinkedException.
catch (JMSException e)
{
if (e != null)
{
System.err.println("getLinkedException()=" + e.getLinkedException());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
}
}
Are you sure that port # of 1401 is correct? The default port # for MQ is 1414. Start runmqsc against your queue manager. i.e.
runmqsc MY_LOCAL_QM
then issue the following command:
DIS LISTENER(LISTENER.TCP)
what value is given for the PORT attribute?
tmo.setIntProperty(WMQConstants.JMS_IBM_CHARACTER_SET, 1208);
tmo.setIntProperty(WMQConstants.JMS_IBM_ENCODING,546);
Why are you setting the CCSID and Encoding? Why don't you let JMS & MQ take care of it?
Here is a fully functioning JMS program that puts a message to a queue:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import javax.jms.*;
import com.ibm.mq.jms.*;
import com.ibm.msg.client.wmq.WMQConstants;
/**
* Program Name
* MQTestJMS11
*
* Description
* This java JMS class will connect to a remote queue manager and put a message to 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 MQTestJMS11
{
private static final SimpleDateFormat LOGGER_TIMESTAMP = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
private Hashtable<String,String> params;
private MQQueueConnectionFactory mqQCF = null;
/**
* The constructor
*/
public MQTestJMS11()
{
super();
params = new Hashtable<String,String>();
}
/**
* 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 variables.
* #param args
* #throws IllegalArgumentException
*/
private void init(String[] args) throws IllegalArgumentException
{
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())
{
try
{
mqQCF = new MQQueueConnectionFactory();
mqQCF.setQueueManager((String) params.get("-m"));
mqQCF.setHostName((String) params.get("-h"));
mqQCF.setChannel((String) params.get("-c"));
mqQCF.setTransportType(WMQConstants.WMQ_CM_CLIENT);
try
{
mqQCF.setPort(Integer.parseInt((String) params.get("-p")));
}
catch (NumberFormatException e)
{
mqQCF.setPort(1414);
}
}
catch (JMSException e)
{
if (e != null)
{
MQTestJMS11.logger("getLinkedException()=" + e.getLinkedException());
MQTestJMS11.logger(e.getLocalizedMessage());
e.printStackTrace();
}
throw new IllegalArgumentException();
}
catch (Exception e)
{
MQTestJMS11.logger(e.getLocalizedMessage());
e.printStackTrace();
throw new IllegalArgumentException();
}
}
else
{
throw new IllegalArgumentException();
}
}
/**
* Test the connection to the queue manager.
* #throws MQException
*/
private void testConn()
{
QueueConnection conn = null;
QueueSession session = null;
Queue myQ = null;
try
{
conn = mqQCF.createQueueConnection((String) params.get("-u"), (String) params.get("-x"));
conn.start();
session = conn.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
MQTestJMS11.logger("successfully connected.");
myQ = session.createQueue((String) params.get("-q"));
MQDestination mqd = (MQDestination) myQ;
mqd.setTargetClient(WMQConstants.WMQ_CLIENT_JMS_COMPLIANT);
// mqd.setTargetClient(WMQConstants.WMQ_CLIENT_NONJMS_MQ);
sendMsg( session, myQ);
}
catch (JMSException e)
{
if (e != null)
{
MQTestJMS11.logger("getLinkedException()=" + e.getLinkedException());
MQTestJMS11.logger(e.getLocalizedMessage());
e.printStackTrace();
}
}
catch (Exception e)
{
MQTestJMS11.logger(e.getLocalizedMessage());
e.printStackTrace();
}
finally
{
try
{
if (session != null)
session.close();
}
catch (Exception ex)
{
MQTestJMS11.logger("session.close() : " + ex.getLocalizedMessage());
}
try
{
if (conn != null)
conn.stop();
}
catch (Exception ex)
{
MQTestJMS11.logger("connection.stop() : " + ex.getLocalizedMessage());
}
try
{
if (conn != null)
conn.close();
}
catch (Exception ex)
{
MQTestJMS11.logger("connection.close() : " + ex.getLocalizedMessage());
}
}
}
/**
* Send a message to a queue.
* #throws MQException
*/
private void sendMsg(QueueSession session, Queue myQ) throws JMSException
{
QueueSender sender = null;
try
{
TextMessage msg = session.createTextMessage();
msg.setText("Nice simple test. Time in 'ms' is -> " + System.currentTimeMillis());
// msg.setJMSReplyTo(tq);
// msg.setJMSDeliveryMode( DeliveryMode.NON_PERSISTENT);
MQTestJMS11.logger("Sending request to " + myQ.getQueueName());
MQTestJMS11.logger("");
sender = session.createSender(myQ);
sender.send(msg);
}
finally
{
try
{
if (sender != null)
sender.close();
}
catch (Exception ex)
{
MQTestJMS11.logger("sender.close() : " + ex.getLocalizedMessage());
}
}
}
/**
* 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);
}
/**
* mainline
* #param args
*/
public static void main(String[] args)
{
MQTestJMS11 write = new MQTestJMS11();
try
{
write.init(args);
write.testConn();
}
catch (IllegalArgumentException e)
{
MQTestJMS11.logger("Usage: java MQTestJMS11 -m QueueManagerName -h host -p port -c channel -q JMS_Queue_Name -u UserID -x Password");
System.exit(1);
}
catch (Exception e)
{
MQTestJMS11.logger(e.getLocalizedMessage());
System.exit(1);
}
System.exit(0);
}
}

Oracle : Send latest insert/update to JMS

I have an insert/update trigger for a Oracle table.
Is there a way to send the details of the affected row(all columns) as a message to JMS?
I can write a Java Program, 'loadjava' that and call from the trigger.
Does this way affect performance?
Is there any native way of achieving this?
There is indeed a native way: use AQ JMS from PL/SQL, see https://docs.oracle.com/database/121/ADQUE/jm_exmpl.htm#ADQUE1600. In short you create an AQ queue with a JMS payload type; then you can post messages with PL/SQL from the trigger. An external Java client can connect to the database and read the messages with JMS.
I don't know how much a call into Java would affect performance, but I try to avoid it. It was a nice idea but it never really caught on, so it remains a fringe case and at least early on there were always issues. PL/SQL on the other hand works.
If you need to send data to another message queue product (tags activemq and mq) you can read the messages in Java and forward them. It adds an extra step, but it is straightforward.
loadjava have many problems and not stable if there is many classes loaded and many business, take a look Calling Java from Oracle, PLSQL causing oracle.aurora.vm.ReadOnlyObjectException
Oracle AQ as i know is not free.
I have implemented the same need after trying many possibilities by creating only 1 class loaded to oracle with loadjava which is called as a procedure by a trigger and have the responsability to call an external java program with all needed parameters and log external process output to a table, as below.
i have encoded text mesage to BASE64 because i used JSON format and some specials caracters can causes problems as a parameters to external java program.
i have used "#*#jms_separator#*#" as a separator in the sent parameter string to parse the content if i need to send many parameters to the external program.
the whole duration of ShellExecutor.shellExec is around 500ms and running since 1 year without any problem.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.concurrent.FutureTask;
import sun.misc.BASE64Encoder;
public class ShellExecutor {
static {
System.setProperty("file.encoding", "UTF-8");
}
private static final String INSERT_LOGS_SQL = "INSERT INTO JMS_LOG (TEXT_LOG) VALUES (?) ";
private static final String DEFAULT_CONNECTION = "jdbc:default:connection:";
public static String SQLshellExec(String command) throws Exception {
long start = System.currentTimeMillis();
StringBuffer result = new StringBuffer();
ShellExecutor worker = new ShellExecutor();
try {
worker.shellExec(command, result);
} finally {
result.append("exe duration : " + (System.currentTimeMillis() - start + "\n"));
Connection dbConnection = null;
PreparedStatement logsStatement = null;
try {
dbConnection = DriverManager.getConnection(DEFAULT_CONNECTION);
logsStatement = dbConnection.prepareStatement(INSERT_LOGS_SQL);
logsStatement.clearParameters();
Clob clob = dbConnection.createClob();
clob.setString(1, result.toString());
logsStatement.setClob(1, clob);
logsStatement.executeUpdate();
} finally {
if (logsStatement != null) {
try {
logsStatement.close();
} catch (Exception e) {
}
}
}
}
return result.substring(result.length() - 3090);
}
public void shellExec(String command, StringBuffer result) throws Exception {
Process process = null;
int exit = -10;
try {
InputStream stdout = null;
String[] params = command.split("#*#jms_separator#*#");
BASE64Encoder benc = new BASE64Encoder();
for (int i = 0; i < params.length; i++) {
if (params[i].contains("{") || params[i].contains("}") || params[i].contains("<")
|| params[i].contains("/>")) {
params[i] = benc.encodeBuffer(params[i].getBytes("UTF-8"));
}
}
result.append("Using separator : " + "#*#jms_separator#*#").append("\n")
.append("Calling : " + Arrays.toString(params)).append("\n");
ProcessBuilder pb = new ProcessBuilder(params);
pb.redirectErrorStream(true);
process = pb.start();
stdout = process.getInputStream();
LogStreamReader lsr = new LogStreamReader(stdout, result);
FutureTask<String> stdoutFuture = new FutureTask<String>(lsr, null);
Thread thread = new Thread(stdoutFuture, "LogStreamReader");
thread.start();
try {
exit = process.waitFor();
} catch (InterruptedException e) {
try {
exit = process.waitFor();
} catch (Exception e1) {
}
}
stdoutFuture.get();
result.append("\n").append("exit code :").append(exit).append("\n");
if (exit != 0) {
throw new RuntimeException(result.toString());
}
} catch (Exception e) {
result.append("\nException(").append(e.toString()).append("):").append(e.getCause()).append("\n\n");
e.printStackTrace(System.err);
throw e;
} finally {
if (process != null) {
process.destroy();
}
}
}
}
class LogStreamReader implements Runnable {
private BufferedReader reader;
private StringBuffer result;
public LogStreamReader(InputStream is, StringBuffer result) {
this.reader = new BufferedReader(new InputStreamReader(is));
this.result = result;
}
public void run() {
try {
String line = null;
while ((line = reader.readLine()) != null) {
result.append(line).append("\n");
}
} catch (Exception e) {
result.append("\nException(").append(e.toString()).append("):").append(e.getCause()).append("\n\n");
e.printStackTrace(System.err);
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
The class of the external Java program packaged as an executable with all needed librairies, a simple JMS sender :
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;
import progress.message.jclient.ConnectionFactory;
import progress.message.jimpl.Connection;
public class JMSSender {
private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
public static void main(String[] args) throws Throwable {
doSend(args[0]);
}
public static void doSend(String text)
throws Throwable {
if (Base64.isBase64(text)) {
text = new String(Base64.decodeBase64(text));
}
String content = "\n\nsending message :" + text;
Connection con = null;
Session session = null;
try {
ConnectionFactory cf = new ConnectionFactory();
session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = session.createTopic(destination) ;
MessageProducer producer = session.createProducer(dest);
con.start();
JSONObject json = new JSONObject();
json.put("content", text);
json.put("date", sdf.format(new Date()));
TextMessage tm = session.createTextMessage(json.toString());
producer.send(tm);
content += " \n\n" + "sent message :" + json.toString();
} catch (Throwable e) {
content += " \n\n" + e.toString() + " \n\n" + Arrays.toString(e.getStackTrace());
if (e.getCause() != null) {
content += " \n\nCause : " + e.getCause().toString() + " \n\n"
+ Arrays.toString(e.getCause().getStackTrace());
}
e.printStackTrace(System.err);
throw e;
} finally {
write("steps on sending message : " + content);
if (session != null) {
try {
session.commit();
session.close();
} catch (Exception e) {
}
session = null;
}
if (con != null) {
try {
con.stop();
con.close();
} catch (Exception e) {
}
}
}
}
private static void write(String log) {
try {
if (System.out != null) {
System.out.println(log);
}
} catch (Exception e2) {
}
}
}

Https authentication in android L using bouncy castle

So since the apache libraries have been deprecated in Android L, I have been trying to implement the ssl authentication with a web sphere server using the UrlConnection api. The code is as follows:
The function calling the web service
SSLContext ctx = SSLContext.getInstance("TLS");
try
{
ctx.init(null, new TrustManager[] { new UDMX509TrustManager(
Constants.UDM_SERVER_SOURCE) }, new SecureRandom());
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
URL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection) url
.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /*
* milliseconds
*/);
urlConnection.setSSLSocketFactory(ctx.getSocketFactory());
if (jsonObject != null)
{
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/json");
DataOutputStream printout = new DataOutputStream(
urlConnection.getOutputStream());
printout.writeBytes(URLEncoder.encode(jsonObject.toString(),
"UTF-8"));
printout.flush();
printout.close();
InputStream in = urlConnection.getInputStream();
Reader reader = null;
reader = new InputStreamReader(in, "UTF-8");
char[] buffer = new char[1000];
reader.read(buffer);
response = new String(buffer);
MLog.v("response is", response);
}/*
* catch (Exception e) { e.printStackTrace(); } }
*/else
{
return response = Constants.NETWORK_UNAVAILABLE;
}
/*
* } catch (Exception e) { e.printStackTrace(); }
*/
And my custom X509 manager is :
public class UDMX509TrustManager implements X509TrustManager
{
/*
* The default X509TrustManager returned by IbmX509. We'll delegate
* decisions to it, and fall back to the logic in this class if the default
* X509TrustManager doesn't trust it.
*/
X509TrustManager pkixTrustManager;
public UDMX509TrustManager(int source) throws Exception
{
// create a "default" JSSE X509TrustManager.
KeyStore ks = KeyStore.getInstance("BKS");
InputStream in = null;
int resId = 0;
if (source == Constants.UDM_SERVER_SOURCE)
{
resId = Constants.SERVER_KEYSTORE_PATH;
} else if (source == Constants.MQTT_SERVER_SOURCE)
{
resId = Constants.MQTT_KEYSTORE_PATH;
}
in = VerizonUdmApplication.getContext().getResources()
.openRawResource(resId);
ks.load(in, Constants.KEYSTORE_PASSWORD.toCharArray());
in.close();
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager tms[] = tmf.getTrustManagers();
/*
* Iterate over the returned trustmanagers, look for an instance of
* X509TrustManager. If found, use that as our "default" trust manager.
*/
for (int i = 0; i < tms.length; i++)
{
if (tms[i] instanceof X509TrustManager)
{
pkixTrustManager = (X509TrustManager) tms[i];
return;
}
}
/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("Couldn't initialize");
}
/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
try
{
pkixTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException excep)
{
// do any special handling here, or rethrow exception.
}
}
/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
try
{
pkixTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep)
{
/*
* Possibly pop up a dialog box asking whether to trust the cert
* chain.
*/
}
}
/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers()
{
return pkixTrustManager.getAcceptedIssuers();
}
}
Now so far I've created two scenarios:
Generating bks with the machine ip as the common name parameter:- The
exception I get in that case is : java.io.ioexception: hostname
"xx.xx.xx.xx" was not verified android
Generating bks with the domain name as the common name parameter:-
The exception I encountered in this case is :
java.net.UnknownHostException: Unable to resolve host "host name": No
address associated with hostname
Also Note- for testing purpose I'm using a tomcat server. Any ideas how I can resolve this and complete authentication with the server with this api?
Any help on the same would be greatly appreciated.

message not being submitted to handset using jsmpp

I am trying to send a message to the handset using the following code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jsmsoutgoing;
import java.io.IOException;
import java.util.Date;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.PDUException;
import org.jsmpp.bean.Alphabet;
import org.jsmpp.bean.BindType;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.GeneralDataCoding;
import org.jsmpp.bean.MessageClass;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.ReplaceIfPresentFlag;
import org.jsmpp.bean.SMSCDeliveryReceipt;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.examples.MessageReceiverListenerImpl;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.session.BindParameter;
import org.jsmpp.session.SMPPSession;
import org.jsmpp.util.AbsoluteTimeFormatter;
import org.jsmpp.util.MessageId;
import org.jsmpp.util.TimeFormatter;
public class Jsmsoutgoing {
/**
* #param args the command line arguments
*/
private static TimeFormatter timeFormatter = new AbsoluteTimeFormatter();
public static void main(String[] args) {
// TODO code application logic here
SMPPSession session = new SMPPSession();
session.setMessageReceiverListener(new MessageReceiverListenerImpl());
String host = "X";
int port = y;
String userName = "user";
String password = "pass";
String TON = "0";
String NPI = "1";
String systemType = "generic";
try {
session.connectAndBind(
host,
port,
BindType.BIND_TRX,
userName,
password,
systemType,
TypeOfNumber.INTERNATIONAL,
NumberingPlanIndicator.ISDN,
null);
System.out.println("Session Connected");
} catch (IOException e) {
System.out.println("Failed connect and bind to host");
e.printStackTrace();
}
try {
String messageId = session.submitShortMessage(
"CMT",
TypeOfNumber.INTERNATIONAL,
NumberingPlanIndicator.UNKNOWN,
"SENDERNUMBER",
TypeOfNumber.INTERNATIONAL,
NumberingPlanIndicator.UNKNOWN,
"RECEIVERNUMBER",
new ESMClass(),
(byte)0,
(byte)1,
null,
null,
new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE),
(byte)0,
new GeneralDataCoding(false, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT),
(byte)0,
"Test from TEST".getBytes()
);
System.out.println("Message submitted, message_id is " + messageId);
//System.out.println("Message submitted, message_id is " + messageId);
Thread.sleep(2000);
}
catch(PDUException e)
{
System.out.println("PDU Exeption");
e.printStackTrace();
}
catch (ResponseTimeoutException e) {
// Response timeout
System.out.println("Response timeout");
e.printStackTrace();
} catch (InvalidResponseException e) {
// Invalid response
System.out.println("Receive invalid respose");
e.printStackTrace();
} catch (NegativeResponseException e) {
// Receiving negative response (non-zero command_status)
System.out.println("Receive negative response");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO error occur");
e.printStackTrace();
}
catch (InterruptedException e) {
System.out.println("Thread interrupted");
e.printStackTrace();
}
session.unbindAndClose();
}
}
Anyone , any idea ?
Thanks

How to call this Comets application from a web page

I have implemented the two classes shown at http://tomcat.apache.org/tomcat-6.0-doc/aio.html which gives a messenger application using Tomcat's comet implementation.
How do I connect this to a web interface and get something to display.
I am thinking these are the basic steps (I don't know the details).
I should create some traditional event - a button click or AJAX event - that calls the ChatServlet and passes in a CometEvent (somehow) - perhaps BEGIN
From then I have my code call the event method every time I want to send something to the client using the READ event as the input parameter.
I have copied the two classes below:
package controller;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.CometEvent;
import org.apache.catalina.CometProcessor;
public class ChatServlet extends HttpServlet implements CometProcessor {
protected ArrayList<HttpServletResponse> connections = new ArrayList<HttpServletResponse>();
protected MessageSender messageSender = null;
public void init() throws ServletException {
messageSender = new MessageSender();
Thread messageSenderThread = new Thread(messageSender, "MessageSender["
+ getServletContext().getContextPath() + "]");
messageSenderThread.setDaemon(true);
messageSenderThread.start();
}
public void destroy() {
connections.clear();
messageSender.stop();
messageSender = null;
}
/**
* Process the given Comet event.
*
* #param event
* The Comet event that will be processed
* #throws IOException
* #throws ServletException
*/
public void event(CometEvent event) throws IOException, ServletException {
HttpServletRequest request = event.getHttpServletRequest();
HttpServletResponse response = event.getHttpServletResponse();
if (event.getEventType() == CometEvent.EventType.BEGIN) {
log("Begin for session: " + request.getSession(true).getId());
PrintWriter writer = response.getWriter();
writer
.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">");
writer
.println("<head><title>JSP Chat</title></head><body bgcolor=\"#FFFFFF\">");
writer.flush();
synchronized (connections) {
connections.add(response);
}
} else if (event.getEventType() == CometEvent.EventType.ERROR) {
log("Error for session: " + request.getSession(true).getId());
synchronized (connections) {
connections.remove(response);
}
event.close();
} else if (event.getEventType() == CometEvent.EventType.END) {
log("End for session: " + request.getSession(true).getId());
synchronized (connections) {
connections.remove(response);
}
PrintWriter writer = response.getWriter();
writer.println("</body></html>");
event.close();
} else if (event.getEventType() == CometEvent.EventType.READ) {
InputStream is = request.getInputStream();
byte[] buf = new byte[512];
do {
int n = is.read(buf); // can throw an IOException
if (n > 0) {
log("Read " + n + " bytes: " + new String(buf, 0, n)
+ " for session: "
+ request.getSession(true).getId());
} else if (n < 0) {
// error(event, request, response);
System.out.println("you have an error");
return;
}
} while (is.available() > 0);
}
}
}
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
public class MessageSender implements Runnable {
protected boolean running = true;
protected ArrayList<String> messages = new ArrayList<String>();
protected ArrayList<HttpServletResponse> connections = new ArrayList<HttpServletResponse>();
public MessageSender() {
}
public void stop() {
running = false;
}
/**
* Add message for sending.
*/
public void send(String user, String message) {
synchronized (messages) {
messages.add("[" + user + "]: " + message);
messages.notify();
}
}
public void run() {
while (running) {
if (messages.size() == 0) {
try {
synchronized (messages) {
messages.wait();
}
} catch (InterruptedException e) {
// Ignore
}
}
synchronized (connections) {
String[] pendingMessages = null;
synchronized (messages) {
pendingMessages = messages.toArray(new String[0]);
messages.clear();
}
// Send any pending message on all the open connections
for (int i = 0; i < connections.size(); i++) {
try {
PrintWriter writer = connections.get(i).getWriter();
for (int j = 0; j < pendingMessages.length; j++) {
writer.println(pendingMessages[j] + "<br>");
}
writer.flush();
} catch (IOException e) {
System.out.println("IOExeption sending message" + e);
}
}
}
}
}
}
Here you have a complete example for Tomcat with source code to download at the bottom:Developing with Comet and Java

Resources