closing MQ connection - java

Good afternoon, I wrote a project to Get Park Queue Info from the IBM MQ, it has producing an error when attempting to close the connection though. It is written in java.
Under application in Event Viewer on the MQ machine it displays two errors. They are:
“Channel program ended abnormally.
Channel program ‘system.def.surconn’ ended abnormally. Look at previous error messages for channel program ‘system.def.surconn’ in the error files to determine the cause of the failure.
The other message states:
“Error on receive from host rnanaj (10.10.12.34)
An error occurred receiving data from rnanaj (10.10.12.34) over tcp/ip. This may be due to a communications failure. The return code from tcp/ip recv() call was 10054 (X’2746’). Record these values.”
This must be something how I try to connect or close the connection, below I have my code to connect and close, any ideas??
Connect:
_logger.info("Start");
File outputFile = new File(System.getProperty("PROJECT_HOME"), "run/" + this.getClass().getSimpleName() + "." + System.getProperty("qmgr") + ".txt");
FileUtils.mkdirs(outputFile.getParentFile());
Connection jmsConn = null;
Session jmsSession = null;
QueueBrowser queueBrowser = null;
BufferedWriter commandsBw = null;
try {
// get queue connection
MQConnectionFactory MQConn = new MQConnectionFactory();
MQConn.setHostName(System.getProperty("host"));
MQConn.setPort(Integer.valueOf(System.getProperty("port")));
MQConn.setQueueManager(System.getProperty("qmgr"));
MQConn.setChannel("SYSTEM.DEF.SVRCONN");
MQConn.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);
jmsConn = (Connection) MQConn.createConnection();
jmsSession = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue jmsQueue = jmsSession.createQueue("PARK");
// browse thru messages
queueBrowser = jmsSession.createBrowser(jmsQueue);
Enumeration msgEnum = queueBrowser.getEnumeration();
commandsBw = new BufferedWriter(new FileWriter(outputFile));
//
String line = "DateTime\tMsgID\tOrigMsgID\tCorrelationID\tComputerName\tSubsystem\tDispatcherName\tProcessor\tJobID\tErrorMsg";
commandsBw.write(line);
commandsBw.newLine();
while (msgEnum.hasMoreElements()) {
Message message = (Message) msgEnum.nextElement();
line = dateFormatter.format(new Date(message.getJMSTimestamp()))
+ "\t" + message.getJMSMessageID()
+ "\t" + message.getStringProperty("pkd_orig_jms_msg_id")
+ "\t" + message.getJMSCorrelationID()
+ "\t" + message.getStringProperty("pkd_computer_name")
+ "\t" + message.getStringProperty("pkd_subsystem")
+ "\t" + message.getStringProperty("pkd_dispatcher_name")
+ "\t" + message.getStringProperty("pkd_processor")
+ "\t" + message.getStringProperty("pkd_job_id")
+ "\t" + message.getStringProperty("pkd_sysex_msg");
_logger.info(line);
commandsBw.write(line);
commandsBw.newLine();
}
}
Close:
finally {
IO.close(commandsBw);
if (queueBrowser != null) { try { queueBrowser.close();} catch (Exception ignore) {}}
if (jmsSession != null) { try { jmsSession.close();} catch (Exception ignore) {}}
if (jmsConn != null) { try { jmsConn.stop();} catch (Exception ignore) {}}
}

As per the Javadoc for the connection object, the function of the stop() method is...
Temporarily stops a connection's
delivery of incoming messages.
So stop() doesn't actually sever the connection. You want the close() method.

Related

Connection does not throw error but does not succeed either

