pcap4j+winpcap should I run rpcapd.exe manually? - winpcap

Hi I have downloaded pcap4j and winpcap and all jar (jna, pcap4j-core-1.8.2, slf4j-api-1.7.25, slf4j-simple-1.7.25) dependency manually. Added to the project and all compile well.
BUT:
when I began to sniff packet.getHeader() and packet.getPayload() returns null!
if I run manually rpcapd.exe then it works...
why?
package sniffer;
import java.io.IOException;
import org.pcap4j.core.BpfProgram.BpfCompileMode;
import org.pcap4j.core.NotOpenException;
import org.pcap4j.core.PacketListener;
import org.pcap4j.core.PcapHandle;
import org.pcap4j.core.PcapNativeException;
import org.pcap4j.core.PcapNetworkInterface;
import org.pcap4j.core.PcapNetworkInterface.PromiscuousMode;
import org.pcap4j.packet.Packet;
import org.pcap4j.util.NifSelector;
public class App {
static PcapNetworkInterface getNetworkDevice() {
PcapNetworkInterface device = null;
try {
device = new NifSelector().selectNetworkInterface();
} catch (IOException e) {
e.printStackTrace();
}
return device;
}
public static void main(String[] args) throws PcapNativeException, NotOpenException {
// The code we had before
PcapNetworkInterface device = getNetworkDevice();
System.out.println("You chose: " + device);
// New code below here
if (device == null) {
System.out.println("No device chosen.");
System.exit(1);
}
// Open the device and get a handle
int snapshotLength = 65536; // in bytes
int readTimeout = 50; // in milliseconds
final PcapHandle handle;
handle = device.openLive(snapshotLength, PromiscuousMode.PROMISCUOUS, readTimeout);
String filter = "tcp port 80";
handle.setFilter(filter, BpfCompileMode.OPTIMIZE);
// Create a listener that defines what to do with the received packets
PacketListener listener = new PacketListener() {
#Override
public void gotPacket(Packet packet) {
// Override the default gotPacket() function and process packet
System.out.println(handle.getTimestamp());
System.out.println(packet);
System.out.println(packet.getHeader());///////////////<<<<<<<<<<<------------
}
};
// Tell the handle to loop using the listener we created
try {
int maxPackets = 50;
handle.loop(maxPackets, listener);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Cleanup when complete
handle.close();
}
}

You need to add a packet factory (e.g. pcap4j-packetfactory-static.jar) to your classpath, or Pcap4J creates UnknownPacket instances, getPayload() and getHeader() of which return null, for all packets.

Related

bytedeco javcv OpenCVFrameGrabber.grab is too slow for 25 fps

I've got the following code and somehow the logged time between 1 and 2 is 65-95 ms all the time so I can only record a video grabbed from my webcam with 10-12 fps :-/
(For instance) Looking at How to capture and record video from webcam using JavaCV I shouldn't be that far off from being able to capture a video with 25 or 30 fps from the webcam
grabber = OpenCVFrameGrabber.createDefault(0);
//grabber.setFrameRate(25);
grabber.setImageWidth(1280);
grabber.setImageHeight(720);
grabber.start();
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {
try {
while (!isStopRequested) {
LOGGER.debug("1: {}", System.currentTimeMillis());
Frame frame = grabber.grab(); // this takes 65-95 ms
LOGGER.debug("2: {}", System.currentTimeMillis());
WritableImage image = frameToImage(frame);
recordingController.processImage(image);
if (isStarted) {
recorder.record(frame);
}
}
} catch (FrameGrabber.Exception fe) {
LOGGER.error("FrameGrabber.Exception when grabbing frame from camera: {}", fe.getMessage());
} catch (FrameRecorder.Exception fre) {
LOGGER.error("FrameRecorder.Exception when recording frame from camera: {}", fre.getMessage());
}
});
The code runs in Java 17 on a laptop with an i7-11800H # 2.30GHz and 64 GB ram, it has 8 cores and not even one of the 8 is fully utilized when running this software, so I don't think it's a hardware issue.
What works for me is this code, in which not only the Thread.sleep() is essential but also the amount of sleep, as 10 or 30 didn't give me good results for the duration, but 40 does (2-2-3-2-2 etc). Don't know why, though and because of this uncertainty I won't accept my own answer as THE answer. I might have to get back to this later
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.image.*;
import ??.screens.RecordingController;
import org.bytedeco.javacv.*;
import org.bytedeco.javacv.Frame;
import org.bytedeco.opencv.global.opencv_imgproc;
import org.bytedeco.opencv.opencv_core.Mat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.awt.*;
import java.io.File;
import java.nio.ByteBuffer;
import static org.opencv.imgproc.Imgproc.COLOR_BGR2BGRA;
#Component
public class WebcamGrabber {
private static final Logger LOGGER = LoggerFactory.getLogger(WebcamGrabber.class);
private RecordingController recordingController;
Mat javaCVMat = new Mat();
/**
* create buffer only once saves much time!
*/
WritablePixelFormat<ByteBuffer> formatByte = PixelFormat.getByteBgraPreInstance();
OpenCVFrameConverter<Mat> javaCVConv = new OpenCVFrameConverter.ToMat();
/**
* controls if application closes
*/
SimpleBooleanProperty cameraActiveProperty = new SimpleBooleanProperty(false);
OpenCVFrameGrabber frameGrabber;
FFmpegFrameRecorder recorder;
ByteBuffer buffer;
Dimension dimension;
boolean isStarted;
public void init(RecordingController recordingController) {
this.recordingController = recordingController;
}
protected void updateView(Frame frame) {
int w = frame.imageWidth;
int h = frame.imageHeight;
Mat mat = javaCVConv.convert(frame);
opencv_imgproc.cvtColor(mat, javaCVMat, COLOR_BGR2BGRA);
if (buffer == null) {
buffer = javaCVMat.createBuffer();
}
PixelBuffer<ByteBuffer> pb = new PixelBuffer<>(w, h, buffer, formatByte);
final WritableImage wi = new WritableImage(pb);
recordingController.processImage(wi);
}
public void setCameraActive(Boolean isActive) {
cameraActiveProperty.set(isActive);
}
public Boolean getCameraActive() {
return cameraActiveProperty.get();
}
public void shutdown() {
setCameraActive(false);
}
void setVideoView(Frame mat) {
updateView(mat);
}
public void startViewing(Dimension dimension, int cameraIndex) {
this.dimension = dimension;
frameGrabber = new OpenCVFrameGrabber(cameraIndex);
frameGrabber.setFrameRate(25);
frameGrabber.setImageWidth(dimension.width);
frameGrabber.setImageHeight(dimension.height);
try {
frameGrabber.start();
} catch (FrameGrabber.Exception fe) {
LOGGER.error("Exception when trying to start grabbing from camera: {}", fe.getMessage());
}
new Thread(() -> {
setCameraActive(true);
while (getCameraActive()) {
try {
new Thread(() -> {
try {
long startTime = System.currentTimeMillis();
Frame frame = frameGrabber.grab();
System.out.println("Duration: " + (System.currentTimeMillis() - startTime));
setVideoView(frame);
if (isStarted) {
recorder.record(frame);
}
} catch (FrameGrabber.Exception fe) {
LOGGER.error("Exception when grabbing frame from camera: {}", fe.getMessage());
} catch (FrameRecorder.Exception fe) {
LOGGER.error("Exception when recording frame from camera: {}", fe.getMessage());
}
}).start();
Thread.sleep(40);
} catch (InterruptedException ie) {
LOGGER.error("InterruptedException when grabbing frame from camera: {}", ie.getMessage());
}
}
try {
frameGrabber.release();
recorder.stop();
} catch (FrameGrabber.Exception fe) {
LOGGER.error("Exception when releasing frame grabber: {}", fe.getMessage());
} catch (FrameRecorder.Exception fe) {
LOGGER.error("Exception when releasing frame recorder: {}", fe.getMessage());
}
}).start();
}
public void startRecording() {
long start = System.currentTimeMillis();
recorder = new FFmpegFrameRecorder(new File("D:\\data\\" + start + ".mp4"), dimension.width, dimension.height, 2);
recorder.setFormat("mp4");
recorder.setFrameRate(25);
try {
recorder.start();
isStarted = true;
} catch (FrameRecorder.Exception fre) {
LOGGER.error("FrameRecorder.Exception when starting recording: {}", fre.getMessage());
}
Context.getInstance().writeMetadata(start);
}
public void stop() {
if (isStarted) {
isStarted = false;
LOGGER.info("Recording stopped");
}
}
}

