I want to consume all messages from MQ.
public static void main(String[] args)
{
JMSContext context = null;
Destination destination = null;
JMSConsumer consumer = null;
JmsFactoryFactory FF = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactor CF = FF.createConnectionFactory();
context = CF.createContext();
destination = context.createQueue(QUEUE_NAME);
consumer = context.createConsumer(destination);
String msg = consumer.receiveBody(String.class, 15090);
System.out.println(msg);
}
It is able to read one message only. How can I consume all messages? Also, is there any simpler way to delete all messages in queue without even reading or consuming them?
The JMS API consumes a single message at a time so you'll need to put your receiveBody in a loop, e.g.:
public static void main(String[] args) {
JMSContext context = null;
Destination destination = null;
JMSConsumer consumer = null;
JmsFactoryFactory FF = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactor CF = FF.createConnectionFactory();
context = CF.createContext();
destination = context.createQueue(QUEUE_NAME);
consumer = context.createConsumer(destination);
String msg = null;
do {
msg = consumer.receiveBody(String.class, 15090);
System.out.println(msg);
} while (msg != null);
}
When receiveBody returns null that means there's no more messages in the queue.
The JMS API doesn't define any way to delete all the messages from a queue, but most JMS servers have an implementation-specific management API through which you can perform those sorts of actions.
If, as your question suggests, all you want to do is empty a queue of all its messages and not actually read them in an application, you could consider simply using the administrative MQSC command:-
CLEAR QLOCAL(queue-name)
You can type this into the runmqsc tool to issue it to the queue manager.
is there any simpler way to delete all messages in queue without even
reading or consuming them?
Yes. You can use the MQ PCF Clear Queue command, so long as no application has the queue open for input or output. i.e. IPPROCS and OPPROCS must be zero for it to work. This is also true for Morag's MQSC Clear command.
Here is a fully functioning Java MQ PCF program to clear a queue.
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
* MQClearQueue01
*
* Description
* This java class issues a PCF "Clear Q" command for a queue to delete all messages
* in the queue of a remote queue manager.
*
* 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 MQClearQueue01
{
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;
public MQClearQueue01()
{
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())
{
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;
String qMgrName = (String) params.get("-m");
String queueName = (String) params.get("-q");
try
{
qMgr = new MQQueueManager(qMgrName, mqht);
MQClearQueue01.logger("successfully connected to "+ qMgrName);
agent = new PCFMessageAgent(qMgr);
MQClearQueue01.logger("successfully created agent");
// https://www.ibm.com/support/knowledgecenter/SSFKSJ_latest/com.ibm.mq.ref.adm.doc/q087420_.html
request = new PCFMessage(CMQCFC.MQCMD_CLEAR_Q);
request.addParameter(CMQC.MQCA_Q_NAME, queueName);
responses = agent.send(request);
MQClearQueue01.logger("responses.length="+responses.length);
for (int i = 0; i < responses.length; i++)
{
if ((responses[i]).getCompCode() == CMQC.MQCC_OK)
MQClearQueue01.logger("Successfully cleared queue '"+queueName+"' of messages.");
else
MQClearQueue01.logger("Error: Failed to clear queue '"+queueName+"' of messages.");
}
}
catch (MQException e)
{
MQClearQueue01.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
catch (IOException e)
{
MQClearQueue01.logger("IOException:" +e.getLocalizedMessage());
}
catch (MQDataException e)
{
MQClearQueue01.logger("MQDataException:" +e.getLocalizedMessage());
}
finally
{
try
{
if (agent != null)
{
agent.disconnect();
MQClearQueue01.logger("disconnected from agent");
}
}
catch (MQDataException e)
{
MQClearQueue01.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
try
{
if (qMgr != null)
{
qMgr.disconnect();
MQClearQueue01.logger("disconnected from "+ qMgrName);
}
}
catch (MQException e)
{
MQClearQueue01.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)
{
MQClearQueue01 mqcq = new MQClearQueue01();
try
{
mqcq.init(args);
mqcq.doPCF();
}
catch (IllegalArgumentException e)
{
MQClearQueue01.logger("Usage: java MQClearQueue01 -m QueueManagerName -h host -p port -c channel -q QueueName -u UserID -x Password");
System.exit(1);
}
System.exit(0);
}
}
Related
Good Day,
I am struggling with below error when trying to connect to IBM MQ. Unable to access createContext(); and forces me to use (JMSContext) cf.createConnection(); which is resulting me error as below:
"Exception in thread "main" java.lang.ClassCastException: com.ibm.mq.jms.MQConnection cannot be cast to javax.jms.JMSContext
at pushmsgs.main(pushmsgs.java:55)"
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import javax.jms.*;
public class pushmsgs {
// System exit status value (assume unset value to be 1)
private static int status = 1;
// Create variables for the connection to MQ
private static final String HOST = "22.188.133.100"; // Host name or IP address
private static final int PORT = 3415; // Listener port for your queue manager
private static final String CHANNEL = "DEV.APP.SVRCONN"; // Channel name
private static final String QMGR = "SITQUEUEMGR"; // Queue manager name
// private static final String APP_USER = "app"; // User name that application uses to connect to MQ
//private static final String APP_PASSWORD = "_APP_PASSWORD_"; // Password that the application uses to connect to MQ
private static final String QUEUE_NAME = "TESTQUEUE.MQAPP.REQ.RCV"; // Queue that the application uses to put and get messages to and from
/**
* Main method
*
* #param args
*/
public static void main(String[] args) {
// Variables
JMSContext context = null;
Destination destination = null;
JMSProducer producer = null;
JMSConsumer consumer = null;
try {
// Create a connection factory
JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactory cf = ff.createConnectionFactory();
// Set the properties
cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
// cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
//cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
// cf.setStringProperty(WMQConstants.USERID, APP_USER);
//cf.setStringProperty(WMQConstants.PASSWORD, APP_PASSWORD);
//cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, "*TLS12");
// Create JMS objects
context = (JMSContext) cf.createConnection();
destination = context.createQueue("queue:///" + QUEUE_NAME);
long uniqueNumber = System.currentTimeMillis() % 1000;
TextMessage message = context.createTextMessage("Your lucky number today is " + uniqueNumber);
producer = context.createProducer();
producer.send(destination, message);
System.out.println("Sent message:\n" + message);
context.close();
recordSuccess();
} catch (JMSException jmsex) {
recordFailure(jmsex);
}
System.exit(status);
} // end main()
/**
* Record this run as successful.
*/
private static void recordSuccess() {
System.out.println("SUCCESS");
status = 0;
return;
}
/**
* Record this run as failure.
*
* #param ex
*/
private static void recordFailure(Exception ex) {
if (ex != null) {
if (ex instanceof JMSException) {
processJMSException((JMSException) ex);
} else {
System.out.println(ex);
}
}
System.out.println("FAILURE");
status = -1;
return;
}
/**
* Process a JMSException and any associated inner exceptions.
*
* #param jmsex
*/
private static void processJMSException(JMSException jmsex) {
System.out.println(jmsex);
Throwable innerException = jmsex.getLinkedException();
if (innerException != null) {
System.out.println("Inner exception(s):");
}
while (innerException != null) {
System.out.println(innerException);
innerException = innerException.getCause();
}
return;
}
}
Added JMS mvn dependency and com.ibm.mq.allclient dependency
It's because you are assigning the wrong object to the wrong variable.
context = (JMSContext) cf.createConnection();
I don't know why you would want to do that. A connection is not a context.
It should be:
Connection conn = cf.createConnection("MyUserId", "mypassword");
See my example called MQTestJMS51 here.
when using a solution provided in the below post : Browse, read, and remove a message from a queue using IBM MQ classes
i am getting below error
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2495;AMQ8568: The native JNI library 'mqjbnd64' was not found. For a client installation this is expected. [3=mqjbnd64]
I am new to IBM MQ , but i think it is trying to fing MQ library on my local machine but i want to connect on remote server as MQ is not installed on my machine
Here is a Java/MQ program that will connect to either (1) a remote queue manager (client mode) or (2) local queue manager (bindings mode), open queue, loop to retrieve all messages from a queue then close and disconnect.
import java.io.EOFException;
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.MQGetMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.CMQC;
/**
* Program Name
* MQTest12L
*
* Description
* This java class will connect to a remote queue manager with the
* MQ setting stored in a HashTable, loop to retrieve all messages from a queue
* then close and disconnect.
*
* Sample Command Line Parameters
* bindings mode
* -m MQA1 -q TEST.Q1
* client mode
* -m MQA1 -q TEST.Q1 -h 127.0.0.1 -p 1414 -c TEST.CHL -u UserID -x Password
*
* #author Roger Lacroix
*/
public class MQTest12L
{
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;
/**
* The constructor
*/
public MQTest12L()
{
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("-m") && params.containsKey("-q");
if (params.containsKey("-c"))
{
b = b && params.containsKey("-c") && params.containsKey("-h") && params.containsKey("-p");
}
if (b)
{
try
{
if (params.containsKey("-p"))
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())
{
if (params.containsKey("-c"))
{
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));
if (params.containsKey("-u"))
mqht.put(CMQC.USER_ID_PROPERTY, params.get("-u"));
if (params.containsKey("-x"))
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, loop and get all messages then close queue and disconnect.
*
*/
private void testReceive()
{
String qMgrName = (String) params.get("-m");
String inputQName = (String) params.get("-q");
MQQueueManager qMgr = null;
MQQueue queue = null;
int openOptions = CMQC.MQOO_INPUT_AS_Q_DEF + CMQC.MQOO_INQUIRE + CMQC.MQOO_FAIL_IF_QUIESCING;
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.options = CMQC.MQGMO_WAIT + CMQC.MQGMO_FAIL_IF_QUIESCING;
gmo.waitInterval = 5000; // wait up to 5 seconds for a message.
MQMessage receiveMsg = null;
int msgCount = 0;
boolean getMore = true;
try
{
if (params.containsKey("-c"))
qMgr = new MQQueueManager(qMgrName, mqht);
else
qMgr = new MQQueueManager(qMgrName);
MQTest12L.logger("successfully connected to "+ qMgrName);
queue = qMgr.accessQueue(inputQName, openOptions);
MQTest12L.logger("successfully opened "+ inputQName);
while(getMore)
{
receiveMsg = new MQMessage();
try
{
// get the message on the queue
queue.get(receiveMsg, gmo);
msgCount++;
if (CMQC.MQFMT_STRING.equals(receiveMsg.format))
{
String msgStr = receiveMsg.readStringOfByteLength(receiveMsg.getMessageLength());
// MQTest12L.logger("["+msgCount+"] " + msgStr);
}
else
{
byte[] b = new byte[receiveMsg.getMessageLength()];
receiveMsg.readFully(b);
// MQTest12L.logger("["+msgCount+"] " + new String(b));
}
}
catch (MQException e)
{
if ( (e.completionCode == CMQC.MQCC_FAILED) &&
(e.reasonCode == CMQC.MQRC_NO_MSG_AVAILABLE) )
{
// All messages read.
getMore = false;
break;
}
else
{
MQTest12L.logger("MQException: " + e.getLocalizedMessage());
MQTest12L.logger("CC=" + e.completionCode + " : RC=" + e.reasonCode);
getMore = false;
break;
}
}
catch (IOException e)
{
MQTest12L.logger("IOException:" +e.getLocalizedMessage());
}
}
}
catch (MQException e)
{
MQTest12L.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
finally
{
MQTest12L.logger("read " + msgCount + " messages");
try
{
if (queue != null)
{
queue.close();
MQTest12L.logger("closed: "+ inputQName);
}
}
catch (MQException e)
{
MQTest12L.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
try
{
if (qMgr != null)
{
qMgr.disconnect();
MQTest12L.logger("disconnected from "+ qMgrName);
}
}
catch (MQException e)
{
MQTest12L.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)
{
MQTest12L write = new MQTest12L();
try
{
write.init(args);
write.testReceive();
}
catch (IllegalArgumentException e)
{
System.err.println("Usage: java MQTest12L -m QueueManagerName -q QueueName [-h host -p port -c channel] [-u UserID] [-x Password]");
System.exit(1);
}
System.exit(0);
}
}
I wish to get the service name being used in the port. However, I am unable to. What I want to do is to check if a port is used. If it is used, then I want to get the service details on that port. How can I achieve this and what I am doing wrong?
public int checkPort(int port){
try {
InetAddress inetAddress = InetAddress.getLocalHost();
ss = new Socket(inetAddress.getHostAddress(), port);
if(ss.isBound()) {
System.out.println("Port " + port + " is being used by ");
Process p1 = Runtime.getRuntime().exec("grep -w " + port + " /etc/services");
p1.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
String line = reader.readLine();
while(line != null) {
System.out.println(line);
line = reader.readLine();
}
}
ss.close();
} catch (Exception e) {
System.out.println("Port " +port+ " is not being used");
}
return 0;
}
Results in
Port 139 is being used by
Port 139 is not being used
Well, assuming you are on Windows (it may or may not be different on other operating systems), you may be getting this exception.
Cannot run program "grep": CreateProcess error=2, The system cannot find the file specified
At least, that is what I got. You might be getting a totally different error. The main issue here is that there is one big try catch block with no e.printStackTrace() and it catches every exception. This means that when it goes wrong, there is no way to know why.
Hopefully this will work for you. Ironically you do not need a socket to test for services on a port so this may be an XY problem.
My solution to finding services on a port is the following.
SocketTester.java
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
/**
* An answer for Unable to get service details on port?
*
* #see Unable to get service details on port?
* #version 1.0
* #author Dan
*/
public class SocketTester {
/**
* This method checks whether a port is being used by any services.
* It will output any information to the system console.
*
* #param port The port to be checked for any services
*/
public static void checkPort(int port) {
TreeSet<String> pids = null;
List<Service> services = null;
pids = getPIDs(port);
if(pids != null) {
services = getServices(port, pids);
}
listInformation(port, services);
}
/**
* This method checks whether there are any PIDs on the specified port.
* If there are these are then returned.
*
* #param port The port to check for PIDs
* #return It returns a TreeSet containing any found PIDs on the specified port
*/
private static TreeSet<String> getPIDs(int port) {
TreeSet<String> returnVal = new TreeSet<String>();
ProcessBuilder pidProcessBuilder = new ProcessBuilder("cmd.exe", "/C", "netstat -ano | find \"" + port + "\"");
pidProcessBuilder.redirectErrorStream(true);
Process pidProcess = null;
try {
pidProcess = pidProcessBuilder.start();
} catch (IOException e) {
return null;
}
BufferedReader pidProcessOutputReader = new BufferedReader(new InputStreamReader(pidProcess.getInputStream()));
String outputLine = null;
try {
outputLine = pidProcessOutputReader.readLine();
} catch (IOException e) {
return null;
}
while (outputLine != null) {
List<String> outputLineParts = new ArrayList<String>(Arrays.asList(outputLine.split(" ")));
outputLineParts.removeAll(Arrays.asList(""));
//outputLineParts.get(1) is the local address. We don't want a foreign address to accidently be found
//outputLineParts.size() - 1 is the PID
if(outputLineParts.get(1).contains(":" + port) && !returnVal.contains(outputLineParts.get(outputLineParts.size() - 1))) {
returnVal.add(outputLineParts.get(outputLineParts.size() - 1));
}
try {
outputLine = pidProcessOutputReader.readLine();
} catch (IOException e) {
return null;
}
}
try {
pidProcess.waitFor();
} catch (InterruptedException e) {
return null;
}
return returnVal;
}
/**
* This method checks whether there are any services related to the PID.
* If there are these are then returned.
*
* #param port A reference to the PIDs port
* #param pids A list of PIDs found by getPIDs
* #return It returns a List containing any found services on the specified PIDs
*/
private static List<Service> getServices(int port, TreeSet<String> pids) {
List<Service> returnVal = new ArrayList<Service>();
for(String pid : pids) {
ProcessBuilder serviceProcessBuilder = new ProcessBuilder("cmd.exe", "/C", "tasklist /svc /FI \"PID eq " + pid + "\" | find \"" + pid + "\"");
serviceProcessBuilder.redirectErrorStream(true);
Process serviceProcess = null;
try {
serviceProcess = serviceProcessBuilder.start();
} catch (IOException e) {
return null;
}
BufferedReader serviceProcessOutputReader = new BufferedReader(new InputStreamReader(serviceProcess.getInputStream()));
String outputLine = null;
try {
outputLine = serviceProcessOutputReader.readLine();
} catch (IOException e) {
return null;
}
while(outputLine != null) {
List<String> outputLineParts = new ArrayList<String>(Arrays.asList(outputLine.split(" ")));
outputLineParts.removeAll(Arrays.asList(""));
//outputLineParts.get(0) is the service
returnVal.add(new Service(port, pid, outputLineParts.get(0)));
try {
outputLine = serviceProcessOutputReader.readLine();
} catch (IOException e) {
return null;
}
}
try {
serviceProcess.waitFor();
} catch (InterruptedException e) {
return null;
}
}
return returnVal;
}
/**
* This method lists the information found by checkPort
*
* #param port The port that has been checked for services
* #param servicesRunning The services found on the port
*/
private static void listInformation(int port, List<Service> servicesRunning) {
if(servicesRunning != null && servicesRunning.size() != 0) {
System.out.println("The following services are being run on port " + port);
for(Service service : servicesRunning) {
System.out.println("\t" + service.getService());
}
} else {
System.out.println("There are no services being run on port " + port);
}
}
public static void main(String[] args) {
final int portToCheck = 135;
checkPort(portToCheck);
}
}
Sevice.java
package socket;
/**
* An supplementary class to support SocketTester
*
* #see Unable to get service details on port?
* #version 1.0
* #author Dan
*/
public class Service {
private int port;
private String pid;
private String service;
public Service(int port, String pid, String service) {
this.port = port;
this.pid = pid;
this.service = service;
}
public int getPort() {
return port;
}
public String getPID() {
return pid;
}
public String getService() {
return service;
}
#Override
public String toString() {
return "Service \"" + "\" is being run on port " + port + " and has the PID " + pid;
}
}
I'm working with Teamcenter and Catia via the Java SOA libraries. I'm running into an issue where the demo code appears broken and I can't find a good example or documentation to work towards. The following code results in a null value exception. Specifically the line "session = PortalContext.getContext().getSession();" is where I'm crashing.
package com.ebsolutions.catiman.actions;
import java.io.File;
import java.io.RandomAccessFile;
/*
* Tc java classes
*/
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentRevisionRuleType;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
/*
* Catia integration java classes
*/
import com.ebsolutions.catiman.ErrorWarningMessages;
import com.ebsolutions.catiman.PortalContext;
import com.ebsolutions.catiman.commands.TClassUserLUSCommand;
/**
* Sample file.
* This class is not launched by the CATIAV5 integration
*
* #date 02/06/2008
*/
public class SampleIndependentSilentLUS
{
/**
* Current TC session: needed to access Tc server (service.call)
* null value is not allowed.
*/
protected TCSession session = null;
/**
* This flag defines wether the LUS should be performed in silent mode or not
*/
protected boolean is_silent[];
/**
* title of the messages
*/
private String _title = "Sample Independent SilentLUS";
/**
* components that contains the assembly to LUS.
*/
private TCComponentItem[] item = null;
private TCComponentItemRevision[] item_revision = null;
private TCComponentDataset[] part_dataset = null;
private TCComponentDataset[] product_dataset = null;
private TCComponentDataset[] drawing_dataset = null;
private TCComponentForm[] other = null;
private TCComponentBOMWindow bom_window[] = null;
/**
* The constructor.
*/
public SampleIndependentSilentLUS()
{
/* try to find the TCSession
note: this is not the only way to retrieve the TCSession. */
session = PortalContext.getContext().getSession();
}
/* --------------------------------------------------------------------- */
/*
* Sample main function
* #date 02/06/2008
*/
public void customerProcess() {
showInformationMessage("START of silent LUS");
TClassUserLUSCommand silent_lus_command = null;
/*
* example of searching items to LUS
*/
int return_value = findItemToLUS();
if (return_value < 0)
{
/* Unable to find any item to LUS */
return;
}
/**
* Initialize the API
*/
silent_lus_command = new TClassUserLUSCommand(session);
/*
* API: LUS process.
* call the "executeLUS" function
*/
/******* Item ********/
try
{
if (item[0] != null)
{
silent_lus_command.executeLUS(item[0], is_silent[0]);
showInformationMessage("pause in silent LUS after Item");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (1) Exception : " + ex);
}
/******* Item Revision ********/
try
{
if (item_revision[1] != null)
{
silent_lus_command.executeLUS(item_revision[1], is_silent[1]);
showInformationMessage("pause in silent LUS after Item_rev");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (2) Exception : " + ex);
}
/******* bom window ********/
try
{
if (bom_window[2] != null)
{
silent_lus_command.executeLUS(bom_window[2], is_silent[2]);
showInformationMessage("pause in silent LUS after bom_widow");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (3) Exception : " + ex);
}
/******* CATPart dataset ********/
try
{
if (part_dataset[3] != null)
{
silent_lus_command.executeLUS(part_dataset[3], is_silent[3]);
showInformationMessage("pause in silent LUS after CATPart");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (4) Exception : " + ex);
}
/******* CATProduct dataset ********/
try
{
if (product_dataset[4] != null)
{
silent_lus_command.executeLUS(product_dataset[4], is_silent[4]);
showInformationMessage("pause in silent LUS after CATProduct");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (5) Exception : " + ex);
}
/******* CATDrawing dataset ********/
try
{
if (drawing_dataset[5] != null)
{
silent_lus_command.executeLUS(drawing_dataset[5], is_silent[5]);
showInformationMessage("pause in silent LUS after CATDrawing");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (6) Exception : " + ex);
}
/******* other dataset ********/
try
{
if (other[6] != null)
{
silent_lus_command.executeLUS(other[6], is_silent[6]);
showInformationMessage("pause in silent LUS ");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (7) Exception : " + ex);
}
silent_lus_command.stopProcess();
}
/**
* is used to display an Error message
* #param i_msg (I) the message to be displayed
*/
private void showErrorMessage(final String i_msg)
{
ErrorWarningMessages.showErrorMessage(i_msg, _title);
}
/**
* is used to display an Information message
* #param i_msg (I) the message to display
*/
private void showInformationMessage(final String i_msg)
{
ErrorWarningMessages.showInformationMessage(i_msg, _title);
}
/**
* Sample of searching item to LUS.
* read the query.txt file that contains the item_id, item_rev_id and silent mode of the selected item
* The first line contains the number of assembly to LUS
* Then, for each assembly, we need 3 lines : item_id, item_rev_id and silent_mode
* example :
* 2
* 000010
* A
* true
* 000020
* B
* false
*/
protected int findItemToLUS()
{
String item_id = null;
String item_rev_id = null;
int return_value = 0;
int nb_assy = 0;
RandomAccessFile reader = null;
File file = null;
try
{
String file_path = "c:\\catiman_tmp\\tmp\\query.txt";
file = new File(file_path);
reader = new RandomAccessFile(file, "r");
nb_assy = Integer.valueOf(reader.readLine()).intValue();
is_silent = new boolean[nb_assy];
item = new TCComponentItem[nb_assy];
item_revision = new TCComponentItemRevision[nb_assy];
part_dataset = new TCComponentDataset[nb_assy];
product_dataset = new TCComponentDataset[nb_assy];
drawing_dataset = new TCComponentDataset[nb_assy];
other = new TCComponentForm[nb_assy];
bom_window = new TCComponentBOMWindow[nb_assy];
}
catch (Exception ex)
{
showErrorMessage("error 0 - " + ex);
return_value = -1;
}
for (int i = 0 ; i < (nb_assy) ; i++)
{
try
{
item_id = reader.readLine();
item_rev_id = reader.readLine();
is_silent[i] = Boolean.valueOf(reader.readLine()).booleanValue();
// search item name item_id
TCComponentItemType it = (TCComponentItemType)(session.getTypeComponent("Item"));
item[i] = it.find(item_id);
if (item[i] == null)
{
showErrorMessage("Error : item <" + item_id + ">not found");
return_value = -1;
}
else
{
// the item was found, search the correction item revision
AIFComponentContext[] revisions = item[i].getChildren();
TCComponentItemRevision revision_component = null;
for (int j = 0; j < revisions.length; j++)
{
InterfaceAIFComponent component = revisions[j].getComponent();
if (component instanceof TCComponentItemRevision)
{
revision_component = (TCComponentItemRevision) component;
if (revision_component.getProperty("item_revision_id").equals(item_rev_id))
{
item_revision[i] = revision_component;
break;
}
}
}
if (item_revision[i] == null)
{
showErrorMessage("Error : Item revision [" + item_rev_id + "] doesn't exist for item [" + item_id + "]");
return_value = -1;
}
else
{
// create the BOMWindow with the item revision previously found
TCComponentBOMWindowType type = (TCComponentBOMWindowType)session.getTypeComponent("BOMWindow");
TCComponentRevisionRuleType rule = (TCComponentRevisionRuleType)session.getTypeComponent("RevisionRule");
bom_window[i] = type.create(rule.getDefaultRule());
/* Define the BOMWindow top line */
TCComponentBOMLine top_line = bom_window[i].setWindowTopLine(item[i], item_revision[i], null, null);
}
}
}
catch (Exception ex)
{
showErrorMessage("error 1 - " + ex);
return_value = -1;
}
// search for a dataset (CATPart or CATProduct and/or CATDrawing)
try
{
int nb = item_revision[i].getChildrenCount();
if (nb > 0)
{
AIFComponentContext[] aif_comp_cont = item_revision[i].getChildren();
for (int j = 0 ; j < nb ; j++)
{
InterfaceAIFComponent int_aif_comp = aif_comp_cont[j].getComponent();
if (int_aif_comp.getType().equals("CATPart"))
{
part_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("CATProduct"))
{
product_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("CATDrawing"))
{
drawing_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("ItemRevision Master"))
{
other[i] = (TCComponentForm)int_aif_comp;
}
}
}
}
catch (Exception ex)
{
showErrorMessage("error 2 - " + ex);
return_value = -1;
}
}
try
{
reader.close();
}
catch (Exception ex)
{
showErrorMessage("error 3 - " + ex);
}
return return_value;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Lets try this");
SampleIndependentSilentLUS test = new SampleIndependentSilentLUS();
//test.customerProcess();
}
}
There are two ways to get TCSession.
1) If you writing a Rich-Client Plugin
//numTry - number of attemts
private static TCSession getCurrentSession(int numTry) throws Exception {
try {
TCSession session = null;
ISessionService iss=null;
int numtry=numTry;
while (iss==null && numtry>0) {
iss = AifrcpPlugin.getSessionService();
numtry--;
}
session=(TCSession)iss.getSession("com.teamcenter.rac.kernel.TCSession");
return session;
}
catch (Exception ex) {
throw ex;
}
}
2) If you writing a stand-alone application, using SOA to work with Teamcenter API.
In this case, you need to connect teamcenter first. View "HelloTeamcenter" example in documentation for details.
did you get a solution for this?
SampleIndependentSilentLUS is a very good way of automating LUS process.but i prefer using the other class(SampleSilentLUS ) that can be called from command line because TCIC will automatically provide a TCSession
the session object you get from SOA(com.teamcenter.services.strong.core._2008_06.Session) is not compatible with RAC Session(com.teamcenter.rac.TCSession).
but if you use loose services(com.teamcenter.services.loose.core), i think you can simply typecast to TCSession
This is one of the most common application scenario that can be found all over the net. and I'm not asking any questions about the java codes that I did because I was successful in running it on my laptop where both the client and server part of the .java file resides. Rather I have had problem getting it to work in between two computers. I tried establishing physical connection using cross-over cable to connect two computers, and did a test to see if file transfers successfully and it did, however, keeping one Server part of the .java file in one computer and client part in the other, I tried to run the server first and then the client but it got a "access denied" error.
For reference here's my two .java files:
/* ChatClient.java */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClient {
private static int port = 5000; /* port to connect to */
private static String host = "localhost"; /* host to connect to (server's IP)*/
private static BufferedReader stdIn;
private static String nick;
/**
* Read in a nickname from stdin and attempt to authenticate with the
* server by sending a NICK command to #out. If the response from #in
* is not equal to "OK" go bacl and read a nickname again
*/
private static String getNick(BufferedReader in,
PrintWriter out) throws IOException {
System.out.print("Enter your nick: ");
String msg = stdIn.readLine();
out.println("NICK " + msg);
String serverResponse = in.readLine();
if ("SERVER: OK".equals(serverResponse)) return msg;
System.out.println(serverResponse);
return getNick(in, out);
}
public static void main (String[] args) throws IOException {
Socket server = null;
try {
server = new Socket(host, port);
} catch (UnknownHostException e) {
System.err.println(e);
System.exit(1);
}
stdIn = new BufferedReader(new InputStreamReader(System.in));
/* obtain an output stream to the server... */
PrintWriter out = new PrintWriter(server.getOutputStream(), true);
/* ... and an input stream */
BufferedReader in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
nick = getNick(in, out);
/* create a thread to asyncronously read messages from the server */
ServerConn sc = new ServerConn(server);
Thread t = new Thread(sc);
t.start();
String msg;
/* loop reading messages from stdin and sending them to the server */
while ((msg = stdIn.readLine()) != null) {
out.println(msg);
}
}
}
class ServerConn implements Runnable {
private BufferedReader in = null;
public ServerConn(Socket server) throws IOException {
/* obtain an input stream from the server */
in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
}
public void run() {
String msg;
try {
/* loop reading messages from the server and show them
* on stdout */
while ((msg = in.readLine()) != null) {
System.out.println(msg);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
and here's the ChatServer.java:
/* ChatServer.java */
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Hashtable;
public class ChatServer {
private static int port = 5000; /* port to listen on */
public static void main (String[] args) throws IOException
{
ServerSocket server = null;
try {
server = new ServerSocket(port); /* start listening on the port */
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.err.println(e);
System.exit(1);
}
Socket client = null;
while(true) {
try {
client = server.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
System.exit(1);
}
/* start a new thread to handle this client */
Thread t = new Thread(new ClientConn(client));
t.start();
}
}
}
class ChatServerProtocol {
private String nick;
private ClientConn conn;
/* a hash table from user nicks to the corresponding connections */
private static Hashtable<String, ClientConn> nicks =
new Hashtable<String, ClientConn>();
private static final String msg_OK = "OK";
private static final String msg_NICK_IN_USE = "NICK IN USE";
private static final String msg_SPECIFY_NICK = "SPECIFY NICK";
private static final String msg_INVALID = "INVALID COMMAND";
private static final String msg_SEND_FAILED = "FAILED TO SEND";
/**
* Adds a nick to the hash table
* returns false if the nick is already in the table, true otherwise
*/
private static boolean add_nick(String nick, ClientConn c) {
if (nicks.containsKey(nick)) {
return false;
} else {
nicks.put(nick, c);
return true;
}
}
public ChatServerProtocol(ClientConn c) {
nick = null;
conn = c;
}
private void log(String msg) {
System.err.println(msg);
}
public boolean isAuthenticated() {
return ! (nick == null);
}
/**
* Implements the authentication protocol.
* This consists of checking that the message starts with the NICK command
* and that the nick following it is not already in use.
* returns:
* msg_OK if authenticated
* msg_NICK_IN_USE if the specified nick is already in use
* msg_SPECIFY_NICK if the message does not start with the NICK command
*/
private String authenticate(String msg) {
if(msg.startsWith("NICK")) {
String tryNick = msg.substring(5);
if(add_nick(tryNick, this.conn)) {
log("Nick " + tryNick + " joined.");
this.nick = tryNick;
return msg_OK;
} else {
return msg_NICK_IN_USE;
}
} else {
return msg_SPECIFY_NICK;
}
}
/**
* Send a message to another user.
* #recepient contains the recepient's nick
* #msg contains the message to send
* return true if the nick is registered in the hash, false otherwise
*/
private boolean sendMsg(String recipient, String msg) {
if (nicks.containsKey(recipient)) {
ClientConn c = nicks.get(recipient);
c.sendMsg(nick + ": " + msg);
return true;
} else {
return false;
}
}
/**
* Process a message coming from the client
*/
public String process(String msg) {
if (!isAuthenticated())
return authenticate(msg);
String[] msg_parts = msg.split(" ", 3);
String msg_type = msg_parts[0];
if(msg_type.equals("MSG")) {
if(msg_parts.length < 3) return msg_INVALID;
if(sendMsg(msg_parts[1], msg_parts[2])) return msg_OK;
else return msg_SEND_FAILED;
} else {
return msg_INVALID;
}
}
}
class ClientConn implements Runnable {
private Socket client;
private BufferedReader in = null;
private PrintWriter out = null;
ClientConn(Socket client) {
this.client = client;
try {
/* obtain an input stream to this client ... */
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
/* ... and an output stream to the same client */
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.err.println(e);
return;
}
}
public void run() {
String msg, response;
ChatServerProtocol protocol = new ChatServerProtocol(this);
try {
/* loop reading lines from the client which are processed
* according to our protocol and the resulting response is
* sent back to the client */
while ((msg = in.readLine()) != null) {
response = protocol.process(msg);
out.println("SERVER: " + response);
}
} catch (IOException e) {
System.err.println(e);
}
}
public void sendMsg(String msg) {
out.println(msg);
}
}
Now, what should I do in order to run this two files from two computers given that I have the physical connection(TCP/IP) setup already??
Thanks in advance... :)
Sounds like it's quite possibly a firewall problem. Have you tried opening a hole in your firewall for port 1001?
Have you also looked at your java.policy and make sure that it is configured to allow local codebase to open sockets?
as mentioned in comment, you should not use port < 1025 for you applications, since they are always used in deamon processes. However you should test your program like this
1) if you get connection refused then you should check the exception properly, whether client program takes time before generating exception ( that mean request is going to server and then it's giving connection refused), in that case you should try java.policy put following in a file named java.policy
grant {
permission java.net.SocketPermission ":1024-65535",
"connect,accept";
permission java.net.SocketPermission ":80", "connect";
permission java.io.FilePermission "", "read,write,delete";
permission java.security.SecurityPermission "";
};
while compiling use this flag -Djava.security.policy=java.policy
more-over you should also try -Djava.rmi.server.hostname=IP, where IP is clien-ip for client.java and server-ip for server.java
2) if you are immediately getting exception at client side then your request is not going outside your pc, so client has some problem.
check the exception properly and post them over here.
3) though i've not got access denied error, but it seems to have port problem that might be solved using policy or port>1024.
post what are you getting now.