I am currently trying to connect to an amazon RDS from a lambda function. The problem I am facing is that I do not get an error but neither I manage to get a connection, so I am not sure how to proceed. I do not have a timeout, or an error with the parameters, but the object "con" is always null.
To do this I am doing the following:
Connection con = null;
String jdbcUrl2 = "jdbc:mysql://" + "connectionValueExample-zone.rds.amazonaws.com" + ":" + "3306" + "/" + "botdb" + "?user=" + "bot" + "&password=" + "PWvalueExample";
con = DriverManager.getConnection(jdbcUrl2);
After every step I check with prints() how it's going. After I try to stablish the connection I try to catch it, because while I am not getting exceptions right now, the object con never stops being null, so I do not stablish a connection.
catch (SQLException e) {
e.toString();
log.warn(e.toString());
} catch (Exception e) {
System.out.println("excepcion no capturada ");
e.toString();
}
The second catch is just in case I was missing something, originally it was not there.
All in all, the code looks something like:
#Override
public String handleRequest(Object input, Context context) {
context.getLogger().log("Input: " + input);
Connection con = null;
try {
String jdbcUrl2 = "jdbc:mysql://" + "value-zone.rds.amazonaws.com" + ":" + "3306" + "/" + "botdb" + "?user=" + "bot" + "&password=" + "PW";
con = DriverManager.getConnection(jdbcUrl2);
} catch (SQLException e) {
e.toString();
log.warn(e.toString());
} catch (Exception e) {
System.out.println("excepcion no capturada ");
e.toString();
}
String status = null;
if (con != null) {
status = "conexion establecida";
System.out.println("connection stablished");
} else status = "connection failed";
return status;
}
Edit:
I am now capturing slightly better the exceptions and get the following message:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
At this point I am unsure if the Strin jdbcURL is not properly formed OR why is the connection failing.

Waiting forever in ObjectInputStream Constructor [duplicate]

