A requester is sending messages over a normal queue to a responder, indicating a dynamic queue it created as a reply queue. The responder puts these same messages on the reply queue. The responder retrieves all messages correctly.
For each message sent the requester obtains a message from the reply queue, but its body is filled with zeroes. Both programs are written in Java, using com.ibm.mq.allclient-9.2.2.0.jar. When I wrote the same in JavaScript with Node.js and ibmmq for node, everything worked fine.
Requester.java:
package com.hellerim.imq.comm.requester;
import static com.ibm.mq.constants.CMQC.MQENC_INTEGER_NORMAL;
import static com.ibm.mq.constants.CMQC.MQFMT_STRING;
import static com.ibm.mq.constants.CMQC.MQGMO_FAIL_IF_QUIESCING;
import static com.ibm.mq.constants.CMQC.MQGMO_NO_SYNCPOINT;
import static com.ibm.mq.constants.CMQC.MQGMO_NO_WAIT;
import static com.ibm.mq.constants.CMQC.MQGMO_WAIT;
import static com.ibm.mq.constants.CMQC.MQMT_REQUEST;
import static com.ibm.mq.constants.CMQC.MQOO_FAIL_IF_QUIESCING;
import static com.ibm.mq.constants.CMQC.MQOO_INPUT_EXCLUSIVE;
import static com.ibm.mq.constants.CMQC.MQOO_OUTPUT;
import static com.ibm.mq.constants.CMQC.MQPMO_NO_SYNCPOINT;
import static com.ibm.mq.constants.CMQC.MQRC_NO_MSG_AVAILABLE;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import io.netty.util.CharsetUtil;
import net.jcip.annotations.GuardedBy;
public class Requester
{
private static final int WAIT_WHILE_EMPTY = 100; // ms
private static int MAX_MILLIS_BETWEEN_REQUESTS = 100;
private static int LONG_WIDTH_IN_HEX_CHARS = 16;
private static final Charset charset = CharsetUtil.ISO_8859_1;
private MQQueueManager qMgr;
private final MQQueue requestQueue;
private final String queueNamePattern = "TEST.SESSION.*";
private String replyQueueName;
private final MQQueue replyQueue;
private final MQGetMessageOptions getOptions = new MQGetMessageOptions();
private static final String MQ_MANAGER = "MY_QM";
private static final String REQUEST_QUEUE = "TEST.REQUESTS";
private static final String MODEL_QUEUE = "TEST.SESSION.MODEL";
final private Object locker = new Object();
#GuardedBy("this")
boolean stopped = false;
int rcvd = 0;
public static void main(String[] args) {
try {
Requester rq = new Requester(MQ_MANAGER, REQUEST_QUEUE, MODEL_QUEUE);
List<String> poem = writePoem();
Random requestIds = new Random();
Random delays = new Random(1000);
int cnt = 0;
int position = 0;
for (int i = 0; i < 50; ++i) {
if (i == poem.size()) {
int requestId = requestIds.nextInt(99999) + 1;
String text = poem.stream().collect(Collectors.joining("\n"));
String request = appRequestFrom(text, requestId);
rq.write(request);
System.out.println("Requester: sent request no " + (++cnt) + " - " + requestId);
}
position %= poem.size();
String line = poem.get(position);
int requestId = requestIds.nextInt(99999) + 1;
String request = appRequestFrom(line, requestId);
rq.write(request);
System.out.println("Requester: sent request no " + (++cnt) + " - " + requestId);
position++;
try {
Thread.sleep((long) Math.ceil((Math.pow(
delays.nextDouble(), 4) * MAX_MILLIS_BETWEEN_REQUESTS) + 1));
} catch (InterruptedException e) {
// ignore
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// ignore
}
rq.close();
} catch (MQException e) {
e.printStackTrace();
}
}
public Requester(String mqManagerName, String requestQueueName, String modelQueueName) throws MQException {
super();
System.out.println("Requester: establishing mq session (mq manager: " + mqManagerName +
"/ request queue: " + requestQueueName + " / model queue: " + modelQueueName +")");
qMgr = new MQQueueManager(mqManagerName);
// get request queue
int openOptions = MQOO_OUTPUT + MQOO_FAIL_IF_QUIESCING;
requestQueue = qMgr.accessQueue(requestQueueName, openOptions);
// get dynamic reply queue
int inputOptions = MQOO_INPUT_EXCLUSIVE + MQOO_FAIL_IF_QUIESCING;
replyQueue = new MQQueue(qMgr,
modelQueueName,
inputOptions,
"",
queueNamePattern,
"");
replyQueueName = replyQueue.getName();
System.out.println("Requester: created temporary reply queue " + replyQueueName);
getOptions.options = MQGMO_NO_SYNCPOINT +
MQGMO_NO_WAIT +
MQGMO_FAIL_IF_QUIESCING;
// catch-up (for those replies not retrieved after a request was put)
Executors.newSingleThreadExecutor().execute(new Runnable() {
#Override
public void run() {
// read options
MQGetMessageOptions getOptions = new MQGetMessageOptions();
getOptions.options = MQGMO_NO_SYNCPOINT +
MQGMO_WAIT +
MQGMO_FAIL_IF_QUIESCING;
getOptions.waitInterval = WAIT_WHILE_EMPTY;
while(proceed()) {
try {
if (!retrieveMessage(getOptions)) {
try {
Thread.sleep(getOptions.waitInterval);
} catch (InterruptedException e1) {}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private boolean retrieveMessage(MQGetMessageOptions getOptions) throws IOException {
MQMessage msg = new MQMessage();
try {
msg.clearMessage();
msg.seek(0);
replyQueue.get(msg, getOptions);
System.out.println("Requester: reply no " + ++rcvd + " received - id: " +
Long.parseLong(new String(msg.messageId, Charset.forName("ISO_8859_1")), 16));
byte[] buf = new byte[msg.getDataLength()];
String message = new String(buf, charset);
System.out.println("Requester: message received:\n" + message);
} catch (MQException e) {
if (e.reasonCode == MQRC_NO_MSG_AVAILABLE) {
return false;
}
}
return true;
}
public byte[] write(String message) {
int positionRequestId = 24;
int endIndex = positionRequestId + 16;
CharSequence requestId = message.substring(positionRequestId, endIndex);
StringBuffer sb = new StringBuffer("00000000");
sb.append(requestId);
byte[] id = sb.toString().getBytes(charset);
MQMessage mqMsg = new MQMessage();
mqMsg.characterSet = 819;
mqMsg.encoding = MQENC_INTEGER_NORMAL;
mqMsg.format = MQFMT_STRING;
mqMsg.messageType = MQMT_REQUEST;
mqMsg.messageId = id;
mqMsg.correlationId = id;
mqMsg.replyToQueueName = replyQueueName;
try {
mqMsg.writeString(message);
mqMsg.seek(0);
MQPutMessageOptions pmo = new MQPutMessageOptions();
pmo.options = MQPMO_NO_SYNCPOINT;
requestQueue.put(mqMsg, pmo);
} catch (IOException e) {
e.printStackTrace();
} catch (MQException e) {
e.printStackTrace();
}
// try to read from reply queue fail immediately
try {
retrieveMessage(getOptions);
} catch (IOException e) {
e.printStackTrace();
}
return id;
}
public void close() {
stop();
try {
Thread.sleep(2 * WAIT_WHILE_EMPTY);
} catch (InterruptedException e1) {
// ignore
}
try {
if (requestQueue != null) {
requestQueue.close();
}
if (qMgr != null) {
qMgr.disconnect();
}
} catch (MQException e) {
// ignore
}
}
public boolean proceed() {
synchronized(locker) {
return !stopped;
}
}
public void stop() {
synchronized(locker) {
stopped = true;
}
}
private static List<String> writePoem() {
List<String> poem = new ArrayList<>();
poem.add("Das Nasobem");
poem.add("von Joachim Ringelnatz");
poem.add("");
poem.add("Auf seiner Nase schreitet");
poem.add("einher das Nasobem,");
poem.add("von seineme Kind begleitet -");
poem.add("es steht noch nicht im Brehm.");
poem.add("");
poem.add("Es steht noch nicht im Meyer");
poem.add("und auch im Brockhaus nicht -");
poem.add("es tritt aus meiner Leier");
poem.add("zum ersten Mal ans Licht.");
poem.add("");
poem.add("Auf seiner Nase schreitet");
poem.add("- wie schon gesagt - seitdem");
poem.add("von seinem Kind begleitet");
poem.add("einher das Nasobem.");
poem.add("");
poem.add("");
return poem;
}
private static String iToHex(int num, int places) {
StringBuilder sb = new StringBuilder();
char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
for (int i = 0; i < places; ++i) {
sb.append(digits[num % places]);
num /= places;
}
return sb.reverse().toString();
}
private static String iToHex(int num) {
return iToHex(num, LONG_WIDTH_IN_HEX_CHARS);
}
private static String appRequestFrom(String msgBody, int requestId) {
int headerLength = 72;
// includes message body length field here!
int bodyLength = msgBody.length();
StringBuilder sb = new StringBuilder();
sb.append("GHI "); // magic
sb.append("1"); // version major
sb.append("0"); // version minor
sb.append("0"); // flags
sb.append("1"); // app message type SYNCHRONOUS REQUEST
sb.append(iToHex(headerLength + bodyLength)); // message length
sb.append(iToHex(requestId)); // request id
sb.append(iToHex(0)); // timeout
sb.append(iToHex(bodyLength)); // message body length
sb.append(msgBody); // message body
return sb.toString();
}
}
Responder.java:
package com.hellerim.imq.comm.responder;
import static com.ibm.mq.constants.CMQC.*;
import java.io.EOFException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import io.netty.util.CharsetUtil;
import net.jcip.annotations.GuardedBy;
public class Responder
{
private MQQueueManager qMgr;
private MQQueue requestQueue;
private Map<String, MQQueue> replyQueues = new HashMap<>();
private final Object locker = new Object();
static final private int WAIT_WHILE_EMPTY = 100; // ms
#GuardedBy("locker")
private boolean stopped = false;
Thread fetcherThread = null;
private final static byte MESSAGE_TYPE_REPLY = 52; // '4'
public final static String MQ_MANAGER = "MY_QM";
public final static String REQUEST_QUEUE = "TEST.REQUESTS";
public static void main( String[] args ) throws MQException, IOException
{
System.out.println( "running reponder application" );
try {
new Responder(MQ_MANAGER, REQUEST_QUEUE).start();
} catch(Exception e) {
e.printStackTrace();
}
}
public Responder(String mqManagerName, String requestQueueName) throws MQException {
System.out.println("establishing mq session (mq manager: " + mqManagerName +
" / request queue: " + requestQueueName + ")");
qMgr = new MQQueueManager(mqManagerName);
int openOptions = MQOO_INPUT_SHARED + MQOO_FAIL_IF_QUIESCING;
requestQueue = qMgr.accessQueue(requestQueueName, openOptions);
}
public MQQueue getReplyQueue(String replyQueueName) throws MQException {
if (replyQueues.containsKey(replyQueueName)) {
return replyQueues.get(replyQueueName);
}
int openOptions = MQOO_OUTPUT + MQOO_FAIL_IF_QUIESCING;
MQQueue replyQueue = qMgr.accessQueue(replyQueueName, openOptions);
replyQueues.put(replyQueueName, replyQueue);
System.out.println("Responder: opened dynamic reply queue");
return replyQueue;
}
private void start() throws IOException {
Runnable fetcher = new Runnable() {
#Override
public void run() {
int cnt = 0;
while(proceed()) {
MQMessage msg = new MQMessage();
try {
//msg.clearMessage();
MQGetMessageOptions getOptions = new MQGetMessageOptions();
getOptions.options = MQGMO_NO_SYNCPOINT +
MQGMO_WAIT +
MQGMO_FAIL_IF_QUIESCING;
getOptions.waitInterval = WAIT_WHILE_EMPTY;
requestQueue.get(msg, getOptions);
System.out.println("Responder: message no " + ++cnt + " received");
MQQueue replyQueue = null;
try {
replyQueue = getReplyQueue(msg.replyToQueueName);
} catch(MQException e) {
if (e.completionCode == MQCC_FAILED && e.reasonCode == MQRC_UNKNOWN_OBJECT_NAME) {
// dynamic reply queue does not exist any more => message out of date
continue;
}
throw e;
}
// set message type for reply
if (msg.getDataLength() < 56) {
System.out.println("invalid message:");
System.out.println(Msg2Text(msg));
continue;
}
System.out.println(Msg2Text(msg));
int typePosition = 7;
msg.seek(typePosition);
msg.writeByte(MESSAGE_TYPE_REPLY);
msg.seek(0);
String text = Msg2Text(msg);
MQMessage msgOut = new MQMessage();
msgOut.characterSet = 819;
msgOut.encoding = MQENC_INTEGER_NORMAL;
msgOut.format = MQFMT_STRING;
msgOut.messageType = MQMT_REPLY;
msgOut.messageId = msg.messageId;
msgOut.correlationId = msg.correlationId;
msgOut.seek(0);
msgOut.writeString(text);
msgOut.seek(0);
System.out.println(text);
// System.out.println("Responder: message received");
MQPutMessageOptions pmo = new MQPutMessageOptions(); // accept the defaults, same
pmo.options = MQPMO_NO_SYNCPOINT;
replyQueue.put(msgOut, pmo);
System.out.println("Responder: message no " + cnt + " returned");
} catch (MQException e) {
if (e.reasonCode == MQRC_NO_MSG_AVAILABLE) {
; // NOOP
} else {
try {
msg.seek(0);
System.out.println(msg);
} catch (EOFException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
e.printStackTrace();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {}
}
} catch (IOException e) {
e.printStackTrace();
}
}
shutdown();
}
};
Thread task = new Thread(fetcher);
task.run();
System.out.print("press <ENTER> to terminate ");
System.in.read();
System.out.println();
synchronized(locker) {
stopped = true;
}
try {
task.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String Msg2Text(MQMessage msg) {
int length;
String text = "";
try {
length = msg.getDataLength();
byte[] buf = new byte[length];
msg.seek(0);
msg.readFully(buf);
text = new String(buf, CharsetUtil.ISO_8859_1);
msg.seek(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return text;
}
private boolean proceed() {
synchronized(locker) {
return !stopped;
}
}
private void shutdown() {
System.out.print("\nshutting down responder... ");
for (MQQueue queue : replyQueues.values()) {
try {
queue.close();
} catch (MQException e) { }
}
replyQueues.clear();
try {
qMgr.close();
} catch (MQException e) { }
System.out.println("done.");
}
}
Is there any idea what might be wrong?
It looks like you have created a buffer the right size for the message data and printed that, without moving the data into it.
In retrieveMessage:
byte[] buf = new byte[msg.getDataLength()];
String message = new String(buf, charset);
System.out.println("Requester: message received:\n" + message);
You might need to call the readFully (or similar) method to get the data.
If you know that your message payload is text (string) then you can do this:
String msgStr = msg.readStringOfByteLength(msg.getMessageLength());
System.out.println("Requester: message received:\n" + msgStr);
I have a simple parking-lot simulation which simulates the entry and exit of customers. A class called entrySimulation is used as the producer and the exitSimulation consumes the message and peforms checks to see if a customer should enter.The entry simulation class is as follows:
package parking.experiment_2;
public class entrySimulation implements Runnable {
public static void main(String[] args) {
ScheduledExecutorService entrySimulation = Executors.newScheduledThreadPool(1);
entrySimulation.scheduleAtFixedRate(new entrySimulation(), 2, 4, TimeUnit.SECONDS);
}
///PRODUCER CLASS
int numOfRuns = 100;//1000 runs
public securityGuard_exp_1 myGuard = new securityGuard_exp_1();
//System.out.println("Customer Exiting");
//Thread.sleep(randomTime.nextInt(5000));
public meterClass_exp_1 myMeter = new meterClass_exp_1();
//Details are only set if there is space available
//The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min
//instantiation of the info generator class
public infoGenerator_exp_1 info = new infoGenerator_exp_1();
//Generating random Car info
//spot_exp_1 mySpot = new spot_exp_1();
//Use an iterator
public List<ticketClass_exp_1> ticketArray = new ArrayList<>();
Iterator<ticketClass_exp_1> iter = ticketArray.iterator();
public final spot_exp_1 availableSpot = new spot_exp_1();
//Random time generator
Random randomTime = new Random();
//List<Employee> empList = new ArrayList<>();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos;
{
try {
oos = new ObjectOutputStream(bos);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public List<ticketClass_exp_1> randomEntry() throws IOException, TimeoutException {
Gson gson = new GsonBuilder().create();
carClass_exp_2 car = null;
String queueName = "exitQueue";
String message = null;
for (int currentRuns = 0; currentRuns < numOfRuns; currentRuns++) {
String plateNumber = info.plateGenerator();
String carModel = info.modelGenerator();
String color = info.colorGenerator();
myMeter.setPurchasedMinutes(randomTime.nextInt(30));
carClass_exp1_1 vehicle = new carClass_exp1_1(carModel, color, plateNumber, randomTime.nextInt(2880));
ticketClass_exp_1 myTicket = myGuard.ticketGenerator(vehicle, myMeter);
//Generating details
myTicket.setmeter(myMeter);
myTicket.setCar(vehicle);
myTicket.getCar().plateSetter(plateNumber);
myTicket.getCar().colorSetter(color);
myTicket.getCar().modelSeter(carModel);
//myTicket.getGuard().setguardName("Phill");
//myTicket.getGuard().setBadgeNumber("AF170");
int spotAvail = availableSpot.assignSpot();
myTicket.setSlotNum(spotAvail);
message = gson.toJson(myTicket);
ticketArray.add(myTicket);
return ticketArray;
}
public void publishMessage( ticketClass_exp_1 tickArray ) throws IOException, TimeoutException{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(tickArray);
///Direct exchange from enrtySimulation to exit simulation -Used to inform customer exit
//Topic exchange from entrySimulation to individual car park types . EG: Mercedes benz lot, SRT lot, ...
String exchangeName = "entryExchange";
String routingKey = "exitKey";
//Creating a connection factory
ConnectionFactory factory = new ConnectionFactory();
try(Connection conVar = factory.newConnection()){
Channel channelCon = conVar.createChannel();
//Exchange declaration
channelCon.exchangeDeclare(exchangeName,"customerEntry");
channelCon.basicPublish(exchangeName,routingKey,null,bos.toByteArray());
//System.out.println(message);
System.out.println("Customer Entered");
}catch(Exception e){}
}
#Override
public void run() {
ticketClass_exp_1 message = null;
try {
message = (ticketClass_exp_1) randomEntry();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
//Publishing message
try {
publishMessage(message);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
}
}
The consumer then consumes the array as follows;
public class exitSimulation implements Runnable {
//public exitSimulation(Channel channel) {
//super(channel);
//String storedMessage;
//}
public String reciver() throws Exception {
ConnectionFactory factory = new ConnectionFactory();
Connection connection = factory.newConnection();
//Creat connection
Channel channel = connection.createChannel();
//create channel
String recievQueue = channel.queueDeclare().getQueue();
System.out.println(" Awaiting Cars");
consumeConvert consumer=new consumeConvert(channel);
channel.basicConsume(recievQueue,true,consumer);
// using
return consumer.getFormatMessage();
}
public class consumeConvert extends DefaultConsumer {
private String storedMessage;
public consumeConvert(Channel channelReceiver) {
super(channelReceiver);
}
public String getFormatMessage() {
return storedMessage;
}
#Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] messageBody)
throws IOException {
String message = new String(messageBody, "UTF-8");
System.out.println(" MSG RECIEVED: " + message + "'");
storedMessage = message; // store message here
}
}
public static void main(String[] args) {
//Receives message when customers are entering - Contains customer information e.g. customer x is entering.. details ....
// Adds them to a local array
// IF any customers checkParking(ExitCar, meterOut) == true : CUSTOMER EXITS
//
//
//Get the messages and pass as function inputs
/*
*
public class MyConsumer extends DefaultConsumer {
private String storedMessage;
public MyConsumer(Object channelRecv) {
super(channelRecv);
}
public String getStoredMessage() {
return storedMessage;
}
#Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
storedMessage = message; // store message here
}
}
*
*
* Perfrom checks and send exiting car
* */
//String qName = channelCon.queueDeclare().getQueue();
//Binding the queue
//channelCon.queueBind(qName, exchangeName, routingKey);
Collection<ticketClass_exp_2> ticketArray = new ArrayList<ticketClass_exp_2>();
int availableSpot = 0;
Random randomTime = new Random();
//System.out.println(availableSpot.getSpotNum());
for (ticketClass_exp_2 tick : ticketArray) {
if (ticketArray.size() != 0) {
meterClass_exp_2 meterOut = tick.getMeter();
carClass_exp_2 ExitCar = tick.getCar();
securityGuard_exp_2 myGuard2 = new securityGuard_exp_2();
//System.out.println("IND" + tick.slotNum);
if (myGuard2.checkParking(ExitCar, meterOut)) {
try {
Thread.sleep(randomTime.nextInt(2000));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("\nCustomer " + ExitCar.plateGetter() + " is exiting the carpark...");
double penaltyVal = tick.getPenalty();
System.out.println("FINE: " + penaltyVal);
System.out.println("==================================================================");
}
}
if (availableSpot == 16) {
System.out.println("Carpark full, No cars allowed unitl a space is free");
//Send a message
//System.out.println("Total Waiting customers: " + bouncedCustomers);
}
//} catch (Exception e) {
//}
//currentRuns += 1;
///Thread.join(5000);
}
}
The array recived is of type ticketArray. How can I make this work please?
Any enhancement recommendations are welcome
MessageCreator: Encapsulate and resolve ports and device unique identifiers.
public class MessageCreator {
private static final String HEADER_PORT = "to port:";
private static final String HEADER_SN = "My sn:";
public static String buildWithPort(int port) {
return HEADER_PORT + port;
}
public static int parsePort(String data) {
if (data.startsWith(HEADER_PORT)) {
return Integer.parseInt(data.substring(HEADER_PORT.length()));
}
return -1;
}
public static String buildWithSn(String sn) {
return HEADER_SN + sn;
}
public static String parseSn(String data) {
if (data.startsWith(HEADER_SN)) {
return data.substring(HEADER_SN.length());
}
return null;
}
}
UdpProvider: Loop to listen to a specific port, then parse the received data, determine whether the data conforms to the predetermined format, get the sender's response port from it, and respond with the uniquely identified UUID value to the UDP searcher.
public class UdpProvider {
public static void main(String[] args) throws IOException {
String sn = UUID.randomUUID().toString();
Provider provider = new Provider(sn);
provider.start();
// Warning: Result of 'InputStream.read()' is ignored
System.in.read();
provider.exit();
}
private static class Provider extends Thread {
private DatagramSocket ds = null;
private boolean done = false;
private final String sn;
public Provider(String sn) {
super();
this.sn = sn;
}
#Override
public void run() {
super.run();
try {
ds = new DatagramSocket(20000);
while (!done) {
final byte[] buf = new byte[512];
DatagramPacket receivePak = new DatagramPacket(buf, buf.length);
ds.receive(receivePak);
String ip = receivePak.getAddress().getHostAddress();
int port = receivePak.getPort();
byte[] receivePakData = receivePak.getData();
String receiveData = new String(receivePakData, 0, /*receivePakData.length*/receivePak.getLength());
System.out.println("received from -> ip: " + ip + ", port: " + port + ", data: " + receiveData);
int responsePort = MessageCreator.parsePort(receiveData.trim());
if (responsePort != -1) {
String responseData = MessageCreator.buildWithSn(sn);
byte[] bytes = responseData.getBytes(StandardCharsets.UTF_8);
DatagramPacket responsePak = new DatagramPacket(bytes, bytes.length,
/*InetAddress.getLocalHost()*/
receivePak.getAddress(),
responsePort);
ds.send(responsePak);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}
public void exit() {
done = true;
close();
}
public void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
}
}
UdpSearcher: Listening to a specific port and sending a LAN broadcast, sending a broadcast sets the listening port in the data, so you need to turn on listening first to finish before you can send a broadcast, and once you receive the response data, you can parse the device information
public class UdpSearcher {
private static final int LISTENER_PORT = 30000;
public static void main(String[] args) throws IOException, InterruptedException {
Listener listener = listen();
sendBroadcast();
// Warning: Result of 'InputStream.read()' is ignored
System.in.read();
List<Device> deviceList = listener.getDevicesAndClose();
for (Device device : deviceList) {
System.out.println(device);
}
}
public static void sendBroadcast() throws IOException {
DatagramSocket ds = new DatagramSocket();
String sendData = MessageCreator.buildWithPort(LISTENER_PORT);
byte[] sendDataBytes = sendData.getBytes(StandardCharsets.UTF_8);
DatagramPacket sendPak = new DatagramPacket(sendDataBytes, sendDataBytes.length);
sendPak.setAddress(InetAddress.getByName("255.255.255.255"));
sendPak.setPort(20000);
ds.send(sendPak);
ds.close();
}
public static Listener listen() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
Listener listener = new Listener(LISTENER_PORT, countDownLatch);
listener.start();
countDownLatch.await();
return listener;
}
private static class Listener extends Thread {
private final int listenPort;
private DatagramSocket ds = null;
private boolean done = false;
private final CountDownLatch countDownLatch;
private List<Device> devices = new ArrayList<>();
public Listener(int listenPort, CountDownLatch countDownLatch) {
super();
this.listenPort = listenPort;
this.countDownLatch = countDownLatch;
}
#Override
public void run() {
super.run();
countDownLatch.countDown();
try {
ds = new DatagramSocket(listenPort);
while (!done) {
final byte[] buf = new byte[512];
DatagramPacket receivePak = new DatagramPacket(buf, buf.length);
ds.receive(receivePak);
String ip = receivePak.getAddress().getHostAddress();
int port = receivePak.getPort();
byte[] data = receivePak.getData();
String receiveData = new String(data, 0, /*data.length*/receivePak.getLength());
String sn = MessageCreator.parseSn(receiveData);
System.out.println("received from -> ip: " + ip + ", port: " + port + ", data: " + receiveData);
if (sn != null) {
Device device = new Device(ip, port, sn);
devices.add(device);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}
public void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
public List<Device> getDevicesAndClose() {
done = true;
close();
return devices;
}
}
private static class Device {
private String ip;
private int port;
private String sn;
public Device(String ip, int port, String sn) {
this.ip = ip;
this.port = port;
this.sn = sn;
}
#Override
public String toString() {
return "Device{" +
"ip='" + ip + '\'' +
", port=" + port +
", sn='" + sn + '\'' +
'}';
}
}
}
UdpProvider and UdpSearcher worked fine and printed corrresponding data until I input a char sequence from keyboard follwed by pressing Enter key on each console window, both threw an exception on this line ds.receive(receivePak); :
5 with jdk1.8 when I run the project. I got an Exception ExceptionInInitializerError. But when I run the same project in jdk1.6. It is running successfully. That error message as
Exception in thread "main" java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at java.lang.Class.newInstance(Class.java:442)
at org.ofbiz.entity.GenericDelegator.initEntityEcaHandler(GenericDelegator.java:339)
at org.ofbiz.entity.DelegatorFactory.getDelegator(DelegatorFactory.java:42)
at org.ofbiz.catalina.container.CatalinaContainer.init(CatalinaContainer.java:175)
at org.ofbiz.base.container.ContainerLoader.loadContainer(ContainerLoader.java:189)
at org.ofbiz.base.container.ContainerLoader.load(ContainerLoader.java:66)
at org.ofbiz.base.start.Start.initStartLoaders(Start.java:260)
at org.ofbiz.base.start.Start.init(Start.java:97)
at org.ofbiz.base.start.Start.main(Start.java:411)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5747
at org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.readClass(Unknown Source)
at org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.accept(Unknown Source)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:308)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:331)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.createClassInfoFromStream(AsmClassInfo.java:790)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:273)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getInterfaces(AsmClassInfo.java:619)
at org.codehaus.aspectwerkz.reflect.ClassInfoHelper.implementsInterface(ClassInfoHelper.java:56)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.collectCustomProceedMethods(AbstractJoinPointCompiler.java:237)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.collectCustomProceedMethods(AbstractJoinPointCompiler.java:208)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.initialize(AbstractJoinPointCompiler.java:149)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.(AbstractJoinPointCompiler.java:133)
at org.codehaus.aspectwerkz.transform.inlining.compiler.MethodExecutionJoinPointCompiler.(MethodExecutionJoinPointCompiler.java:33)
at org.codehaus.aspectwerkz.transform.inlining.compiler.JoinPointFactory.compileJoinPoint(JoinPointFactory.java:86)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager$CompiledJoinPoint.(JoinPointManager.java:262)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager.compileJoinPoint(JoinPointManager.java:251)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager.loadJoinPoint(JoinPointManager.java:118)
at org.ofbiz.entityext.eca.DelegatorEcaHandler.aw$initJoinPoints(DelegatorEcaHandler.java)
at org.ofbiz.entityext.eca.DelegatorEcaHandler.(DelegatorEcaHandler.java)
... 13 more"
I found two files are problem when I run the project in jdk1.8 that coding files are:
CatalinaContainer.java
/**
* CatalinaContainer - Tomcat 5
*
*/
public class CatalinaContainer implements Container {
public static final String CATALINA_HOSTS_HOME = System.getProperty("ofbiz.home") + "/framework/catalina/hosts";
public static final String J2EE_SERVER = "OFBiz Container 3.1";
public static final String J2EE_APP = "OFBiz";
public static final String module = CatalinaContainer.class.getName();
protected static Map<String, String> mimeTypes = new HashMap<String, String>();
// load the JSSE propertes (set the trust store)
static {
SSLUtil.loadJsseProperties();
}
protected Delegator delegator = null;
protected Embedded embedded = null;
protected Map<String, ContainerConfig.Container.Property> clusterConfig = new HashMap<String, ContainerConfig.Container.Property>();
protected Map<String, Engine> engines = new HashMap<String, Engine>();
protected Map<String, Host> hosts = new HashMap<String, Host>();
protected boolean contextReloadable = false;
protected boolean crossContext = false;
protected boolean distribute = false;
protected boolean enableDefaultMimeTypes = true;
protected String catalinaRuntimeHome;
/**
* #see org.ofbiz.base.container.Container#init(java.lang.String[], java.lang.String)
*/
public void init(String[] args, String configFile) throws ContainerException {
// get the container config
ContainerConfig.Container cc = ContainerConfig.getContainer("catalina-container", configFile);
if (cc == null) {
throw new ContainerException("No catalina-container configuration found in container config!");
}
// embedded properties
boolean useNaming = ContainerConfig.getPropertyValue(cc, "use-naming", false);
//int debug = ContainerConfig.getPropertyValue(cc, "debug", 0);
// grab some global context settings
this.delegator = DelegatorFactory.getDelegator(ContainerConfig.getPropertyValue(cc, "delegator-name", "default"));
this.contextReloadable = ContainerConfig.getPropertyValue(cc, "apps-context-reloadable", false);
this.crossContext = ContainerConfig.getPropertyValue(cc, "apps-cross-context", true);
this.distribute = ContainerConfig.getPropertyValue(cc, "apps-distributable", true);
this.catalinaRuntimeHome = ContainerConfig.getPropertyValue(cc, "catalina-runtime-home", "runtime/catalina");
// set catalina_home
System.setProperty("catalina.home", System.getProperty("ofbiz.home") + "/" + this.catalinaRuntimeHome);
// configure JNDI in the StandardServer
StandardServer server = (StandardServer) ServerFactory.getServer();
try {
server.setGlobalNamingContext(new InitialContext());
} catch (NamingException e) {
throw new ContainerException(e);
}
// create the instance of Embedded
embedded = new Embedded();
embedded.setUseNaming(useNaming);
// create the engines
List<ContainerConfig.Container.Property> engineProps = cc.getPropertiesWithValue("engine");
if (UtilValidate.isEmpty(engineProps)) {
throw new ContainerException("Cannot load CatalinaContainer; no engines defined!");
}
for (ContainerConfig.Container.Property engineProp: engineProps) {
createEngine(engineProp);
}
// load the web applications
loadComponents();
// create the connectors
List<ContainerConfig.Container.Property> connectorProps = cc.getPropertiesWithValue("connector");
if (UtilValidate.isEmpty(connectorProps)) {
throw new ContainerException("Cannot load CatalinaContainer; no connectors defined!");
}
for (ContainerConfig.Container.Property connectorProp: connectorProps) {
createConnector(connectorProp);
}
try {
embedded.initialize();
} catch (LifecycleException e) {
throw new ContainerException(e);
}
}
public boolean start() throws ContainerException {
// Start the embedded server
try {
embedded.start();
} catch (LifecycleException e) {
throw new ContainerException(e);
}
for (Connector con: embedded.findConnectors()) {
ProtocolHandler ph = con.getProtocolHandler();
if (ph instanceof Http11Protocol) {
Http11Protocol hph = (Http11Protocol) ph;
Debug.logInfo("Connector " + hph.getProtocols() + " # " + hph.getPort() + " - " +
(hph.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
} else {
Debug.logInfo("Connector " + con.getProtocol() + " # " + con.getPort() + " - " +
(con.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
}
}
Debug.logInfo("Started " + ServerInfo.getServerInfo(), module);
return true;
}
protected Engine createEngine(ContainerConfig.Container.Property engineConfig) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Engine without Embedded instance!");
}
ContainerConfig.Container.Property defaultHostProp = engineConfig.getProperty("default-host");
if (defaultHostProp == null) {
throw new ContainerException("default-host element of server property is required for catalina!");
}
String engineName = engineConfig.name;
String hostName = defaultHostProp.value;
StandardEngine engine = (StandardEngine) embedded.createEngine();
engine.setName(engineName);
engine.setDefaultHost(hostName);
// set the JVM Route property (JK/JK2)
String jvmRoute = ContainerConfig.getPropertyValue(engineConfig, "jvm-route", null);
if (jvmRoute != null) {
engine.setJvmRoute(jvmRoute);
}
// create the default realm -- TODO: make this configurable
String dbConfigPath = "catalina-users.xml";
MemoryRealm realm = new MemoryRealm();
realm.setPathname(dbConfigPath);
engine.setRealm(realm);
// cache the engine
engines.put(engine.getName(), engine);
// create a default virtual host; others will be created as needed
Host host = createHost(engine, hostName);
hosts.put(engineName + "._DEFAULT", host);
// configure clustering
List<ContainerConfig.Container.Property> clusterProps = engineConfig.getPropertiesWithValue("cluster");
if (clusterProps != null && clusterProps.size() > 1) {
throw new ContainerException("Only one cluster configuration allowed per engine");
}
if (UtilValidate.isNotEmpty(clusterProps)) {
ContainerConfig.Container.Property clusterProp = clusterProps.get(0);
createCluster(clusterProp, host);
clusterConfig.put(engineName, clusterProp);
}
// request dumper valve
boolean enableRequestDump = ContainerConfig.getPropertyValue(engineConfig, "enable-request-dump", false);
if (enableRequestDump) {
RequestDumperValve rdv = new RequestDumperValve();
engine.addValve(rdv);
}
// configure the CrossSubdomainSessionValve
boolean enableSessionValve = ContainerConfig.getPropertyValue(engineConfig, "enable-cross-subdomain-sessions", false);
if (enableSessionValve) {
CrossSubdomainSessionValve sessionValve = new CrossSubdomainSessionValve();
engine.addValve(sessionValve);
}
// configure the access log valve
String logDir = ContainerConfig.getPropertyValue(engineConfig, "access-log-dir", null);
AccessLogValve al = null;
if (logDir != null) {
al = new AccessLogValve();
if (!logDir.startsWith("/")) {
logDir = System.getProperty("ofbiz.home") + "/" + logDir;
}
File logFile = new File(logDir);
if (!logFile.isDirectory()) {
throw new ContainerException("Log directory [" + logDir + "] is not available; make sure the directory is created");
}
al.setDirectory(logFile.getAbsolutePath());
}
// configure the SslAcceleratorValve
String sslAcceleratorPortStr = ContainerConfig.getPropertyValue(engineConfig, "ssl-accelerator-port", null);
if (UtilValidate.isNotEmpty(sslAcceleratorPortStr)) {
Integer sslAcceleratorPort = Integer.valueOf(sslAcceleratorPortStr);
SslAcceleratorValve sslAcceleratorValve = new SslAcceleratorValve();
sslAcceleratorValve.setSslAcceleratorPort(sslAcceleratorPort);
engine.addValve(sslAcceleratorValve);
}
String alp2 = ContainerConfig.getPropertyValue(engineConfig, "access-log-pattern", null);
if (al != null && !UtilValidate.isEmpty(alp2)) {
al.setPattern(alp2);
}
String alp3 = ContainerConfig.getPropertyValue(engineConfig, "access-log-prefix", null);
if (al != null && !UtilValidate.isEmpty(alp3)) {
al.setPrefix(alp3);
}
boolean alp4 = ContainerConfig.getPropertyValue(engineConfig, "access-log-resolve", true);
if (al != null) {
al.setResolveHosts(alp4);
}
boolean alp5 = ContainerConfig.getPropertyValue(engineConfig, "access-log-rotate", false);
if (al != null) {
al.setRotatable(alp5);
}
if (al != null) {
engine.addValve(al);
}
embedded.addEngine(engine);
return engine;
}
protected Host createHost(Engine engine, String hostName) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Host without Embedded instance!");
}
Host host = embedded.createHost(hostName, CATALINA_HOSTS_HOME);
host.setDeployOnStartup(true);
host.setAutoDeploy(true);
host.setRealm(engine.getRealm());
engine.addChild(host);
hosts.put(engine.getName() + hostName, host);
return host;
}
protected Cluster createCluster(ContainerConfig.Container.Property clusterProps, Host host) throws ContainerException {
String defaultValveFilter = ".*.gif;.*.js;.*.jpg;.*.htm;.*.html;.*.txt;";
ReplicationValve clusterValve = new ReplicationValve();
clusterValve.setFilter(ContainerConfig.getPropertyValue(clusterProps, "rep-valve-filter", defaultValveFilter));
String mcb = ContainerConfig.getPropertyValue(clusterProps, "mcast-bind-addr", null);
String mca = ContainerConfig.getPropertyValue(clusterProps, "mcast-addr", null);
int mcp = ContainerConfig.getPropertyValue(clusterProps, "mcast-port", -1);
int mcf = ContainerConfig.getPropertyValue(clusterProps, "mcast-freq", 500);
int mcd = ContainerConfig.getPropertyValue(clusterProps, "mcast-drop-time", 3000);
if (mca == null || mcp == -1) {
throw new ContainerException("Cluster configuration requires mcast-addr and mcast-port properties");
}
McastService mcast = new McastService();
if (mcb != null) {
mcast.setMcastBindAddress(mcb);
}
mcast.setAddress(mca);
mcast.setPort(mcp);
mcast.setMcastDropTime(mcd);
mcast.setFrequency(mcf);
String tla = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-host", "auto");
int tlp = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-port", 4001);
int tlt = ContainerConfig.getPropertyValue(clusterProps, "tcp-sector-timeout", 100);
int tlc = ContainerConfig.getPropertyValue(clusterProps, "tcp-thread-count", 6);
//String tls = getPropertyValue(clusterProps, "", "");
if (tlp == -1) {
throw new ContainerException("Cluster configuration requires tcp-listen-port property");
}
NioReceiver listener = new NioReceiver();
listener.setAddress(tla);
listener.setPort(tlp);
listener.setSelectorTimeout(tlt);
listener.setMaxThreads(tlc);
listener.setMinThreads(tlc);
//listener.setIsSenderSynchronized(false);
ReplicationTransmitter trans = new ReplicationTransmitter();
try {
MultiPointSender mps = (MultiPointSender)Class.forName(ContainerConfig.getPropertyValue(clusterProps, "replication-mode", "org.apache.catalina.tribes.transport.bio.PooledMultiSender")).newInstance();
trans.setTransport(mps);
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid replication-mode property: " + exc.getMessage());
}
String mgrClassName = ContainerConfig.getPropertyValue(clusterProps, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
//int debug = ContainerConfig.getPropertyValue(clusterProps, "debug", 0);
// removed since 5.5.9? boolean expireSession = ContainerConfig.getPropertyValue(clusterProps, "expire-session", false);
// removed since 5.5.9? boolean useDirty = ContainerConfig.getPropertyValue(clusterProps, "use-dirty", true);
SimpleTcpCluster cluster = new SimpleTcpCluster();
cluster.setClusterName(clusterProps.name);
Manager manager = null;
try {
manager = (Manager)Class.forName(mgrClassName).newInstance();
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
}
//cluster.setManagerClassName(mgrClassName);
//host.setManager(manager);
//cluster.registerManager(manager);
cluster.setManagerTemplate((org.apache.catalina.ha.ClusterManager)manager);
//cluster.setDebug(debug);
// removed since 5.5.9? cluster.setExpireSessionsOnShutdown(expireSession);
// removed since 5.5.9? cluster.setUseDirtyFlag(useDirty);
GroupChannel channel = new GroupChannel();
channel.setChannelReceiver(listener);
channel.setChannelSender(trans);
channel.setMembershipService(mcast);
cluster.setChannel(channel);
cluster.addValve(clusterValve);
// removed since 5.5.9? cluster.setPrintToScreen(true);
// set the cluster to the host
host.setCluster(cluster);
Debug.logInfo("Catalina Cluster [" + cluster.getClusterName() + "] configured for host - " + host.getName(), module);
return cluster;
}
protected Connector createConnector(ContainerConfig.Container.Property connectorProp) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Connector without Embedded instance!");
}
// need some standard properties
String protocol = ContainerConfig.getPropertyValue(connectorProp, "protocol", "HTTP/1.1");
String address = ContainerConfig.getPropertyValue(connectorProp, "address", "0.0.0.0");
int port = ContainerConfig.getPropertyValue(connectorProp, "port", 0);
boolean secure = ContainerConfig.getPropertyValue(connectorProp, "secure", false);
if (protocol.toLowerCase().startsWith("ajp")) {
protocol = "ajp";
} else if ("memory".equals(protocol.toLowerCase())) {
protocol = "memory";
} else if (secure) {
protocol = "https";
} else {
protocol = "http";
}
Connector connector = null;
if (UtilValidate.isNotEmpty(connectorProp.properties)) {
connector = embedded.createConnector(address, port, protocol);
try {
for (ContainerConfig.Container.Property prop: connectorProp.properties.values()) {
connector.setProperty(prop.name, prop.value);
//connector.setAttribute(prop.name, prop.value);
}
embedded.addConnector(connector);
} catch (Exception e) {
throw new ContainerException(e);
}
}
return connector;
}
protected Context createContext(ComponentConfig.WebappInfo appInfo) throws ContainerException {
// webapp settings
Map<String, String> initParameters = appInfo.getInitParameters();
List<String> virtualHosts = appInfo.getVirtualHosts();
Engine engine = engines.get(appInfo.server);
if (engine == null) {
Debug.logWarning("Server with name [" + appInfo.server + "] not found; not mounting [" + appInfo.name + "]", module);
return null;
}
// set the root location (make sure we set the paths correctly)
String location = appInfo.componentConfig.getRootLocation() + appInfo.location;
location = location.replace('\\', '/');
if (location.endsWith("/")) {
location = location.substring(0, location.length() - 1);
}
// get the mount point
String mount = appInfo.mountPoint;
if (mount.endsWith("/*")) {
mount = mount.substring(0, mount.length() - 2);
}
// configure persistent sessions
Property clusterProp = clusterConfig.get(engine.getName());
Manager sessionMgr = null;
if (clusterProp != null) {
String mgrClassName = ContainerConfig.getPropertyValue(clusterProp, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
try {
sessionMgr = (Manager)Class.forName(mgrClassName).newInstance();
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
}
} else {
sessionMgr = new StandardManager();
}
// create the web application context
StandardContext context = (StandardContext) embedded.createContext(mount, location);
context.setJ2EEApplication(J2EE_APP);
context.setJ2EEServer(J2EE_SERVER);
context.setLoader(embedded.createLoader(ClassLoaderContainer.getClassLoader()));
context.setCookies(appInfo.isSessionCookieAccepted());
context.addParameter("cookies", appInfo.isSessionCookieAccepted() ? "true" : "false");
context.setDisplayName(appInfo.name);
context.setDocBase(location);
context.setAllowLinking(true);
context.setReloadable(contextReloadable);
context.setDistributable(distribute);
context.setCrossContext(crossContext);
context.setPrivileged(appInfo.privileged);
context.setManager(sessionMgr);
context.getServletContext().setAttribute("_serverId", appInfo.server);
context.getServletContext().setAttribute("componentName", appInfo.componentConfig.getComponentName());
// create the Default Servlet instance to mount
StandardWrapper defaultServlet = new StandardWrapper();
defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
defaultServlet.setServletName("default");
defaultServlet.setLoadOnStartup(1);
defaultServlet.addInitParameter("debug", "0");
defaultServlet.addInitParameter("listing", "true");
defaultServlet.addMapping("/");
context.addChild(defaultServlet);
context.addServletMapping("/", "default");
// create the Jasper Servlet instance to mount
StandardWrapper jspServlet = new StandardWrapper();
jspServlet.setServletClass("org.apache.jasper.servlet.JspServlet");
jspServlet.setServletName("jsp");
jspServlet.setLoadOnStartup(1);
jspServlet.addInitParameter("fork", "false");
jspServlet.addInitParameter("xpoweredBy", "true");
jspServlet.addMapping("*.jsp");
jspServlet.addMapping("*.jspx");
context.addChild(jspServlet);
context.addServletMapping("*.jsp", "jsp");
// default mime-type mappings
configureMimeTypes(context);
// set the init parameters
for (Map.Entry<String, String> entry: initParameters.entrySet()) {
context.addParameter(entry.getKey(), entry.getValue());
}
if (UtilValidate.isEmpty(virtualHosts)) {
Host host = hosts.get(engine.getName() + "._DEFAULT");
context.setRealm(host.getRealm());
host.addChild(context);
context.getMapper().setDefaultHostName(host.getName());
} else {
// assume that the first virtual-host will be the default; additional virtual-hosts will be aliases
Iterator<String> vhi = virtualHosts.iterator();
String hostName = vhi.next();
boolean newHost = false;
Host host = hosts.get(engine.getName() + "." + hostName);
if (host == null) {
host = createHost(engine, hostName);
newHost = true;
}
while (vhi.hasNext()) {
host.addAlias(vhi.next());
}
context.setRealm(host.getRealm());
host.addChild(context);
context.getMapper().setDefaultHostName(host.getName());
if (newHost) {
hosts.put(engine.getName() + "." + hostName, host);
}
}
return context;
}
protected void loadComponents() throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot load web applications without Embedded instance!");
}
// load the applications
List<ComponentConfig.WebappInfo> webResourceInfos = ComponentConfig.getAllWebappResourceInfos();
List<String> loadedMounts = FastList.newInstance();
if (webResourceInfos != null) {
for (int i = webResourceInfos.size(); i > 0; i--) {
ComponentConfig.WebappInfo appInfo = webResourceInfos.get(i - 1);
String mount = appInfo.getContextRoot();
if (!loadedMounts.contains(mount)) {
createContext(appInfo);
loadedMounts.add(mount);
} else {
appInfo.appBarDisplay = false; // disable app bar display on overrided apps
Debug.logInfo("Duplicate webapp mount; not loading : " + appInfo.getName() + " / " + appInfo.getLocation(), module);
}
}
}
}
public void stop() throws ContainerException {
try {
embedded.stop();
} catch (LifecycleException e) {
// don't throw this; or it will kill the rest of the shutdown process
Debug.logVerbose(e, module); // happens usually when running tests, disabled unless in verbose
}
}
protected void configureMimeTypes(Context context) throws ContainerException {
Map<String, String> mimeTypes = CatalinaContainer.getMimeTypes();
if (UtilValidate.isNotEmpty(mimeTypes)) {
for (Map.Entry<String, String> entry: mimeTypes.entrySet()) {
context.addMimeMapping(entry.getKey(), entry.getValue());
}
}
}
protected static synchronized Map<String, String> getMimeTypes() throws ContainerException {
if (UtilValidate.isNotEmpty(mimeTypes)) {
return mimeTypes;
}
if (mimeTypes == null) mimeTypes = new HashMap<String, String>();
URL xmlUrl = UtilURL.fromResource("mime-type.xml");
// read the document
Document mimeTypeDoc;
try {
mimeTypeDoc = UtilXml.readXmlDocument(xmlUrl, true);
} catch (SAXException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
} catch (ParserConfigurationException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
} catch (IOException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
}
if (mimeTypeDoc == null) {
Debug.logError("Null document returned for mime-type.xml", module);
return null;
}
// root element
Element root = mimeTypeDoc.getDocumentElement();
// mapppings
for (Element curElement: UtilXml.childElementList(root, "mime-mapping")) {
String extension = UtilXml.childElementValue(curElement, "extension");
String type = UtilXml.childElementValue(curElement, "mime-type");
mimeTypes.put(extension, type);
}
return mimeTypes;
}
}
Class.class file
try {
return tmpConstructor.newInstance((Object[])null);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
I'm confused state. Please help me to recover this issue.
Thanks in advance.
In the stacktrace there is a
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5747 at
org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.readClass(Unknown Source)
ASM is a tool to read and manipulate Java class files.
There have been changes to the class file format between JDK 6 and 8 and you (most probably) have an outdated version of ASM which runs into problems when reading Java 8 class files.
To solve the issue try to upgrade to the latest version of ASM (or Ofbiz).
EDIT: As commented by integratingweb Opentaps only supports JDK 6.
I'm trying to send a trap v1 using snmp4j. It doesn't throwns any exception and execute everything, but the trap is not reaching its destiny. Am I missing something? Is there another way to do it? The IP and the ports in the code are corrects. What would be wrong?
Here's the code:
public class SNMPv1 {
public static final String community = "public";
public static final String trapOid = ".1.3.6.1.4.1.2595.1.2";
public static final String ipAddress = "10.200.1.220";
public static final String agentIPAddress = "10.200.1.120";
public static final int port = 164;
private static final int specificTrap = 1;
public static void main(String[] args)
{
SNMPv1 snmp4JTrap = new SNMPv1();
/* Sending V1 Trap */
snmp4JTrap.sendSnmpV1Trap();
}
public void sendSnmpV1Trap()
{
try
{
//Create Transport Mapping
TransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
//Create Target
CommunityTarget comtarget = new CommunityTarget();
comtarget.setCommunity(new OctetString(community));
comtarget.setVersion(SnmpConstants.version1);
comtarget.setAddress(new UdpAddress(ipAddress + "/" + port));
comtarget.setRetries(4);
comtarget.setTimeout(10000);
//Create PDU for V1
PDUv1 pdu = new PDUv1();
pdu.setType(PDU.V1TRAP);
pdu.setEnterprise(new OID(trapOid));
pdu.setGenericTrap(PDUv1.ENTERPRISE_SPECIFIC); // 6
pdu.setSpecificTrap(specificTrap);
pdu.setAgentAddress(new IpAddress(agentIPAddress));
VariableBinding v = new VariableBinding();
v.setOid(SnmpConstants.sysName);
v.setVariable(new OctetString("Param1"));
pdu.add(v);
VariableBinding v2 = new VariableBinding();
v2.setOid(SnmpConstants.sysName);
v2.setVariable(new OctetString("Param2"));
pdu.add(v2);
VariableBinding v3 = new VariableBinding();
v3.setOid(SnmpConstants.sysName);
v3.setVariable(new OctetString("Param3"));
pdu.add(v3);
VariableBinding v4 = new VariableBinding();
v4.setOid(SnmpConstants.sysName);
v4.setVariable(new OctetString("Param4"));
pdu.add(v4);
VariableBinding v5 = new VariableBinding();
v5.setOid(SnmpConstants.sysName);
v5.setVariable(new OctetString("Param5"));
pdu.add(v5);
VariableBinding v6 = new VariableBinding();
v6.setOid(SnmpConstants.sysName);
v6.setVariable(new OctetString("Param6"));
pdu.add(v6);
//Send the PDU
Snmp snmp = new Snmp(transport);
System.out.println("Sending trap to" + ipAddress + ":" + port);
snmp.send(pdu, comtarget);
snmp.close();
System.out.println("Trap send successfully!!");
}
catch (Exception e)
{
System.err.println("Error sending Trap to " + ipAddress + ":" + port);
System.err.println("Exception Message = " + e.getMessage());
}
}
}