Embedded broker Active MQ start - java

I wrote a little program that use activemq embedded broker. Program run on one machine successfully but does not work another one. Both of server have sun os 10 & java 7 and also activemq 5.5.1. I mean with does not work, new BrokerService() constructor call does not return for a while (a couple of minutes). Snippet code is like below.
Thanks for advices..
public static void main(String[] args) {
// ....
try {
p.start("tcp://192.168.4.2:61616");
} catch (MessagingException e) {
e.printStackTrace();
}
// ....
}
public void start(String brokerAddress) throws MessagingException {
try {
System.out.println(">>> initialize 2");
broker = new JmsBroker(brokerAddress, brokerAddress.substring(6));
System.out.println(">>> initialize 3");
broker.start();
System.out.println(">>> initialize 4");
messageProducer = new JmsProducer(brokerAddress,
"MESSAGING_IF_NAME",
false,
5000);
System.out.println(">>> initialize 5");
} catch (JMSException e) {
System.out.println(e);
}
}
public class JmsBroker extends Thread {
private BrokerService broker;
private Object lock;
private static final Logger logger = LoggerFactory.getLogger(JmsBroker.class);
private String connector;
public JmsBroker(String jmsAddress, String brokerName) throws MessagingException {
broker = new BrokerService(); // !!!!! PROBLEM
broker.setBrokerName(brokerName);
broker.setUseJmx(true);
broker.setUseLoggingForShutdownErrors(true);
broker.setSchedulerSupport(false);
broker.setPersistent(false);
connector = jmsAddress;
try {
System.out.println(">>> s1");
broker.addConnector(connector);
System.out.println(">>> s2");
broker.start(true);
System.out.println(">>> s3");
while (!broker.isStarted()) {
Thread.sleep(10);
System.out.println("BROKER NOT STARTED");
}
logger.info("JMS BROKER STARTED");
System.out.println("JMS BROKER STARTED");
} catch (InterruptedException e) {
throw new MessagingException(e);
} catch (Exception e) {
throw new MessagingException(e);
}
}
public void run() {
try {
lock = new Object();
synchronized (lock) {
lock.wait();
}
} catch (Exception e) {
logger.error("", e);
}
}
}

wrong record on etc/hosts file causes this problem. After removing problem is solved.

Related

How to tell if a JMS queue is started or stopped?

I have a Java service which is getting messages from an Oracle Advanced Queue. I can create the connection and listen and get messages OK. I can see that you can stop and start listening for messages, so I have implemented controls for that. However, I would like to be able to report on the current status of the listener. I can see if it's there, but how can I tell if it's stopped or started?
I have a container class along the lines of (Listener is my own class (implementing both MessageListener and ExceptionListener) which actually does something with the message)
public class QueueContainer {
private static final String QUEUE_NAME = "foo";
private final Connection dbConnection;
private final QueueConnection queueConnection;
private final QueueSession queueSession;
private final Queue queue;
private final MessageConsumer consumer;
private final Listener listener;
public QueueContainer(final Connection dbConnection ) {
try {
this.dbConnection = dbConnection;
queueConnection = AQjmsQueueConnectionFactory.createQueueConnection(dbConnection);
queueSession = queueConnection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
queue = ((AQjmsSession) queueSession).getQueue(context.getEnvironment(), QUEUE_NAME);
consumer = queueSession.createConsumer(queue);
listener = new Listener(QUEUE_NAME);
consumer.setMessageListener(listener);
queueConnection.setExceptionListener(listener);
} catch (JMSException | SQLException e) {
throw new RunTimeException("Queue Exception", e);
}
}
public void startListening() {
try {
queueConnection.start();
} catch (JMSException e) {
throw new RunTimeException("Failed to start listening to queue", e);
}
}
public void stopListening() {
try {
queueConnection.stop();
} catch (JMSException e) {
throw new RunTimeException("Failed to stop listening to queue", e);
}
}
public void close() {
if (queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e) {
throw new RunTimeException("Failed to stop listening to queue", e);
}
}
}
public boolean isRunning() {
try {
// This doesn't work - I can't distinguish between started and stopped
return queueConnection.getClientID() != null;
} catch (JMSException e) {
LOGGER.warn("Failed to get queue client ID", e);
return false;
}
}
I can't see what to put in isRunning that could distinguish between a stopped and started listener
The JMS API assumes you know yourself what you did. So why not add a boolean flag and keep track of this ?
private volatile boolean isListening = false;
...
public void startListening() {
try {
queueConnection.start();
isListening = true;
} catch (JMSException e) {
throw new RunTimeException("Failed to start listening to queue", e);
}
}
public void stopListening() {
try {
queueConnection.stop();
isListening = false;
} catch (JMSException e) {
throw new RunTimeException("Failed to stop listening to queue", e);
}
}
public void close() {
if (queueConnection != null) {
try {
queueConnection.close();
isListening = false;
} catch (JMSException e) {
throw new RunTimeException("Failed to stop listening to queue", e);
}
}
}
public boolean isRunning() {
return isListening;
}
There is no JMS API call to determine whether or not a javax.jms.Connection is started.
To be clear, the queue itself is not the entity that is started or stopped. The connection is started or stopped.
You may be able to get this information from the Oracle Advanced Queue implementation object, but I'm not familiar with that implementation so I can't say. Obviously any solution using an implementation object rather than the standard API will not be portable.