CannotCompileException while Instrumenting Java code with using Java Assist, cannot find class

I'm trying create a generic Java Agent to instrument any Java application's methods.
I've followed this tutorial https://javapapers.com/core-java/java-instrumentation/ and created a java agent.
The java agent is supposed to look for a particular class ( I'm restricting it to one class now since it's not working for me)
Once the class is found, I'm using JavaAssist API to add a local variable to the beginning of each method and capture the current time. In the end of the method I'd like to simply print the time it took for the method to execute. (Pretty much following all the typical examples about Java agent.
I run my test application ( a web server using Vert.x ) with --javaagent flag pointing to the Java agent jar file I created ( the code is down below).
This works just fine for methods that either don't have return value and no parameters or return/take a primitive type.
However when a method is returning or taking a parameter that is an object from a another class (that has not been loaded yet I think) I get a CannotCompileException exception with the message that that class which is in the parameters list or in the return statement is not found.
For example the instrumentation for this method works:
#Override
public void start() throws Exception {
logger.debug("started thread {}", Thread.currentThread().getName());
for (int port : ports) {
HttpServer httpServer = getVertx().createHttpServer(httpServerOptions);
Router router = setupRoutes();
httpServer.requestHandler(router::accept);
logger.info("Listening on port {}", port);
httpServer.listen(port);
}
}
However for this method that returns io.vertx.ext.web.Router:
private Router setupRoutes() {
Router router = Router.router(getVertx());
router.get(STATUS_PATH).handler(this::statusHandler);
router.route().handler(BodyHandler.create());
router.post().handler(this::handleBidRequest);
router.put().handler(this::handleBidRequest);
router.get(SLEEP_CONTROLLER_PATH).handler(this::sleepControllerHandler);
return router;
}
I get an exception and the output of my java agent is :
Instrumenting method rubiconproject.com.WebServerVerticle.setupRoutes()
Could not instrument method setupRoutes error: cannot find io.vertx.ext.web.Router
This the code for my java agent:
import java.lang.instrument.Instrumentation;
import transformers.TimeMeasuringTransformer;
public class TimeCapturerAgent {
public static void premain(String agentArgs, Instrumentation inst) {
System.out.println(TimeCapturerAgent.class.getCanonicalName() + " is loaded...... ");
inst.addTransformer(new TimeMeasuringTransformer());
}}
package transformers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
public class TimeMeasuringTransformer implements ClassFileTransformer {
public TimeMeasuringTransformer() {
System.out.println("TimeMeasuringTransformer added ");
}
#Override
public byte[] transform(ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {
if(className != null && className.contains("WebServerVerticle")) {
System.out.println("Instrumenting class " + className);
return modifyClass(classfileBuffer);
}
return null;
}
private byte[] modifyClass(byte[] originalClassfileBuffer) {
ClassPool classPool = ClassPool.getDefault();
CtClass compiledClass;
try {
compiledClass = classPool.makeClass(new ByteArrayInputStream(originalClassfileBuffer));
System.out.println("Created new compiled Class " + compiledClass.getName());
} catch (IOException e) {
e.printStackTrace();
return null;
}
instrumentMethods(compiledClass);
byte [] newClassByteCode = createNewClassByteArray(compiledClass);
compiledClass.detach();
return newClassByteCode;
}
private byte[] createNewClassByteArray(CtClass compiledClass) {
byte[] newClassByteArray = null;
try {
newClassByteArray = compiledClass.toBytecode();
} catch (IOException e) {
e.printStackTrace();
} catch (CannotCompileException e) {
e.printStackTrace();
} finally {
return newClassByteArray;
}
}
private void instrumentMethods(CtClass compiledClass) {
CtMethod[] methods = compiledClass.getDeclaredMethods();
System.out.println("Class has " + methods.length + " methods");
for (CtMethod method : methods) {
try {
System.out.println("Instrumenting method " + method.getLongName());
method.addLocalVariable("startTime", CtClass.longType);
method.insertBefore("startTime = System.nanoTime();");
method.insertAfter("System.out.println(\"Execution Duration "
+ "(nano sec): \"+ (System.nanoTime() - startTime) );");
} catch (CannotCompileException e) {
System.out.println("Could not instrument method " + method.getName()+" error: " + e.getMessage());
continue;
}
}
}}

mystified with javax.sound.sampled.Clip NullPointerException

mystified with javax.sound.sampled.Clip NullPointerException
Running on Eclipse on a Mac.
Input wave file exists,
Constructor works fine. Object instance is created.
Just can't access the instance methods, any of them.
Probably a Java 101 issue here, so I apologize in advance, if so?
Or Eclipses 101, for that matter...
public class AudioClipTester {
public static void main(String[] args)
{
// TODO Auto-generated method stub
AudioClipPlayer mooMoo = new AudioClipPlayer("cow.wav");
mooMoo.play();
}
}
/=====
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* Handles play, pause, and looping of sounds for the game.
* #author Tyler Thomas
*
*/
public class AudioClipPlayer
{
private Clip myClip;
public AudioClipPlayer(String fileName) {
try {
File file = new File(fileName);
if (file.exists()) {
Clip myClip = AudioSystem.getClip();
System.out.println("file "+fileName+" is in root dir");
AudioInputStream ais = AudioSystem.getAudioInputStream(file.toURI().toURL());
myClip.open(ais);
System.out.println("ais "+ais.toString()+" is open");
}
else {
throw new RuntimeException("Sound: file not found: " + fileName);
}
}
catch (MalformedURLException e) {
throw new RuntimeException("Sound: Malformed URL: " + e);
}
catch (UnsupportedAudioFileException e) {
throw new RuntimeException("Sound: Unsupported Audio File: " + e);
}
catch (IOException e) {
throw new RuntimeException("Sound: Input/Output Error: " + e);
}
catch (LineUnavailableException e) {
throw new RuntimeException("Sound: Line Unavailable: " + e);
}
}
public void play(){
System.out.println("clip "+myClip.toString()+" is about to play");
myClip.setFramePosition(0); // Must always rewind!
myClip.loop(0);
myClip.start();
// Thread.sleep(10000);
}
public void loop(){
myClip.loop(Clip.LOOP_CONTINUOUSLY);
}
public void stop(){
myClip.stop();
}
}
That is because in the following line:
Clip myClip = AudioSystem.getClip();
you declare and initialize local variable and the field myClip stays null. Try to replace the above line with
myClip = AudioSystem.getClip();

J2ME connect localhost nullpointerexception 0

I am trying to connect localhost and insert data into database through j2me application.but when I am connecting the server it shows there is a nullpointerexception 0 error.
this is midlet code
import java.io.DataOutputStream;
import java.io.InputStream;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.*;
public class Midlet_1 extends MIDlet implements CommandListener {
Display mdDisplay;
Form mForm;
StringItem messageitem;
Command exit, connectCommand;
public Midlet_1() {
mForm = new Form("My Counter midlet");
messageitem = new StringItem(null, "");
exit = new Command("Exit", Command.EXIT, 0);
connectCommand = new Command("Connect", Command.SCREEN, 0);
mForm.append(messageitem);
mForm.addCommand(exit);
mForm.addCommand(connectCommand);
mForm.setCommandListener(this);
}
public void startApp() {
mdDisplay = Display.getDisplay(this);
mdDisplay.setCurrent(mForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exit) {
notifyDestroyed();
} else if (c == connectCommand) {
Form waitform = new Form("Waiting");
mdDisplay.setCurrent(waitform);
Thread t = new Thread() {
public void run() {
connect();
}
};
t.start();
}
}
private void connect() {
try {
HttpConnection hs = null;
InputStream in = null;
String url = "localhost:8080/testweb/src/save";
hs.setRequestProperty("User-Agent", "Profile/MIDP-2.0,Configuration/CLDC-2.0");
hs.setRequestProperty("Content-Language", "en-US");
hs.setRequestMethod(HttpConnection.POST);
DataOutputStream ds = hs.openDataOutputStream();
ds.writeUTF("nam56");
ds.writeUTF("67");
ds.writeUTF("0716522549");
ds.flush();
ds.close();
in = hs.openInputStream();
int connectlength = (int) hs.getLength();
byte[] raw = new byte[connectlength];
int length = in.read(raw);
// int ch;
// StringBuffer sb=new StringBuffer();
// while((ch=in.read())!=-1){
// sb.append((char)ch);
// }
in.close();
hs.close();
String s = new String(raw, 0, length);
messageitem.setText(s);
} catch (Exception e) {
messageitem.setText(e.toString());
System.out.println(e);
}
mdDisplay.setCurrent(mForm);
}
}
and this is servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
DataInputStream in=new DataInputStream(request.getInputStream());
String name=in.readUTF();
String id=in.readUTF();
String contt=in.readUTF();
Connection c=DBcon.setconConnection();
Statement s=c.createStatement();
s.executeUpdate("insert into details values('"+id+"','"+name+"''"+contt+"')");
out.print("successfullllll");
} finally {
out.close();
}
}
please check this out.....
This might work only if you are running an emulator on the same machine as the server. Try to replace locahost by 127.0.0.1.
In your connect() method, I can see that you initialized hs as null then you called setRequestProperty. Try to initialize hs properly before calling its methods.