This question already has an answer here:
Must server & client have reverse sequence of claiming ObjectOutputStream & ObjectInputStream?
(1 answer)
Closed 4 years ago.
I am creating a client-server as follows:
Server:
Listener thread daemon (listening always for incoming connections)
Service object that send/receive data with clients connected
Client(s):
There can be many instances of clients
However, on either sides after connection is established, it takes forever to create Constructor of type ObjectOutputStream & ObjectInputStream. Bit of googling revealed this and this. I followed steps of :
1. creating ObjectOutputStream first
2. flush it
3. creating ObjectInputStream second
But this doesn't work for me. Wonder why ??
Server:
Listener Thread/daemon:
Socket connSocket;
try {
ServiceListener.serverSocket = new ServerSocket(listenPort);
System.out.println("Listening on port: " + listenPort);
while (true) {
connSocket = serverSocket.accept();
nodeList.add(connSocket);
System.out.println("Accepted connections ( " + connSocket + "):" + getConnectedNodeCount());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Server Thread (After accepting Connection)
for (int i=0; i<listenerObj.getConnectedNodeCount(); i++) {
try {
System.out.println(listenerObj.nodeList.get(i));
serviceTx = new ObjectOutputStream(listenerObj.nodeList.get(i).getOutputStream());
serviceTx.flush();
serviceRx = new ObjectInputStream(listenerObj.nodeList.get(i).getInputStream());
String rxMsg = (String) serviceRx.readObject();
if (rxMsg.equals("HELLO")) {
System.out.println("Service received: " + rxMsg);
serviceTx.writeObject((Object) "HELLO");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Client:
try {
System.out.println("Creating Node socket...");
clientSocket = new Socket(getServerIp(), getServerPort());
nodeTx = new ObjectOutputStream(clientSocket.getOutputStream());
nodeTx.flush();
nodeRx = new ObjectInputStream(clientSocket.getInputStream());
System.out.println("Connected to " + getServerIp() + ":" + getServerPort());
do {
String outBoundMsg = new String();
outBoundMsg = "HELLO";
System.out.println("Node sending \"" + outBoundMsg + "\" to service");
nodeTx.writeObject(outBoundMsg);
nodeTx.flush();
String rcvdMsg = (String) nodeRx.readObject();
if(rcvdMsg.equals("HELLO")) {
System.out.println("++++ client says " + rcvdMsg + " ++++");
}
} while(false);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Server Console Output:
starting Listener 11...
Service Function started !!
Listening on port: 2244
Accepted connections ( Socket[addr=/127.0.0.1,port=62994,localport=2244]):1
Client Console:
Creating Node socket...
I would change the do { } while(false) to a do { } while(true) otherwise it make no sense to have a while loop that runs only once and exit, i.e. the do-while(false) loop acts just as if it is not there.

JTOpen ProgramCall Socket Timeout

I'm working on a web app (running on Tomcat) that calls programs on an IBM i (AS/400) using the JTOpen ProgramCall class (com.ibm.as400.access.ProgramCall). My problem is with program calls that take more than 30s to respond, which are triggering a java.net.SocketTimeoutException: Read timed out exception.
There is a setTimeout() method available for this class, but it doesn't seem to have an effect on the socket timeout. I've also checked my Tomcat configurations and didn't see anything that would cause this behavior.
Does anyone know of a way to alter the timeout for such an implementation?
Code:
pgmCall.setProgram(getCompleteName(), parmList);
initializeAS400TextParameters();
// Run the AS/400 program.
try {
Trace.setTraceDiagnosticOn(true);
Trace.setTraceInformationOn(true);
Trace.setTraceWarningOn(true);
Trace.setTraceErrorOn(true);
Trace.setTraceDatastreamOn(true);
if (pgmCall.run() != true) {
messageList = pgmCall.getMessageList();
for (int i = 0; i < messageList.length; i++) {
log.debug("Error Message " + i + " " + messageList[i]);
}
setCompletionMsg("Program call failed.");
log.debug("442 Program call failed.");
return false;
} else {
messageList = pgmCall.getMessageList();
for (int i = 0; i < messageList.length; i++) {
log.debug("Success Message " + i + " " + messageList[i]);
}
setCompletionMsg("Program called ok.");
log.debug("452 Program called ok.");
return true;
}
} catch (Exception e) {
// This is where the timeout exception is thrown
log.debug("Error Running Program: " + e.getMessage() + " " + e.getLocalizedMessage());
setCompletionMsg(e.getMessage());
}
Well, after several more hours I've found the solution. Apparently the original developer added a socket timeout parameter to the JDBC connection string - simply removing the parameter did the trick as the default value is 0, or infinite timeout.
Before:
String connectionStr = "jdbc:as400://" + systemInfo.getIPAddress() + ":1527" + ";naming=system;socket timeout=30000;thread used=false;errors=full;prompt=false;date format=iso;block size=128;transaction isolation=none;user=" + systemInfo.getUserName() + ";password=" + systemInfo.getPassword();
After:
String connectionStr = "jdbc:as400://" + systemInfo.getIPAddress() + ":1527" + ";naming=system;thread used=false;errors=full;prompt=false;date format=iso;block size=128;transaction isolation=none;user=" + systemInfo.getUserName() + ";password=" + systemInfo.getPassword();
:\

Blackberry Connection Nightmare

I'm busy writing a Program that Transmits GPS Coordinates to a Server from a mobile phone where the coordinates are then used for calculations. But I'm constantly hitting a wall with blackberry. I have built the Android App and it works great but can't seem to contact the server on a real blackberry device. I have tested the application in a simulator and it works perfectly but when I install it on a real phone I get no request the phone.
I have read quite a bit about the secret strings to append at the end of the url so I adapted some demo code to get me the first available transport but still nothing ...
The Application is Signed and I normally then either install it by debugging through eclipse or directly on the device from the .jad file and allow the application the required permissions.
The current code was adapted from the HTTP Connection Demo in the Blackberry SDK.
Could you have a look and give me some direction. I'm losing too much hair here ...
The Backend Service that keeps running:
public void run() {
System.out.println("Starting Loop");
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
cr.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
cr.setCostAllowed(false);
cr.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT);
cr.setPreferredResponseTime(1000);
LocationProvider lp = null;
try {
lp = LocationProvider.getInstance(cr);
} catch (LocationException e) {
System.out.println("*****************Exception" + e);
}
if (lp == null) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("GPS not supported!");
return;
}
});
} else {
System.out
.println(lp.getState() + "-" + LocationProvider.AVAILABLE);
switch (lp.getState()) {
case LocationProvider.AVAILABLE:
// System.out.println("Provider is AVAILABLE");
while (true) {
Location l = null;
int timeout = 120;
try {
l = lp.getLocation(timeout);
final Location fi = l;
System.out.println("Got a Coordinate "
+ l.getQualifiedCoordinates().getLatitude()
+ ", "
+ l.getQualifiedCoordinates().getLongitude());
System.out.println("http://" + Constants.website_base
+ "/apis/location?device_uid=" + Constants.uid
+ "&lat="
+ l.getQualifiedCoordinates().getLatitude()
+ "&lng="
+ l.getQualifiedCoordinates().getLongitude());
if (!_connectionThread.isStarted()) {
fetchPage("http://"
+ Constants.website_base
+ "/apis/location?device_uid="
+ Constants.uid
+ "&lat="
+ l.getQualifiedCoordinates().getLatitude()
+ "&lng="
+ l.getQualifiedCoordinates()
.getLongitude());
} else {
createNewFetch("http://"
+ Constants.website_base
+ "/apis/location?device_uid="
+ Constants.uid
+ "&lat="
+ l.getQualifiedCoordinates().getLatitude()
+ "&lng="
+ l.getQualifiedCoordinates()
.getLongitude());
}
Thread.sleep(1000 * 60);
} catch (LocationException e) {
System.out.println("Location timeout");
} catch (InterruptedException e) {
System.out.println("InterruptedException"
+ e.getMessage());
} catch (Exception ex) {
System.err.println(ex.getMessage());
ex.printStackTrace();
}
}
}
}
My Connection is Made with:
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc = connFact.getConnection(getUrl());
// Open the connection and extract the data.
try {
// StreamConnection s = null;
// s = (StreamConnection) Connector.open(getUrl());
HttpConnection httpConn = (HttpConnection) connDesc.getConnection();
/* Data is Read here with a Input Stream */
Any Ideas ?
Figured it out!
Using a function I found online to determine which ; extension to use when connecting by using numerous Try / Catch. Then had to set the Internet APN settings. I'm in South-Africa using Vodacom so the APN is "Internet" with no Password.
Barely have hair left ....

IOException doesn't give enough information

My android program isn't working. I am using normal client-server sockets. I have tested my server with telnet and it works fine, but when I try it with my android program, it doesn't work (more details in a second). Here's my code:
Socket s = null;
try
{
String SocketServerAddress = db.getPhSsServerAddress();
Integer SocketServerPort = db.getPhSsServerPort();
s = new Socket(SocketServerAddress, SocketServerPort);
Log.d(MY_DEBUG_TAG, "Setting up Socket: " + SocketServerAddress + ":" + SocketServerPort);
DataOutputStream out = new DataOutputStream(s.getOutputStream());
DataInputStream in = new DataInputStream(s.getInputStream());
Log.d(MY_DEBUG_TAG, "Connected to: " + s.getInetAddress() + " on port " + s.getPort());
out.writeUTF("Helo, Server");
out.flush();
Log.d(MY_DEBUG_TAG, "Bytes written: " + out.size());
String st = in.readUTF();
Log.d(MY_DEBUG_TAG, "SocketServerResponse: " + st);
}
catch (UnknownHostException e)
{
Log.e(MY_ERROR_TAG, "UnknownHostException: " + e.getMessage() + "; " + e.getCause());
}
catch (IOException e)
{
Log.e(MY_ERROR_TAG, "IOException: " + e.getMessage() + "; " + e.getCause() + "; " + e.getLocalizedMessage());
}
finally
{
try {
s.close();
} catch (IOException e) {
Log.e(MY_ERROR_TAG, "IOException on socket.close(): " + e.getMessage() + "; " + e.getCause());
}
}
All I ever get here is a thrown IOException with no message or cause attached. The specific line causing the error is the String st = in.readUTF(). If I comment out that line, my code runs fine (no exceptions thrown), but my server does not acknowledge that any data has been sent to it. And of course I don't get any data back since that line is commented out.
So, how can I figure out what the problem is? Tonight I am going to try and see what is being passed with wireshark to see if that gives any insight.
Is the server using readUTF() and writeUTF() too? writeUTF() writes data in a unique format that can only be understood by readUTF(), which won't understand anything else.
EDIT EOFException means that there is no more data. You should catch it separately and handle it by closing the socket etc. It can certainly be caused spuriously by readUTF() trying to read data that wasn't written with writeUTF().
And deciding it was an IOException when it was really an EOFException means you didn't print out or log the exception itself, just its message. Always use the log methods provided for exceptions, or at least use Exception.toString().
As I remember I had a problem with DataInpuStream some day... try doing so:
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

Categories

Resources