Server closes after one client disconnect (JAVA)

My server closes after one clients disconnects,and I can write only one more message then it crashes.I wonder why,since I only close the client socket when it types "EXIT SERVER" .This is the exception it throws:
java.io.EOFException
This is my code :
import java.net.*;
import java.io.*;
public class ServerPeer extends Thread {
Socket _socket;
String username;
public ServerPeer(Socket _socket) {
this._socket = _socket;
}
public void sendMessage(String _username, String _message) throws IOException {
ObjectOutputStream _obj = new ObjectOutputStream(
_socket.getOutputStream());
_obj.writeObject(new Message(_username, _message));
_obj.flush();
}
public synchronized void run() {
try {
ObjectInputStream _ois = new ObjectInputStream(_socket.getInputStream());
Message _message;
while (_socket.isConnected()) {
_message = (Message) _ois.readObject();
String divide = _message.getAll().substring(0, _message.getAll().indexOf(":"));
username = divide;
Server.listofusers.add(username);
for (ServerPeer sp : Server.listofpeers) {
if (_message.getAll().contains("EXIT SERVER")) {
Server.listofpeers.remove(sp);
_socket.close();
}
if (_message instanceof PrivateMessage) {
PrivateMessage privm = (PrivateMessage) _message;
for (ServerPeer sp2 : Server.listofpeers) {
if (sp2.username.equals(privm.getReceiver())) {
sp2.sendMessage(divide, privm.getAll());
String priv = privm.getAll().replaceAll("/w", "");
System.out.println(priv);
break;
}
}
} else {
sp.sendMessage(divide, _message.getAll());
System.out.println(_message.getAll());
}
}
_ois = new ObjectInputStream(_socket.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Server Class:
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
static ServerConfig _svconfig = new ServerConfig();
public static ArrayList<ServerPeer> listofpeers = new ArrayList<ServerPeer>();
public static ArrayList<String> listofusers = new ArrayList<String>();
public static int i = 0;
// final static int _mysocket;
public static void main(String[] args) {
try {
final int _mysocket = _svconfig.getPORTNumber();
System.out.println("Wainting for clients.....");
ServerSocket _serversocket = new ServerSocket(_mysocket, _svconfig.getCLIENTSNumber());
while (listofpeers.size() <= _svconfig.getCLIENTSNumber()) {
Socket _clientsocket = _serversocket.accept();
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.start();
listofpeers.add(_serverpeer);
}
_serversocket.close();
} catch (MissingKeyException e) {
e.printStackTrace();
} catch (UnknownKeyException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (ConnectException e) {
e.printStackTrace();
} catch (BindException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (SocketException e) {
System.out.println("You have been disconnected");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
EDIT:
Exception thrown in the console of the client who disconnects:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2328)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2797)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:802)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at ClientPeer.serverEcho(ClientPeer.java:35)
at ClientPeer.run(ClientPeer.java:44)
BUILD STOPPED (total time: 1 minute 26 seconds)
From what I can tell i'd guess your code is incorrect, but it hard to tell without more code.
At first glance it seems that if too many people connect to your server you just shut down the entire server not just those connections.
while (listofpeers.size() <= _svconfig.getCLIENTSNumber()) {
Socket _clientsocket = _serversocket.accept();
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.start();
listofpeers.add(_serverpeer);
}
_serversocket.close();
A better approach would be something like the following. If too many users try to connect, just close the users connection.
ServerSocket _serversocket = new ServerSocket(_mysocket, _svconfig.getCLIENTSNumber());
boolean alive = true;
while (alive) {
try {
//Keep accepting connection request
Socket clientRequest = _serversocket.accept();
//Check if too many user are connected
if (listofpeers.size() <= _svconfig.getCLIENTSNumber()) {
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.start();
listofpeers.add(_serverpeer);
}else{
//Reject connection if too many connected
clientRequest.close();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
//When server dead close it down
_serversocket.close();
Hope this helps.
Your code must be exiting after the client thread is terminated, create a thread that has the server accept method that starts the client thread, something like this,
/**
*/
private class ServerListener extends Thread
{
/**
*/
public void run()
{
try
{
Socket clientSocket = socket.accept();
System.out.println("client connected => "+clientSocket.getInetAddress().getHostAddress());
ServerListener th = new ServerListener();
th.start();
ClientThread cth = new ClientThread(clientSocket);
cth.start();
clients.add(cth);
return;
}
catch (Exception e)
{
e.printStackTrace();
//Main.getInsatance().println(e);
//Main.getInstance().println("socket disconnected => "+clientSocket.getInetAddress().getHostAddress());
}
}
}

Java application and AMD processor issues

We have a windows application, which was tested on Windows XP, 7, 8, 8.1. Application consists of 2 parts: Bootstrap and main application. Bootstrap assures updates of the main app, and updates main app at a particular point. But users were able to force stop Boostrap process via the Task Manager (Ctrl+Shift+ESC->processes) by killing a process named javaw. In that case main app would not update and elder version would be launched. To avoid such issue we introduced interface of Bootstrap with main application via Socket. Here are the VM parameters of Bootstrap when it starts:
javaw.exe -Xms75M -Xmx90M -Xincgc -jar bootstrap.jar
There is a class SocketServer in the bootstrap:
public class Provider {
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
public Provider() {
}
public void run() {
try{
providerSocket = new ServerSocket(54345);
connection = providerSocket.accept();
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
do {
try {
message = (String)in.readObject();
if (message.equals("bye")) {
sendMessage("bye");
}
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
} while (!message.equals("bye"));
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
try {
in.close();
out.close();
providerSocket.close();
} catch(IOException ioef) {
ioef.printStackTrace();
}
}
}
public void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public void stop() {
if (providerSocket != null && in != null && out != null && !providerSocket.isClosed()) {
try {
in.close();
out.close();
providerSocket.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Main app is being started by Bootstrap via ProcessBuilder like so:
public static void communicate(Process process) {
final BufferedReader stdOut = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("Windows-1251")));
final BufferedReader stdErr = new BufferedReader(new InputStreamReader(process.getErrorStream(), Charset.forName("Windows-1251")));
//InputStream
new Thread() {
#Override
public void run() {
String line;
try {
while ((line = stdOut.readLine()) != null) {
debugOut(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
stdOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}.start();
//ErrorStream
new Thread() {
#Override
public void run() {
String line;
try {
while ((line = stdErr.readLine()) != null) {
debugOut(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
stdErr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}.start();
try {
final Provider provider = new Provider();
ExecutorService pEexec = Executors.newCachedThreadPool();
Future<Void> FPExec = pEexec.submit(new Callable<Void>() {
#Override
public Void call() throws Exception {
while (!Thread.currentThread().isInterrupted()) {
provider.run();
}
return null;
}
});
pEexec.shutdown();
process.waitFor();
debugOut("[MainApp] Exit");
provider.stop();
FPExec.cancel(true);
debug("Destroy process");
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void startApp() {
try {
ArrayList<String> params = new ArrayList<String>();
...
params.add("-Xms32M");
params.add("-Xmx48M");
params.add("-Xincgc");
params.add("-cp");
params.add(new File(pathToJar, "mainapp.jar").getPath());
params.add("net.craftwork.mainapp.AppStart");
params.add(licCode());
ProcessBuilder procBuild = new ProcessBuilder(params);
debugOut("[MainApp] Start");
Process proc = procBuild.start();
communicate(proc);
} catch (Exception e) {
e.printStackTrace();
}
}
There is a class SocketClient in the main app:
public class Requester {
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
static Future<Void> oExec;
Requester() {
}
void run() {
try {
requestSocket = new Socket("localhost", 54345);
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
do {
try {
message = (String)in.readObject();
sendMessage("bye");
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
} while (!message.equals("bye"));
} catch(UnknownHostException uhe) {
uhe.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
oExec.cancel(true);
CommonUtils.debug("Bootstrap not found. Exit.");
System.exit(0);
} finally {
try {
in.close();
out.close();
requestSocket.close();
} catch(IOException ioef) {
ioef.printStackTrace();
}
}
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public static void main() {
final Requester client = new Requester();
ExecutorService exec = Executors.newCachedThreadPool();
oExec = exec.submit(new Callable<Void>() {
#Override
public Void call() throws Exception {
while (!Thread.currentThread().isInterrupted()) {
client.run();
Thread.sleep(1000);
}
return null;
}
});
exec.shutdown();
}
}
Socket Client is called when main application starts
public class AppStart {
public static void main(final String[] args) {
Requester.main();
EventQueue.invokeLater(new Runnable() {
public void run() {
...
}
});
}
}
This is all to it I do believe. Whole setup worked perfectly fine, even on slower computers. Problem is that after introduction of Socket interface we had major complaints from some users, reporting crashes. Took us some time to figure out the issue, but here is what we found: computers with Intel processors are perfectly fine, only ones with AMD processors crash. Crash normally happens within 3 to 15 minutes from the start of Bootstrap. When crash occurs resources of the computer are not fully used, processor workload is about 20-50% and RAM is quite free as well. When crash occurs user is only able to reset computer using hardware reset or power button, nothing else responds. All users have latest JAVA 1.7.0_51. Whether system is 32 or 64 bit does both crash (or not crash if it is Intel based). Please share your thoughts. May be someone had identical issues and could help me to figure this out.

Retrieve GPS DATA on a JTextArea with 2 different class

I have a a GPS receptor. I create a class to retrieve all the GPS data on my Eclipse Console.
(This is the code of makia42)
public class COM implements Runnable{
static Thread myThread=null;
static BufferedReader br;
static BufferedWriter wr;
static InputStreamReader isr;
static OutputStreamWriter osw;
static java.io.RandomAccessFile port;
public COM(){ /**Constructeur*/
myThread=new Thread(this);
}
public void start(){
try {
port=new java.io.RandomAccessFile("COM3","rwd");
port.writeBytes("\r\n");
port.writeBytes("c,31,0,0,5\r\n");
port.writeBytes("T,1000,1\r\n");
}
catch (Exception e) {
System.out.println("start "+e.toString());
}
myThread.start();
}
public void run() {
System.out.println("lecture COM...");
for(;;){
String st = null;
try {
st=port.readLine();
} catch (IOException e) {System.out.println(e.getMessage());}
System.out.println(st);
}
}
public static void main(String[] args) {
COM temp= new COM();
temp.start();
}
}
I have another class which is a frame containing a button and a JTextArea. This class is in communication with my first class COM.
When i click the button, COM is starting and show me the data in my Eclipse Console.
But now, I'd like to show it on my JTextArea.
How can I do it ?
Best regards,
Tofuw
Take a moment to read about this pattern.
Make the Thread a Subject. Before starting register the instance of the class that contains the JTextArea as the Observer with the instance of the Thread. At the run() instead of printing on the console, use the notify(String);
public void run() {
System.out.println("lecture COM...");
for(;;){
String st = null;
try {
st=port.readLine();
} catch (IOException e) {System.out.println(e.getMessage());}
System.out.println(st);
}
}
Change to
public void run() {
System.out.println("lecture COM...");
for(;;){
String st = null;
try {
st=port.readLine();
} catch (IOException e) {System.out.println(e.getMessage());}
notifyObservers(st); //Pass the data to the observers.
}
}
EDIT:
I suppose you can rewrite the Thread to a simple class. It will render the program unresponsive while it reads, that's why you have a Thread. I suppose you can implement a cleaner way using Future<String>
public class GpsReader {
public class GenericGPSException extends Exception {
public GenericGPSException(String message, Throwable cause) {
super(message, cause);
}
}
public static void main(String[] args) {
// Example of usage
GpsReader gpsReader = new GpsReader();
String messageFromDevice;
try {
// Try read it
messageFromDevice = gpsReader.getCoordinate();
} catch (GenericGPSException e) {
// Error, what does it says?
messageFromDevice = e.getMessage();
}
JTextArea mockArea = new JTextArea();
// Show to user anything that comes to it.
mockArea.setText(messageFromDevice);
}
private boolean isReady;
private RandomAccessFile port;
public GpsReader() {
}
public String getCoordinate() throws GenericGPSException {
if (!isReady) {
try {
port = new RandomAccessFile("COM3", "rwd");
port.writeBytes("\r\n");
port.writeBytes("c,31,0,0,5\r\n");
port.writeBytes("T,1000,1\r\n");
isReady = true;
} catch (FileNotFoundException e) {
throw new GenericGPSException(
"Error at starting communication to Device ", e);
} catch (IOException e) {
throw new GenericGPSException(
"Error at starting communication to Device ", e);
}
}
try {
return port.readLine();
} catch (IOException e) {
throw new GenericGPSException("Error at reading the Device ", e);
}
}
}

Problem with cleaning up a thread pool

I have a server in Java which is multithreading, and I've created a thread pool for it.
Now everything goes well and my server accepts and reads data from the clients that connect to it, but I don't know really how to clean up the sockets after the connections are closed.
So here is my code:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ThreadPooledServer server = new ThreadPooledServer(queue,7001);
new Thread(server).start();
}
ThreadPooledServer class:
public class ThreadPooledServer implements Runnable {
protected ExecutorService threadPool = Executors.newFixedThreadPool(5);
public ThreadPooledServer(BlockingQueue queue,int port) {
this.serverPort = port;
this.queue=queue;
}
public void run() {
openServerSocket();
while (!isStopped()) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
clientconnection++;
} catch (IOException e) {
if (isStopped()) {
System.out.println("Server Stopped.");
return;
}
throw new RuntimeException("Error accepting client connection", e);
}
WorkerRunnable workerRunnable = new WorkerRunnable(queue,clientSocket);
this.threadPool.execute(workerRunnable);
}
this.threadPool.shutdown();
System.out.println("Server Stopped.");
}
private synchronized boolean isStopped() {
return this.isStopped;
}
public synchronized void stop() {
this.isStopped = true;
try {
this.serverSocket.close();
}
catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
Here's what I don't understand: My while() loop that accepts for clients works as loong as isStopped is false.
When isStopped is set to true, my loop ends and then I shut down my thread pool, which is correct.
isStopped is set to true in onstop(){..............}....
Where should I call onstop()...?
Because in this moment I'm not using this method ,I'm not calling it and that means that I'm not cleaning correctly my threads.
WorkerRunnable class:
public class WorkerRunnable implements Runnable {
public WorkerRunnable(BlockingQueue queue2, Socket clientSocket2) {
// TODO Auto-generated constructor stub
this.clientSocket2 = clientSocket2;
this.queue2 = queue2;
}
public void run() {
try {
is = new ObjectInputStream(this.clientSocket2.getInputStream());
try {
while (!stop) {
System.out.println("Suntem in interiorul buclei while:!");
v = (Coordinate) is.readObject();
queue2.put(v);
}
} catch (Exception e) {
e.printStackTrace();
is.close();
clientSocket2.close();
}
is.close();
clientSocket2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() {
this.stop = true;
}
}
}
Here I have the same issue. How should I clean and close up my sockets correctly?
Once you call shutdown() the thread pool will close off each thread once all the tasks are complete.
You should call onstop() from whatever code knows the pool should be shutdown. This depends on what the rest of your application does and why you would stop the pool before the application has finished.

Categories

Resources