I made an alert function which gets price data from websocket and send alert if condition is fulfilled.
I only have "price condition" now, and I want to add "percentage Condition".
So What I'm trying to do is
Open a websocket
get the first data, calculate the limitation price
for Example) user wants to get alert when price is 5% down.
open the websocket, current price is 100$
So I need to send alert to user when price hits 95$(limitation price)
To do so, I need to compute limitation price when opening the websocket.
But I can't figure out "where and how" can I store limitation price..
This is my websocket code implementing price condition(not "percentage condition")
WebSocketClientEndPoint
#ClientEndpoint
public class WebsocketClientEndpoint {
Session userSession = null;
private MessageHandler messageHandler;
public WebsocketClientEndpoint() {
}
public Session connect(URI endpointURI) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
userSession = container.connectToServer(this, endpointURI);
return userSession;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Callback hook for Connection open events.
*
* #param userSession the userSession which is opened.
*/
#OnOpen
public void onOpen(Session userSession) {
System.out.println("opening websocket");
this.userSession = userSession;
}
/**
* Callback hook for Connection close events.
*
* #param userSession the userSession which is getting closed.
* #param reason the reason for connection close
*/
#OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println("closing websocket");
this.userSession = null;
}
/**
* Callback hook for Message Events. This method will be invoked when a client send a message.
*
* #param message The text message
*/
#OnMessage
public void onMessage(String message) throws ParseException, IOException {
if (this.messageHandler != null) {
this.messageHandler.handleMessage(message);
}
}
#OnMessage
public void onMessage(ByteBuffer bytes) {
System.out.println("Handle byte buffer");
}
/**
* register message handler
*
* #param msgHandler
*/
public void addMessageHandler(MessageHandler msgHandler) {
this.messageHandler = msgHandler;
}
/**
* Send a message.
*
* #param message
*/
public void sendMessage(String message) {
this.userSession.getAsyncRemote().sendText(message);
}
/**
* Message handler.
*
* #author Jiji_Sasidharan
*/
public static interface MessageHandler {
public void handleMessage(String message) throws ParseException, IOException;
}
}
AlertUserByPrice
public void AlertUserByPrice(Long id) {
Alert alert = alertRepository.findById(id).orElseThrow(() -> new NoSuchElementException());
String type = alert.getAlertType().getKey();
double SetPrice = alert.getPrice();
String ticker = alert.getTicker();
JSONParser jsonParser = new JSONParser();
final NotificationRequest build;
if (type == "l_break") {
build = NotificationRequest.builder()
.title(ticker + " alert")
.message(SetPrice + "broke down")
.token(notificationService.getToken(userDetailService.returnUser().getEmail()))
.build();
}
else { // upper_break
build = NotificationRequest.builder()
.title(ticker + " alert")
.message(SetPrice + "pierced upward")
.token(notificationService.getToken(userDetailService.returnUser().getEmail()))
.build();
}
try {
final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint();
Session session = clientEndPoint.connect(new URI("wss://ws.coincap.io/prices?assets=" + ticker));
WebsocketClientEndpoint.MessageHandler handler = new WebsocketClientEndpoint.MessageHandler() {
public void handleMessage(String message) throws ParseException, IOException {
Object obj = jsonParser.parse(message);
JSONObject jsonObject = (JSONObject) obj;
double price = Double.parseDouble(jsonObject.get(ticker).toString());
System.out.println("가격 : " + price);
if (type == "l_break") {
if (price < SetPrice) {
System.out.println("끝");
notificationService.sendNotification(build);
session.close();
}
} else {
if (price > SetPrice) {
System.out.println("끝");
notificationService.sendNotification(build);
session.close();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.err.println("InterruptedException exception: " + ex.getMessage());
}
}
};
clientEndPoint.addMessageHandler(handler);
} catch (URISyntaxException ex) {
System.err.println("URISyntaxException exception: " + ex.getMessage());
}
}
what should I do to implement "alert by perentage condition"?? Someone please help..
Thanks in advance
double percent = 0.05;
if (price-(price*percent) < SetPrice) {
System.out.println("끝");
notificationService.sendNotification(build);
session.close();
}
if (price-(price*percent) > SetPrice) {
System.out.println("끝");
notificationService.sendNotification(build);
session.close();
}
Try if this helps
Related
I am trying to establish a WebSocket connection in my servlet. I receive some callback messages from the server, but only very few. I call a Thread.sleep(30000), so the servlet should wait 30 seconds for new messages, but it seems not wait for some reason.
This is the code in my Servlet:
try {
// open websocket
final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("wss://www.bitmex.com/realtime"));
// add listener
clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
public void handleMessage(String message) {
System.out.println(message);
logger.info("WEBSOCKET MSG: "+message);
}
});
// send message to websocket
clientEndPoint.sendMessage("{\"op\": \"subscribe\", \"args\": \"trade\"}");
// wait 30 seconds for messages from websocket
Thread.sleep(30000);
} catch (InterruptedException ex) {
System.err.println("InterruptedException exception: " + ex.getMessage());
} catch (URISyntaxException ex) {
System.err.println("URISyntaxException exception: " + ex.getMessage());
}
And this is my WebsocketClientEndpoint code:
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
#ClientEndpoint
public class WebsocketClientEndpoint {
Session userSession = null;
private MessageHandler messageHandler;
public WebsocketClientEndpoint(URI endpointURI) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, endpointURI);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Callback hook for Connection open events.
*
* #param userSession the userSession which is opened.
*/
#OnOpen
public void onOpen(Session userSession) {
System.out.println("opening websocket");
this.userSession = userSession;
}
/**
* Callback hook for Connection close events.
*
* #param userSession the userSession which is getting closed.
* #param reason the reason for connection close
*/
#OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println("closing websocket");
this.userSession = null;
}
/**
* Callback hook for Message Events. This method will be invoked when a client send a message.
*
* #param message The text message
*/
#OnMessage
public void onMessage(String message) {
if (this.messageHandler != null) {
this.messageHandler.handleMessage(message);
}
}
public void addMessageHandler(MessageHandler msgHandler) {
this.messageHandler = msgHandler;
}
public void sendMessage(String message) {
this.userSession.getAsyncRemote().sendText(message);
}
public static interface MessageHandler {
public void handleMessage(String message);
}
}
What's the right way to do it? Or could this be some issue with App Engine (Standard Environment)?
Trying to perform an application that reads sms from gsm modem each a period of time.
Thought about this solution:
Got 2 Threads in my application.
T1)- GSMModemHandler which is a handler for serial communications.
T2)- SMSPicker that requests for sms each period of time and perform some string algorithms on them.
I want my application to do so:
A)- T2 asks for sms using readAllMessages(), a method from the GSMModemHandler class and then keeps blocked.
B)- T1 has got a SerialEventListener, so it listens for the response to the request sent from the GSM-Modem, and sends it back to T2.
C)- Once the response is available in a list from the T2 class, T2 resume its task concerning the string algorithms and then do again the same operations from A after waiting a certain period of time.
I've tried to code that, when i launch the application, it does its work for some time and then blocks, i guess the problem come from a missunderstanding between the 2 Threads, but can't find where the problem is and how to solve it.
Here's my code, and the result:
public class GSMModemHandler extends SerialPort implements
SerialPortEventListener{
private static final String
COMMAND_REMISE_A_ZERO = "ATZ",
COMMAND_SMS_MODE_TEXT = "AT+CMGF=1",
COMMAND_DETAILED_ERRORS = "AT+CMEE=1",
COMMAND_SET_UP_MEMORIES = "AT+CPMS=\"MT\",\"MT\",\"MT\"",
COMMAND_LIST_SUPPORTED_STORAGE_MODES = "AT+CPMS=?",
COMMAND_ENVOIE_SMS = "AT+CMGS=",
COMMAND_GET_ALL_SMS = "AT+CMGL=\"ALL\"",
COMMAND_GET_NEW_SMS = "AT+CMGL=\"REC UNREAD\"",
COMMAND_DELETE_ALL_MESSAGES = "AT+CMGD=0[,4]",
COMMAND_DELETE_READ_MESSAGES = "AT+CMGD=0[,1]";
private SMSPicker smsPicker = null;
private String response = "";
public GSMModemHandler(String port) throws SerialPortException{
super(port);
this.openPort();
this.setParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
this.addEventListener(this);
this.startGsm();
}
public void startGsm() throws SerialPortException{
this.writeString(GSMModemHandler.COMMAND_REMISE_A_ZERO + "\r\n");
this.writeString(GSMModemHandler.COMMAND_SMS_MODE_TEXT + "\r\n");
this.writeString(GSMModemHandler.COMMAND_DETAILED_ERRORS + "\r\n");
this.writeString(GSMModemHandler.COMMAND_SET_UP_MEMORIES + "\r\n");
}
public void sendMessage(SMS sms){
try{
if(this.isOpened()){
this.writeString(GSMModemHandler.COMMAND_ENVOIE_SMS + "\"" + sms.getCorrespondantSms() + "\"\r\n");
this.writeString(sms.getContenuSms() + '\032');
}
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
public void readAllMessages(){
try{
if(this.isOpened())
this.writeString(GSMModemHandler.COMMAND_GET_ALL_SMS + "\r\n");
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
public void readUnreadMessages(){
try{
if(this.isOpened())
this.writeString(GSMModemHandler.COMMAND_GET_NEW_SMS + "\r\n");
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
public void deleteAllMessages(){
try{
if(this.isOpened())
this.writeString(GSMModemHandler.COMMAND_DELETE_ALL_MESSAGES + "\r\n");
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
public void deleteReadMessages(){
try{
if(this.isOpened())
this.writeString(GSMModemHandler.COMMAND_DELETE_READ_MESSAGES + "\r\n");
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
public synchronized void fermerConnexion(){
try{
this.closePort();
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
AtomicBoolean nextResponseIsSms = new AtomicBoolean(false);
#Override
public void serialEvent(SerialPortEvent spe) {
try {
String reponse = this.readString();
System.out.println("GSM response = " + reponse);
// If the next response contains the wanted sms
if(reponse != null && reponse.contains("AT+CMGL=")){
this.nextResponseIsSms.set(true);
System.out.println("nextResponseIsSms = true");
}
// if the response contains sms
else if(this.nextResponseIsSms.get()){
this.smsPicker.getResponse().add(reponse);
System.out.println("response sent !");
this.deleteAllMessages(); // deleting the sms in the gsm modem
System.out.println("messages deleted");
this.nextResponseIsSms.set(false);
System.out.println("nextResponseIsSms = false");
// gives the SMSPicker the hand to treat the response
synchronized(this.smsPicker){ this.smsPicker.notify(); }
System.out.println("smsPicker notified");
}
} catch (SerialPortException ex) {
Logger.getLogger(GSMModemHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #return the smsPicker
*/
public SMSPicker getSmsPicker() {
return smsPicker;
}
/**
* #param smsPicker the smsPicker to set
*/
public void setSmsPicker(SMSPicker smsPicker) {
this.smsPicker = smsPicker;
}
}
public class SMSPicker extends ControlledThread{
private GSMModemHandler modemGsm;
private SMSQueueToDatabase smsQueueHandler;
private volatile Queue<String> responses = new LinkedList<String>();
public SMSPicker(double frequency, GSMModemHandler gsmModem){
super(frequency);
this.modemGsm = gsmModem;
this.modemGsm.setSmsPicker(this);
this.smsQueueHandler = new SMSQueueToDatabase(frequency);
}
#Override
public void whatToDoBeforeTheLoop(){
this.smsQueueHandler.start();
try {
this.wait(2 * this.waitingPeriod.get());
} catch (InterruptedException ex) {
Logger.getLogger(SMSPicker.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void whatToDoDuringTheLoop() throws NullPointerException{
synchronized(this){
try {
System.out.println("I'm going to launch the request !");
// Sending the sms read request to the gsm modem
this.modemGsm.readAllMessages();
System.out.println("i'm going to be stopped!");
// wait till we get the answer
this.wait();
System.out.println("I've been stopped and now resuming");
}
catch (InterruptedException ex) {
Logger.getLogger(SMSPicker.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Treating the response in order to extract sms from it
while(!this.responses.isEmpty()){
String longMessage = this.responses.poll();
if(longMessage != null){
String[] shortMessages = null;
shortMessages = longMessage.split("\\+CMGL: [0-9]*,\"");
if(shortMessages == null) continue;
for(String shortMessage: shortMessages){
int indexLastOK = shortMessage.lastIndexOf("OK");
if(indexLastOK != -1 && shortMessage.contains("+"))
this.smsQueueHandler.getSmsFifo().add(this.fromStringToSms(shortMessage
.substring(0,shortMessage.lastIndexOf("OK") - 2))); // if it is the last sms
else if(shortMessage.contains("REC")) // if it is not the last one
this.smsQueueHandler.getSmsFifo().add(this.fromStringToSms(shortMessage));
}
}
}
}
private SMS fromStringToSms(String stringSms){
String[] smsParts = stringSms.split(",");
String correspondantSms = smsParts[1].replaceAll("\"", "");
String dateSms = smsParts[3].replace("\"","").replaceAll("/", "-");
String heureSms = smsParts[4].substring(0,smsParts[4].lastIndexOf("\"")).substring(0, 8);
String contenuSms = stringSms.substring(stringSms.lastIndexOf("\"") + 3);
LocalDateTime momentSms = LocalDateTime.parse("20" + dateSms + "T" + heureSms);
return new SMS(correspondantSms,contenuSms,momentSms);
}
#Override
public void whatToDoAfterTheLoop() {
}
/**
* #return the modemGsm
*/
public GSMModemHandler getModemGsm() {
return modemGsm;
}
/**
* #param modemGsm the modemGsm to set
*/
public void setModemGsm(GSMModemHandler modemGsm) {
this.modemGsm = modemGsm;
}
/**
* #return the smsQueueHandler
*/
public SMSQueueToDatabase getSmsQueueHandler() {
return smsQueueHandler;
}
/**
* #param smsQueueHandler the smsQueueHandler to set
*/
public void setSmsQueueHandler(SMSQueueToDatabase smsQueueHandler) {
this.smsQueueHandler = smsQueueHandler;
}
/**
* #return the response
*/
public Queue<String> getResponse() {
return responses;
}
/**
* #param response the response to set
*/
public void setResponse(Queue<String> responses) {
this.responses = responses;
}
}
public abstract class ControlledThread extends Thread{
protected AtomicBoolean workable = null;
protected AtomicLong waitingPeriod = null;
public ControlledThread(double frequency){
super();
this.workable = new AtomicBoolean(true);
this.waitingPeriod = new AtomicLong(((long)(1000 / frequency)));
}
#Override
public synchronized void run() {
this.whatToDoBeforeTheLoop();
while(this.workable.get()){
try{
this.whatToDoDuringTheLoop();
this.wait(this.waitingPeriod.get());
}
catch(InterruptedException exp){
exp.printStackTrace();
}
}
this.whatToDoAfterTheLoop();
}
public void stopWorking(){
this.workable.set(false);
}
public synchronized boolean isWorking(){
return this.workable.get();
}
public abstract void whatToDoBeforeTheLoop();
public abstract void whatToDoDuringTheLoop();
public abstract void whatToDoAfterTheLoop();
}
Result:
Note: The blocking state happens at the red line (BUILD STOPPED is just a result of the fact that i stopped the application by a kill)
Thanks in advance !
Most likely, you're experiencing a missed signal : you start waiting for a notify() that has already happened.
This is because you start waiting unconditionally. You should, however, always wait from within a loop that checks its wait condition.
In your case the contion to keep waiting is probably until an answer has been supplied.
so :
while (!hasAnswer()) {
this.wait();
}
You must also make sure that the monitor you synchronize on (the SMSPicker in your case) properly guards the state that determines the condition. Since you simply seem expose the response queue, it think it's likely not the case, but I'm missing too many details to say for sure.
For a more detailed explanation look here.
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
// Check for closing frame
if (frame instanceof CloseWebSocketFrame) {
handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
return;
}
if (frame instanceof PingWebSocketFrame) {
ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
return;
}
if (!(frame instanceof TextWebSocketFrame)) {
throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
.getName()));
}
// Send the uppercase string back.
String request = ((TextWebSocketFrame) frame).text();
if (logger.isLoggable(Level.FINE)) {
logger.fine(String.format("%s received %s", ctx.channel(), request));
}
Message msg = new Message(ctx.channel(), request);
ReadQueueHandler.getInstance().addMessageToProcess(msg);
}
public class ReadQueueHandler implements Runnable {
private static int POOL_SIZE = 3;
private static ReadQueueHandler instance;
private final BlockingQueue<Message> messageQueue;
private final ExecutorService threadPool;
private final int threadPoolSize;
private final boolean isActive;
private ReadQueueHandler() {
this.threadPoolSize = POOL_SIZE;
this.threadPool = Executors.newFixedThreadPool(threadPoolSize);
this.messageQueue = new LinkedBlockingQueue<Message>();
isActive = true;
initThreadPool();
}
private void initThreadPool() {
for (int i = 0; i < this.threadPoolSize; i++) {
this.threadPool.execute(this);
}
}
/**
* Add message to read queue
*
* #param message
* - adding message
*/
public void addMessageToProcess(Message message) {
if (message != null) {
this.messageQueue.add(message);
}
}
#Override
public void run() {
while (isActive) {
Message message = null;
try {
message = this.messageQueue.take();
} catch (InterruptedException e) {
System.out.println("Exceptio " + e);
/*
* TODO Add logging
*/
}
if (message != null) {
Channel channel = message.getChannel();
channel.write(new TextWebSocketFrame("Message handled "));
}
}
}
public static ReadQueueHandler getInstance() {
if (instance == null) {
instance = new ReadQueueHandler();
}
return instance;
}
}
If i execute Channel.write("something") instead of adding data to queue, then all work fine and client get data. But if Channel.write("") execute from another thread, than data is not got. What can be reason? Channel write can not be execute from another thread?
For me it seems like you forgot to call flush() after the write is done to guaranteer it's flushed to the socket. For example you could fix this by use:
channel.writeAndFlush(new TextWebSocketFrame("Message handled "));
import java.util.concurrent.CountDownLatch;
import quickfix.Initiator;
public class UserSession {
private final CountDownLatch latch = new CountDownLatch(1);
public String await() {
try {
System.out.println("waiting...");
if (latch.await(5, TimeUnit.SECONDS))
System.out.println("released!");
else
System.out.println("timed out");
return secret;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
public void countdown(String s) {
System.out.println("In countdown: "+s+ ". Latch count: "+latch.getCount());
secret = s;
latch.countDown();
System.out.println("Latch count: "+latch.getCount());
}
}
public class LogonHandler extends AbstractHandler {
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
Map<String,String[]> query = request.getParameterMap();
if (query.containsKey("method")) {
if (query.get("method")[0].compareTo(method) == 0) {
baseRequest.setHandled(true);
response.getWriter().println(logon(query));
}
}
else
baseRequest.setHandled(false);
}
private String logon(Map<String,String[]> query) {
if (query.containsKey("username") && query.containsKey("password") && query.containsKey("sendercompid")) {
app.mapUser(query.get("sendercompid")[0], new UserSession(query.get("username")[0], query.get("password")[0]));
SessionID session = new SessionID(new BeginString("FIX.4.4"), new SenderCompID(query.get("sendercompid")[0]), new TargetCompID("PARFX"));
try {
ThreadedSocketInitiator tsi = new ThreadedSocketInitiator(app, app.getFileStoreFactory(), settings, app.getLogFactory(), app.getMessageFactory());
UserSession userSession = new UserSession(query.get("username")[0], query.get("password")[0]);
userSession.setInitiator(tsi);
tsi.start();
return userSession.await();
} catch (ConfigError e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
}
return "fail";
}
}
public class QuickfixjApplication implements Application {
private Map<String,UserSession> users = new HashMap<String,UserSession>();
public void mapUser(String s, UserSession u) {
users.put(s, u);
}
public void toAdmin(Message message, SessionID sessionId) {
try {
if (message.getHeader().getField(new StringField(MsgType.FIELD)).valueEquals(Logon.MSGTYPE)) {
UserSession user = users.get(sessionId.getSenderCompID());
message.setField(new Username(user.getUsername()));
message.setField(new Password(user.getPassword()));
}
} catch (FieldNotFound e) {
e.printStackTrace();
}
}
public void fromAdmin(Message message, SessionID sessionId)
throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, RejectLogon {
if (message.getHeader().getField(new StringField(MsgType.FIELD)).valueEquals(Logon.MSGTYPE)) {
System.out.println(message.toString());
UserSession user = users.get(sessionId.getSenderCompID());
user.countdown(message.toString());
}
}
}
Ok, I've tried to only include the minimum amount of code here. There are three interesting classes, UserSession is the internal glue between the Jetty handler and the QuickFix/j application.
The LogonHandler receives an HTTP logon request and tries to log a user onto a QuickFix/j application session.
QuickFix/j is sending a logon message to a FIX server, this logon request / response is asynchronous. The HTTP logon request is of course synchronous. So we have to wait for the reply from the FIX server before we return from the HTTP request. I do this using CountDownLatch and this UserSession object.
When I create the QuickFix/j session object I also create a UserSession object and add it to a map (that happens in the LogonHandler logon method).
There are two callbacks in the QuickFix/j application object, toAdmin() and fromAdmin(). In fromAdmin() I check if the message is a logon response and if it is I call a method of UserSession to countdown the latch. In debugging the code I see that the fromAdmin() method is hit, the UserSession object is found in the map and the countdown() method is called and the latch.getCount() goes from 1 to 0, but the latch.await() method in UserSession await() never returns. It always times out.
You could use CountDownLatch like this:
public class LogonHandler implements Handler {
private final CountDownLatch loginLatch = new CountDownLatch (1);
private boolean callbackResults;
public void serverResponseCallback(boolean result) {
callbackResults = result;
loginLatch.countDown ();
}
public boolean tryLogon(Credentials creds) throws InterruptedException {
SomeServer server = new SomeServer(address);
server.tryLogon (creds.getName (), creds.getPass ());
loginLatch.await ();
return callbackResults;
}
}
If you want to limit waiting time by, for example, 5 seconds, then instead of loginLatch.await () use the following:
if (loginLatch.await (5L, TimeUnit.SECONDS))
return callbackResults;
else
return false; // Timeout exceeded
I am having a run method which tries to override another run method. But its not happening because I am getting a "Class not found Exception" before it passed on to run method.
Here´s my class with run method
public class PollingSynchronizer implements Runnable{
public Collection<KamMessage> incomingQueue,outgoingQueue,fetchedMessages;
private Connection dbConnection;
/**
* Constructor. Requires to provide a reference to the Kam message queue
*
* #param incomingMessages reference to message queue
* #param dbConnection
*
*/
public PollingSynchronizer(Collection<KpiMessage> incomingQueue, Connection dbConnection) {
super();
this.incomingQueue = incomingQueue;
this.dbConnection = dbConnection;
}
private int seqId;
public int getSeqId() {
return seqId;
}
public void setSeqId(int seqId) {
this.seqId = seqId;
}
#Override
/**
* The method which runs Polling action and record the time at which it is done
*
*/
public void run() {
int seqId = 0;
while(true) {
List<KamMessage> list = null;
try {
list = fullPoll(seqId);
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
incomingQueue.addAll(list);
this.outgoingQueue = incomingQueue;
System.out.println("waiting 3 seconds");
System.out.println("new incoming message");
Thread.sleep(3000);
//when I debug my execution stops here and throws exception
MessageProcessor processor = new MessageProcessor() {
#Override
public void run() {
new MessageProcessor().generate(outgoingQueue);
}
};
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
This is the method which I have to call in order to execute.
public abstract class MessageProcessor implements Runnable {
private Collection<KpiMessage> fetchedMessages;
private Connection dbConnection;
Statement st = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
private Collection<KpiMessage> outgoingQueue;
public KpiMsg804 MessageProcessor(Collection<KpiMessage> outgoingQueue, Connection
dbConnection){
this.outgoingQueue = outgoingQueue;
this.dbConnection = dbConnection;
return (KpiMsg804) fetchedMessages;
}
public Collection<KamMessage> generate(Collection<KamMessage> outgoingQueue)
{
while(true){
try {
while (rs.next()) {
KamMessage filedClass = convertRecordsetToPojo(rs);
outgoingQueue.add(filedClass);
}
for (KamMessage pojoClass : outgoingQueue) {
KamMsg804 updatedValue = createKamMsg804(pojoClass);
System.out.print(" " + pojoClass.getSequence());
System.out.print(" " + pojoClass.getTableName());
System.out.print(" " + pojoClass.getAction());
System.out.print(" " + updatedValue.getKeyInfo1());
System.out.print(" " + updatedValue.getKeyInfo2());
System.out.println(" " + pojoClass.getEntryTime());
}
return outgoingQueue;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How can I implement this?
Since I am new here, please give a reason for thumbs down. So that I can explain my question.
Try this:
MessageProcessor processor = new MessageProcessor() {
#Override
public void run() {
**new MessageProcessor()**.generate(outgoingQueue);
}
};
MessageProcessor is an abstract class. object creation inside the run method should have failed at compile time.
processor object is created but unused.. you need to create a thread with the processor instace and start the thread.