ActiveMQ and JMS : Basic steps for novice

Hi all please give some basic about ActiveMQ with JMS for novice. And configuration steps also.
We are going to create a console based application using multithreading. So create an java project for console application.
Now follow these steps..........
Add javax.jms.jar, activemq-all-5.3.0.jar, log4j-1.2.15.jar to your project library.
(You can download all of above jar files from http://www.jarfinder.com/ .
create a file naming jndi.properties and paste these following texts .. ( Deatils for jndi.properties just Google it)
# START SNIPPET: jndi
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
# use the following property to configure the default connector
java.naming.provider.url = tcp://localhost:61616
# use the following property to specify the JNDI name the connection factory
# should appear as.
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue = example.MyQueue
# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic = example.MyTopic
# END SNIPPET: jndi
Add JMSConsumer.java
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JMSConsumer implements Runnable{
private static final Log LOG = LogFactory.getLog(JMSConsumer.class);
public void run() {
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
MessageConsumer consumer = null;
Destination destination = null;
String sourceName = null;
final int numMsgs;
sourceName= "MyQueue";
numMsgs = 1;
LOG.info("Source name is " + sourceName);
/*
* Create a JNDI API InitialContext object
*/
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
LOG.info("Could not create JNDI API context: " + e.toString());
System.exit(1);
}
/*
* Look up connection factory and destination.
*/
try {
connectionFactory = (ConnectionFactory)jndiContext.lookup("queueConnectionFactory");
destination = (Destination)jndiContext.lookup(sourceName);
} catch (NamingException e) {
LOG.info("JNDI API lookup failed: " + e);
System.exit(1);
}
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(destination);
connection.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MessageListener listener = new MyQueueMessageListener();
consumer.setMessageListener(listener );
//Let the thread run for some time so that the Consumer has suffcient time to consume the message
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JMSException e) {
LOG.info("Exception occurred: " + e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}
}
Add JMSProducer.java
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JMSProducer implements Runnable{
private static final Log LOG = LogFactory.getLog(JMSProducer.class);
public JMSProducer() {
}
//Run method implemented to run this as a thread.
public void run(){
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageProducer producer = null;
String destinationName = null;
final int numMsgs;
destinationName = "MyQueue";
numMsgs = 5;
LOG.info("Destination name is " + destinationName);
/*
* Create a JNDI API InitialContext object
*/
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
LOG.info("Could not create JNDI API context: " + e.toString());
System.exit(1);
}
/*
* Look up connection factory and destination.
*/
try {
connectionFactory = (ConnectionFactory)jndiContext.lookup("queueConnectionFactory");
destination = (Destination)jndiContext.lookup(destinationName);
} catch (NamingException e) {
LOG.info("JNDI API lookup failed: " + e);
System.exit(1);
}
/*
* Create connection. Create session from connection; false means
* session is not transacted.create producer, set the text message, set the co-relation id and send the message.
*/
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
for (int i = 0; i
Add MyQueueMessageListener.java
import java.io.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.jms.*;
public class MyQueueMessageListener implements MessageListener {
private static final Log LOG = LogFactory.getLog(MyQueueMessageListener.class);
/**
*
*/
public MyQueueMessageListener() {
// TODO Auto-generated constructor stub
}
/** (non-Javadoc)
* #see javax.jms.MessageListener#onMessage(javax.jms.Message)
* This is called on receving of a text message.
*/
public void onMessage(Message arg0) {
LOG.info("onMessage() called!");
if(arg0 instanceof TextMessage){
try {
//Print it out
System.out.println("Recieved message in listener: " + ((TextMessage)arg0).getText());
System.out.println("Co-Rel Id: " + ((TextMessage)arg0).getJMSCorrelationID());
try {
//Log it to a file
BufferedWriter outFile = new BufferedWriter(new FileWriter("MyQueueConsumer.txt"));
outFile.write("Recieved message in listener: " + ((TextMessage)arg0).getText());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println("~~~~Listener : Error in message format~~~~");
}
}
}
Add SimpleApp.java
public class SimpleApp {
//Run the producer first, then the consumer
public static void main(String[] args) throws Exception {
runInNewthread(new JMSProducer());
runInNewthread(new JMSConsumer());
}
public static void runInNewthread(Runnable runnable) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(false);
brokerThread.start();
}
}
Now run SimpleApp.java class.
All da best. Happy coding.
Here it is a simple junit test for ActiveMQ and Apache Camel. This two technologies works very good together.
If you want more details about the code, you can find a post in my blog:
http://ignaciosuay.com/unit-testing-active-mq/
public class ActiveMQTest extends CamelTestSupport {
#Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
camelContext.addComponent("activemq", jmsComponentClientAcknowledge(connectionFactory));
return camelContext;
}
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("mina:tcp://localhost:6666?textline=true&sync=false")
.to("activemq:processHL7");
from("activemq:processHL7")
.to("mock:end");
}
};
}
#Test
public void testSendHL7Message() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:end");
String m = "MSH|^~\\&|hl7Integration|hl7Integration|||||ADT^A01|||2.5|\r" +
"EVN|A01|20130617154644\r" +
"PID|1|465 306 5961||407623|Wood^Patrick^^^MR||19700101|1|\r" +
"PV1|1||Location||||||||||||||||261938_6_201306171546|||||||||||||||||||||||||20130617134644|";
mock.expectedBodiesReceived(m);
template.sendBody("mina:tcp://localhost:6666?textline=true&sync=false", m);
mock.assertIsSatisfied();
}