listen to incoming mails - JavaMail - java

I'm trying to write a class that is suppose to listen for incoming messages.
I had added a listener to my inbox.
I parse the messages in the inbox to look for a specific email, when that email is found I want my listener to stop listen to the inbox.
How can this be done?
This is my code:
public Map<String, Object> read(String id, Risk risk) {
setID(id);
try {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", email, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
inbox.addMessageCountListener(new MessageCountAdapter() {
public void messagesAdded(MessageCountEvent ev) {
setListenerExists(true);
boolean emailFound = false;
Message[] msgs = ev.getMessages();
System.out.println("Got " + msgs.length + " new messages");
if (msgs.length >= 1){
for (Message msg: msgs){
try {
Object o = msg.getContent();
if (o instanceof String){
hm = parser.parseMessage(adr, msg.getSubject(), msg.getContent(), getID());
System.out.println("FROM : " + adr);
System.out.println("SUBJECT : " + msg.getSubject());
System.out.println("HTML : " + msg.getContent());
}
else if (o instanceof Multipart){
Multipart mp = (Multipart) o;
BodyPart bp = mp.getBodyPart(0);
hm = parser.parseMessage(adr, msg.getSubject(), bp.getContent(), getID());
/*
System.out.println("FROM : " + adr);
System.out.println("SUBJECT : " + msg.getSubject());
System.out.println("HTML : " + bp.getContent());
*/
}
Iterator<Integer> it = hm.keySet().iterator();
while (it.hasNext()){
if (it.next() == 1){
map = extractValues(hm.get(1));
setMap(map);
//emailReceived = true;
//setEmailReceived(true);
//extractValues(hm.get(1));
}else{
/*
* TODO : remove listener
* setLisetn
*/
System.out.println("HM is Null!");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
while (emailFound == false){
for (Message msg : msgs){
try {
Object o = msg.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
*/
}
});
// Check mail once in "freq" MILLIseconds
boolean supportsIdle = false;
try {
if (inbox instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder)inbox;
f.idle();
supportsIdle = true;
}
} catch (FolderClosedException fex) {
throw fex;
} catch (MessagingException mex) {
supportsIdle = false;
}
for (;;) {
if (supportsIdle && inbox instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder)inbox;
f.idle();
System.out.println("IDLE done");
} else {
Thread.sleep(20000); // sleep for freq milliseconds
// This is to force the IMAP server to send us
// EXISTS notifications.
inbox.getMessageCount();
}
}
}catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getMap();
}
public void setID(String id){
this.riskId = id;
}
public String getID(){
return riskId;
}
public void setMap(Map<String, Object> m){
this.map = m;
}
public Map<String, Object> getMap(){
return map;
}
public void setListenerExists(boolean exists){
this.listener = exists;
}
public boolean getListenerExists(){
return listener;
}
/** extracts values from hashmap received from the parser **/
public Map<String, Object> extractValues(HashMap<String, EmailData> h){
System.out.println("I'M Called");
Risk risk = new Risk();
String id = "";
String sender = "";
String answer = "";
HashMap<String, String> data;
Iterator<String> it = h.keySet().iterator();
while (it.hasNext()){
id = it.next();
EmailData ed = h.get(id);
sender = ed.getEmail();
answer = ed.getAnswer();
}
Map<String, Object> map = createVariablesToInsert(id, sender, answer);
return map;
}
public Map<String, Object> createVariablesToInsert(String id, String sender, String answer){
Map<String, Object> map = new HashMap<String, Object>();
System.out.println("I'M Called");
System.out.println("UUID : " + id);
System.out.println("USER : " + sender);
System.out.println("ANSWE : " + answer);
map.put("uuid", id);
map.put("user", sender);
map.put("ans", answer);
System.out.println("ID : " + map.get("uuid"));
System.out.println("USER : " + map.get("user"));
System.out.println("ANS : " + map.get("ans"));
System.out.println("ID in insert");
return map;
}
}

pay attention that you must declare two variables as final. it allow to access to those variables inside the implementation of MessageCountAdapter
final Folder inbox = store.getFolder("INBOX");
final MessageCountAdapter listener = new MessageCountAdapter() {
boolean emailFound = false;
// do something
if (emailFound) {
inbox.removeMessageCountListener(listener);
}
}
inbox.addMessageCountListener(listener);

Related

Why do I get zero-filled messages from dynamic queue

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);

how to solve market data request for quickfixj

i am new using in fix transport i have try to create connection to my broker using java. i have problem for running my java application for marketdata request.
here my main class java
public class FastmatchMDRequest {
public static void main(String[] args) {
SocketInitiator socketInitiator = null;
try {
InputStream inputStream = null;
if (args.length == 0) {
inputStream = FastmatchMDRequest.class.getResourceAsStream("initiator.cfg");
} else if (args.length == 1) {
inputStream = new FileInputStream(args[0]);
}
if (inputStream == null) {
System.out.println("usage: " + FastmatchMDRequest.class.getName() + " [configFile].");
return;
}
SessionSettings settings = new SessionSettings(inputStream);
inputStream.close();
Application application = new TestMarketdataRequest();
FileStoreFactory fileStoreFactory = new FileStoreFactory(settings);
FileLogFactory logFactory = new FileLogFactory(settings);
MessageFactory messageFactory = new DefaultMessageFactory();
socketInitiator = new SocketInitiator(application,
fileStoreFactory, settings, logFactory,
messageFactory);
socketInitiator.start();
SessionID sessionId = socketInitiator.getSessions().get(0);
sendMarkeDataRequest(sessionId);
int i = 0;
do {
try {
Thread.sleep(1000);
System.out.println(socketInitiator.isLoggedOn());
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
} while ((!socketInitiator.isLoggedOn()) && (i < 30));
} catch (ConfigError e) {
e.printStackTrace();
} catch (SessionNotFound e) {
e.printStackTrace();
} catch (Exception exp) {
exp.printStackTrace();
} finally {
if (socketInitiator != null) {
socketInitiator.stop(true);
}
}
}
private static void sendMarkeDataRequest(SessionID sessionId)
throws SessionNotFound {
UUID uuid = UUID.randomUUID();
String randomUUIDString = uuid.toString();
Message message = new Message();
quickfix.fix42.MarketDataRequest.NoMDEntryTypes group =
new quickfix.fix42.MarketDataRequest.NoMDEntryTypes();
quickfix.fix42.MarketDataRequest.NoRelatedSym group1 =
new quickfix.fix42.MarketDataRequest.NoRelatedSym();
MarketDataRequest marketdatarequest = new MarketDataRequest();
Header header = marketdatarequest.getHeader();
header.setField(new BeginString("FIX.4.2"));
header.setField(new SenderCompID("Mycomp"));
header.setField(new TargetCompID("mybroker"));
header.setField(new MsgType("V"));
message.setField(new MDReqID(randomUUIDString));
message.setField(new SubscriptionRequestType((char) 1));
message.setField(new MarketDepth(1));
message.setField(new NoMDEntryTypes(1));
group.setField(new MDEntryType((char) 1));
message.addGroup(group);
group1.setField(new Symbol("ALL"));
message.addGroup(group1);
try
{
Session.sendToTarget(message);
System.out.println("message" + message);
}catch (Exception ex)
{
System.out.println("error" + ex);
}
}}
and for application class
public class TestMarketdataRequest implements Application {
public void fromAdmin(quickfix.Message arg0, SessionID arg1)
throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, RejectLogon {
// TODO Auto-generated method stub
System.out.println("Successfully called fromAdmin for sessionId : "
+ arg0);
}
public void fromApp(quickfix.Message arg0, SessionID arg1)
throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {
// TODO Auto-generated method stub
System.out.println("Successfully called fromApp for sessionId : "
+ arg0);
}
public void onCreate(SessionID sessionID) {
// TODO Auto-generated method stub
System.out.println("Successfully called onCreate for sessionId : "
+ sessionID);
}
public void onLogon(SessionID sessionID) {
// TODO Auto-generated method stub
System.out.println("Successfully logged on for sessionId : " + sessionID);
}
public void onLogout(SessionID sessionID) {
// TODO Auto-generated method stub
System.out.println("Successfully logged out for sessionId : " + sessionID);
}
public void toAdmin(quickfix.Message message, SessionID sessionID) {
// TODO Auto-generated method stub
System.out.println("Inside toAdmin");
}
public void toApp(quickfix.Message message, SessionID sessionID) throws DoNotSend {
// TODO Auto-generated method stub
System.out.println("Message : " + message + " for sessionid : " + sessionID);
}
public void onMessage(MarketDataIncrementalRefresh message, SessionID sessionID)
throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue {
System.out.println("Inside onMessage for New Order Single" + message + sessionID);
}
public void MarketDataIncrementalRefresh (Message message, SessionID sessionID) throws FieldNotFound{
try
{
MDReqID mdreqid = new MDReqID();
SendingTime sendingtime = new SendingTime();
NoMDEntries nomdentries = new NoMDEntries();
quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries group
= new quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries();
MDUpdateAction mdupdateaction = new MDUpdateAction();
DeleteReason deletereason = new DeleteReason();
MDEntryType mdentrytype = new MDEntryType();
MDEntryID mdentryid = new MDEntryID();
Symbol symbol = new Symbol();
MDEntryOriginator mdentryoriginator = new MDEntryOriginator();
MDEntryPx mdentrypx = new MDEntryPx();
Currency currency = new Currency();
MDEntrySize mdentrysize = new MDEntrySize();
ExpireDate expiredate = new ExpireDate();
ExpireTime expiretime = new ExpireTime();
NumberOfOrders numberoforders = new NumberOfOrders();
MDEntryPositionNo mdentrypositionno = new MDEntryPositionNo();
message.getField(nomdentries);
message.getField(sendingtime);
message.getGroup(1, group);
int list = nomdentries.getValue();
for (int i = 0; i < list; i++)
{
message.getGroup(i + 1, group);
group.get(mdupdateaction);
if (mdupdateaction.getValue() == '2')
System.out.println("Enter");
group.get(deletereason);
group.get(mdentrytype);
group.get(mdentryid);
group.get(symbol);
group.get(mdentryoriginator);
if (mdupdateaction.getValue() == '0')
group.get(mdentrypx);
group.get(currency);
if (mdupdateaction.getValue() == '0')
group.get(mdentrysize);
}
System.out.printf("Got Symbol {0} Price {1}",
symbol.getValue(), mdentrypx.getValue());
}catch (Exception ex)
{
System.out.println("error" + ex);
}
}
public void MarketDataSnapshotFullRefresh (Message message, SessionID sessionID) throws FieldNotFound{
String Symbol = message.getField(new Symbol()).getValue();
NoMDEntries noMDEntries = new NoMDEntries();
message.getField(noMDEntries);
quickfix.fix42.MarketDataSnapshotFullRefresh.NoMDEntries group =
new quickfix.fix42.MarketDataSnapshotFullRefresh.NoMDEntries();
MDEntryType MDEntryType = new MDEntryType();
MDEntryPx MDEntryPx = new MDEntryPx();
MDEntrySize MDEntrySize = new MDEntrySize();
SendingTime sendingTime = new SendingTime();
message.getField(sendingTime);
message.getGroup(1, group);
group.get(MDEntryType);
group.get(MDEntryPx);
group.get(MDEntrySize);
message.getGroup(2, group);
group.get(MDEntryType);
group.get(MDEntryPx);
group.get(MDEntrySize);
System.out.printf("Symbol {0} Price {1}", Symbol, MDEntryPx);
}
i have add and artifact in my pom.xml for quickfixj and etc. but when i build as jar and run jar application i got an error like
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: quickfix/SessionNotFound
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: quickfix.SessionNotFound
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:419)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
at java.lang.ClassLoader.loadClass(ClassLoader.java:352)
... 7 more
how to fix my problem for build market data request ?
best regards,
Fuad
Try creating executable/fat jar with dependencies by adding below plugin in your pom.xml
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>

Json Reflaction warning with custom List

I am trying to reflect a json to class. But i have problem when i have JsonArray inside of JsonArray with object's. It seems that is trying to find a class like List<Step> but cannot found.
My output is :
W/System.err: Value ... at steps of type org.json.JSONArray cannot be converted to JSONObject
My class is like:
class Step {
private Consecutive consecutive;
private List<List<Steps>> steps = null;
}
a part of my Json :
{"step":{"consecutive":{"enabled":true,"period":"day"},"steps":[[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}]]}}
My Json Parser :
public static Object populateObjectFromJSON(Class<?> classname, JSONObject js) {
Object obj = null;
System.out.println("Populating " + classname.getSimpleName() + " -with- " + js.toString());
try {
obj = classname.newInstance();
} catch (InstantiationException e1) {
System.err.println(e1.getMessage());
return null;
} catch (IllegalAccessException e1) {
System.err.println(e1.getMessage());
return null;
}
Field[] fields;
if (privacy == 0) {
fields = classname.getFields();
} else {
fields = classname.getDeclaredFields();
}
for (Field f : fields) {
// System.out.println("Declared " + f.getName());
if ((privacy == 2) && (Modifier.isPrivate(f.getModifiers()))) {
f.setAccessible(true);
}
try {
if (js.has(f.getName())) {
String type = f.getType().getSimpleName();
if (type.equalsIgnoreCase("boolean")) {
f.setBoolean(obj, js.getBoolean(f.getName()));
} else if (type.equalsIgnoreCase("int")) {
f.setInt(obj, js.getInt(f.getName()));
} else if (type.equalsIgnoreCase("double")) {
f.setDouble(obj, js.getDouble(f.getName()));
} else if (type.equalsIgnoreCase("float")) {
f.setFloat(obj, (float) js.getDouble(f.getName()));
} else if (type.equalsIgnoreCase("string")) {
f.set(obj, js.getString(f.getName()));
} else if (f.getType().isArray()) {
f.set(obj, Array.newInstance(f.getType().getComponentType(), js.getJSONArray(f.getName()).length()));
insertArrayFromJSON(f.get(obj), js.getJSONArray(f.getName()));
}else{
f.set(obj, populateObjectFromJSON(f.getType(), js.getJSONObject(f.getName())));
}
}
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
} catch (IllegalAccessException e) {
System.err.println(e.getMessage());
} catch (JSONException e) {
System.err.println(e.getMessage());
}
if ((privacy == 2) && (Modifier.isPrivate(f.getModifiers()))) {
f.setAccessible(false);
}
}
return obj;
}
thanks

ArrayList becomes null while writing to file

My arraylist<"obj"> becomes null after trying to write to a file.
In WriteToFile class arraylist info becomes null after executing the last line
writer.write(info.get(i).getIpadd().toString()+"\n");
It works on the first instance when i am writing another list to file but does not when i run it the 2nd instance. I dun understand why its happening. Below is the whole code and the stack trace.
WriteToFile Class:
public class WriteToFile {
public WriteToFile(ArrayList<Information> info,String location)
{
FileWriter writer=null;
try
{
writer = new FileWriter(location);
System.out.println(info.size());
for(int i=0;i<info.size()-1;i++)
{
writer.write(info.get(i).getDate().toString()+",");
writer.write(info.get(i).getAccount().toString()+",");
writer.write(info.get(i).getStatus().toString()+",");
writer.write(info.get(i).getIpadd().toString()+"\n");
System.out.println(info.get(i).getAccount());
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
StackTrace:
java.lang.NullPointerException
at WriteToFile.<init>(WriteToFile.java:17)
at Gen_Report.<init>(Gen_Report.java:45)
at Gen_Report.main(Gen_Report.java:57)
main:
public class Gen_Report {
public Gen_Report()
{
// TODO Auto-generated constructor stub
//locate file and read all text from .log file to .csv
//file is found.so read text from it and extract all date/time, email add ,accepts and rejects,ip add, delete
Date date=new Date();
String[] dateTokens=date.toString().split(" ");
String dateString=dateTokens[2]+dateTokens[1]+dateTokens[5]+"_"+dateTokens[3].substring(0, 2)+dateTokens[3].substring(3,5)+dateTokens[3].substring(6, 8);
String logFileLocation = "/Users/gundu_87/Documents/workspace/GenFLRReport/";
ReaderFromLog rfl = new ReaderFromLog(logFileLocation+"radsecproxy.log");
//include duplicates
WriteToFile wtf = new WriteToFile(rfl.log,logFileLocation+dateString+"_FLRlogduplicates.txt");
//exclude duplicates
RemoveDuplicatesInList rdil = new RemoveDuplicatesInList(logFileLocation+dateString+"_FLRlogduplicates.txt");
for(int i=0;i<rdil.log.size();i++)
{
System.out.println(rdil.log.get(i).getAccount());
}
wtf = new WriteToFile(rdil.log,logFileLocation+dateString+"_FLRlog.txt");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Gen_Report gr= new Gen_Report();
}
}
Information class:
public class Information {
private String ipadd;
private String status;
private String account;
private String date;
public String getIpadd() {
return ipadd;
}
public void setIpadd(String ipadd) {
this.ipadd = ipadd;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
ReaderFromLog class
public class ReaderFromLog {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public ReaderFromLog(String logFileLocation) {
// TODO Auto-generated constructor stub
File logFile = new File(logFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Access-Accept for user"))
{
newUser.setStatus("Accept");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
else if(line.contains("Access-Reject for user"))
{
newUser.setStatus("Reject");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
}while(s1.hasNextLine());
}
}
RemoveDuplicate class:
public class RemoveDuplicatesInList {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public RemoveDuplicatesInList(String duplicateFileLocation)
{
// TODO Auto-generated constructor stub
File logFile = new File(duplicateFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
boolean sameAccount=false;
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Accept"))
{
newUser.setStatus("Accept");
String[] sb=line.split(",");
sameAccount=false;
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
else if(line.contains("Reject"))
{
newUser.setStatus("Reject");
String[] sb=line.split(",");
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
}while(s1.hasNextLine());
}
}
Check value of
info.get(i).getIpadd()
if value of this is null then .toString(0 will give you NullPointerException

LazyDataModel called twice

I'm using datatable from primefaces for displaying list of records.
But it call twice the load internal method(overriden) while navigating to pages. This behavior affects the performance.
partial server side code:
public void getInternalList() {
try {
dataList = service.getInternalDetails(userId, 0, 5);
if (null != dataList) {
// Getting the current page data using lazy loading
lazyModelEmployees = new LazyDataModel<Employee>() {
#Override
public List<Employee> load(int first, int pageSize, String arg2, SortOrder arg3, Map<String, String> arg4) {
List<Employee> currentPageEmployeeList = null;
try {
currentPageEmployeeList = service.getInternalDetails(userId, first, pageSize);
} catch (Exception e) {
exceptionHandler(e);
}
if (arg2 != null) {
Collections.sort(currentPageEmployeeList, new LazySorter(arg2, arg3));
}
int dataSize = currentPageEmployeeList.size();
this.setRowCount(dataSize);
if (dataSize > pageSize) {
try {
return currentPageEmployeeList.subList(first, first + pageSize);
} catch (IndexOutOfBoundsException e) {
return currentPageEmployeeList.subList(first, first + (dataSize % pageSize));
}
} else {
return currentPageEmployeeList;
}
}
};
lazyModelEmployees.setRowCount(dataList.size());
lazyModelEmployees.setPageSize(5);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}

Categories