How can I send and receive messages on quickfix? - java

I have created two classes: Initiator and Acceptor. I want to send messages from the initiator to the acceptor and then process the received messages. I can't send message.
This is my initiator.java
SocketInitiator socketInitiator = null;
String fileName = "conf/intiator.cfg";
try {
SessionSettings initiatorSettings = new SessionSettings(new FileInputStream(fileName));
Application initiatorApplication = new Initiator();
FileStoreFactory fileStoreFactory = new FileStoreFactory(
initiatorSettings);
FileLogFactory fileLogFactory = new FileLogFactory(
initiatorSettings);
MessageFactory messageFactory = new DefaultMessageFactory();
socketInitiator = new SocketInitiator(initiatorApplication, fileStoreFactory, initiatorSettings, fileLogFactory, messageFactory);
socketInitiator.start();
Message msg = new Message();
msg.setString(1, "Hello this is test Message");
SessionID sessionId = (SessionID) socketInitiator.getSessions().get(0);
Session.lookupSession(sessionId).logon();
initiatorApplication.onLogon(sessionId);
initiatorApplication.toApp(msg, sessionId);
} catch (Exception e) {
e.printStackTrace();
}
Here is its overRide message of Application Interface.
public void toApp(Message message, SessionID sessionId) throws DoNotSend {
try {
boolean result = quickfix.Session.sendToTarget(message, sessionId);
if (result) {
System.out.println("Message ahs send :)");
} else {
System.out.println("Not Send");
}
} catch (Exception e) {
e.printStackTrace();
}
}
this is initiator initiator.cfg file
[default]
StartTime=00:00:01
EndTime=23:59:59
HeartBtInt=10
SocketUseSSL=N
MillisecondsInTimeStamp=Y
FileIncludeMilliseconds=Y
CheckLatency=N
SocketTcpNoDelay=Y
[session]
BeginString=FIX.4.4
ConnectionType=initiator
DisableQuickFixReconnLogic=Y
AdapterUserIndex=0
SocketConnectHost=127.0.0.1
Timezone=America/New_York
SocketConnectPort=3000
UseDataDictionary=Y
DataDictionary=conf/resources/FIX44.xml
ValidateFieldsOutOfOrder=N
ValidateFieldsHaveValues=N
ValidateUserDefinedFields=N
LogonTimeout=10
FileStorePath=conf/connector
FileLogPath=conf/connector/logs
FileLogBackupPath=conf/connector
ResetOnLogout=Y
ResetOnDisconnect=N
SendResetSeqNumFlag=Y
RawData=fxall123
#SessionQualifier=FXallStream
MillisecondsInTimeStamp=Y
FileIncludeMilliseconds=Y
[session]
BeginString=FIX.4.4
ConnectionType=initiator
DisableQuickFixReconnLogic=Y
AdapterUserIndex=1
SenderCompID=initiator-id
#SenderSubID=trader1
#TargetCompID=target-id
#TargetSubID=qftrade
SocketConnectHost=127.0.0.1
Timezone=America/New_York
#SocketConnectPort=443
SocketConnectPort=3000
UseDataDictionary=Y
DataDictionary=conf/resources/FIX44.xml
ValidateFieldsOutOfOrder=N
ValidateFieldsHaveValues=N
ValidateUserDefinedFields=N
LogonTimeout=5
FileStorePath=conf/connector
FileLogPath=conf/connector
FileLogBackupPath=conf/connector/backup
ResetOnLogout=Y
ResetOnLogon=Y
ResetOnDisconnect=N
SendResetSeqNumFlag=Y
RawData=fxall123
#SessionQualifier=FXallTrade
Acceptor.java
String fileName = "conf/acceptor.cfg";
SocketAcceptor socketAcceptor = null;
try {
FileInputStream is = new FileInputStream(fileName);
SessionSettings executorSettings = new SessionSettings(is);
Application application = new Acceptor();
FileStoreFactory fileStoreFactory = new FileStoreFactory(
executorSettings);
MessageFactory messageFactory = new DefaultMessageFactory();
FileLogFactory fileLogFactory = new FileLogFactory(executorSettings);
socketAcceptor = new SocketAcceptor(application, fileStoreFactory,
executorSettings, fileLogFactory, messageFactory);
socketAcceptor.start();
SessionID sessionId = (SessionID) socketAcceptor.getSessions().get(0);
application.onLogon(sessionId);
int[] i = {1, 2, 3, 4, 5};
// application.fromApp(new Message(i), sessionId);
} catch (Exception e) {
e.printStackTrace();
}
acceptor.cfg
[default]
StartTime=00:00:00
EndTime=23:50:00
HeartBtInt=10
ReconnectInterval=6
SocketUseSSL=N
MillisecondsInTimeStamp=Y
CheckLatency=N
SocketTcpNoDelay=N
SocketAcceptAddress=127.0.0.1
SocketAcceptPort=3000
[session]
BeginString=FIX.4.4
ConnectionType=acceptor
#DisableQuickFixReconnLogic=Y
AdapterUserIndex=0
SenderCompID=target-id
#SenderSubID=qfstream
#TargetCompID=inttest
#TargetSubID=trader1
Timezone=America/New_York
UseDataDictionary=Y
DataDictionary=conf/resources/FIX44.xml
ValidateFieldsOutOfOrder=N
ValidateFieldsHaveValues=N
ValidateUserDefinedFields=N
LogonTimeout=5
FileStorePath=conf/Acceptor
FileLogPath=conf/Acceptor/logs
ResetOnLogout=Y
ResetOnDisconnect=N
SendResetSeqNumFlag=Y
Can anyone tell me where is the problem. Either in configuration or in code?

I will just point out the obvious (there is a lot wrong with this code, see the examples to understand how quickfixj works). The Message that you are trying to send is not a valid FIX message and so will be rejected by the engine before it is sent. You will need to create a real FIX message for quickfix to send it. Just as importantly I need to mention that toApp is an event handler that gets called when a message is sent. If you put a call to quickfix.Session.sendToTarget in it it will then call toApp again when it gets sent. Since there is no control statement in your toApp this results in an infinite loop. The configuration is also slightly wrong, and other bits of code look hinkey, but those are your biggest problems. Please look at the documentation and examples.

you need to make changes in xml file. I guess a field that you are using is not declared in fix.4.4 file. Check your xml file and include that in following way.
i-e you want to send QuoteID with Currency, but in Currency QuoteID is not declared. In that case you will not be able to send message.
you need to decleared that field(QuoteID) in fix.4.4/or any version you are using.
<Currency>
//
//
<field name="QuoteID" required="N" /> // N or Y depend on your requirement
//
//
</currency>
also check log, You will find error message there.
May be you are not including require fields that can also create problem.
use Following link to check which fields are required.
http://www.fixprotocol.org/FIXimate3.0/

Related

How to connect to ElasticSearch with Java transport client?

I am following the ElasticSearch documentation on Java Client. I have started ElasticSearch and I can interact with it with the Rest API. I want to use the Java Client and so far I have a main like this:
public class TestElastic {
public static void main(String[] args) {
try{
TransportClient client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
JSONObject place = new JSONObject();
place.put("name", "AAAAA");
IndexResponse response = client.prepareIndex("my_database", "places", "1")
.setSource(place)
.get();
System.out.println(response.toString());
// Index name
String _index = response.getIndex();
System.out.println(_index);
// Type name
String _type = response.getType();
System.out.println(_type);
// Document ID (generated or not)
String _id = response.getId();
System.out.println(_id);
// Version (if it's the first time you index this document, you will get: 1)
long _version = response.getVersion();
System.out.println(_version);
// isCreated() is true if the document is a new one, false if it has been updated
boolean created = response.isCreated();
System.out.println(created);
client.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
In the Java logs I can see that there is a connection with 127.0.0.1:9300. But after the "prepare index" command I do not see any error and nothing is printed(I have some system out commands). In the ElasticSearch logs is also nothing relative. When I create an index with the Rest API I can see this in the logs.
Ok, as #Val mentioned I forgot to print the errors. The problem was that JSONObject is not the format that ElasticSearch wants. Map and HashMap are acceptable.

RabbitMQ: publish in node.js subscribe in Java

Given the following publisher in node.js and the following subscriber in java (this setup is fully functional) I have the following two questions:
What should I use as the third argument in queueBind and why? Why does it works as is ("test" is a random pick)?
Is there a way to specify queue in addition to exchange in rabbit.js? If yes then how? If not then why and which module should I use instead (code example would be welcome)?
// node.js
var context = require("rabbit.js").createContext();
var pub = context.socket('PUB');
pub.connect(config.exchange);
server.post("/message/:msg", function(req, res) {
pub.write(req.params.msg, 'utf8');
res.end();
});
// java
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(host);
try {
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(exchange, "fanout");
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, exchange, "test"); // Question1: what should I use as the third argument and why?
// Question2: is there a way to configure rabbit.js with a queue name instead?
//channel.queueDeclare(queueName, false, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, true, consumer);
try {
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
LOG.info("Received message: " + message);
}
} catch (InterruptedException e) {
LOG.catching(e);
} finally {
channel.close();
connection.close();
}
} catch (IOException e) {
LOG.catching(e);
}
Own answer, what I've digged up so far:
The third argument, the routing key, is what is known as topic in rabbit.js. By supplying test I am only subscribing to messages send to the test topic or without a topic set (default in rabbit.js). If I were to use topic in the publisher as well, I could use pub.publish(topic, message, encoding) instead of pub.write(message, encoding) or supply it to the connect method
Does not look so and still do not know why really. The argument goes that rabbit.js is a higher-level library and it, therefore, makes certain simplifications. Why exactly this simplification is made I do not know. However, I primarily wanted to use a single exchange for multiple communication threads, which I can also achieve by using topics/routing keys. So not a big deal.

Path manipulation issue Fortify

Hi i have scanned an application using Fortify tool, in the generated reports i got path manipulation issue in the following method.
Note: In the report it is not showing the error line no. can anyone suggest me how to resove it?
private MimeMessage prepareMessage(EmailMessage req) throws EmailProviderException {
long start=System.currentTimeMillis(),finish=0;
try {
MimeMessage message = emailSender.createMimeMessage();
// create a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// set email addresses
helper.setFrom(convertAddress(req.getFromAddress()));
helper.setTo(convertAddress(req.getToAddress()));
helper.setCc(convertAddress(req.getCcAddress()));
helper.setBcc(convertAddress(req.getBccAddress()));
// set subject and body
helper.setSubject(req.getEmailSubject());
String emailBody = req.getEmailBody();
String emailMime = req.getEmailMimeType();
MimeBodyPart messagePart = new MimeBodyPart();
DataSource bodyDataSource = new ByteArrayDataSource(emailBody, emailMime);
messagePart.setDataHandler(new DataHandler(bodyDataSource));
helper.getMimeMultipart().addBodyPart(messagePart);
// add attachments
List<EmailAttachment> lAttach = req.getEmailAttachment();
if (lAttach != null) {
for (EmailAttachment attachMnt: lAttach) {
DataSource dSource = new ByteArrayDataSource(attachMnt
.getContent(), attachMnt
.getMimeType());
helper.addAttachment(attachMnt.getFileName(), dSource);
}
}
finish=System.currentTimeMillis();
statsLogger.info(new FedExLogEntry("prepareMessage took {0}ms",new Object[]{finish-start}));
return message;
} catch (Exception e) {
// covers MessagingException, IllegalStateException, IOException, MailException
String emsg = new StringBuilder("Unable to prepare smtp message.")
.append("\n").append(req.toString()).toString();
logger.warn(emsg, e);
throw new EmailProviderException(emsg, e);
}
}
Hmm. If Fortify is having issues trying to show you the correct line where the issue exists, then it's possible that fortify ran in to a parsing error when it was scanning and rendering the results to your FPR. One thing you could try is to rescan your application under a different build-id and generate a new FPR. Beyond that, I don't know. Sorry.
Something else that I'd recommend would be to inspect your log file to see if there were any errors or warnings during translation/scan.
But after looking at your code sample, I'm thinking that Fortify is tainting the parameter req and flagging the the operation that is occurring when it's trying to add the file as an attachment. Most likely your sink is going to be at
helper.addAttachment(attachMnt.getFileName(), dSource);
You'd want to validate the file names of the attachment themselves prior to trying to save them to disk.

Call to get EMR results always returns empty state collection even when EMR job done

For IP reasons, I'm not able to post full source code. However, I made a call to submit an Amazon Elastic Map Reduce Job (EMR) which now runs to completion. Previously it failed with essentially a file not found error.
RunJobFlowResult result=emr.runJobFlow(request);
succeeds and I can get the job flow ID from it.
Later, I have a loop polls for the status by first
DescribeJobFlowsRequest request=new DescribeJobFlowsRequest(jobFlowIdArray);
I check each state in a loop by calling
request.getJobFlowStates()
Unfortunately, that call always returns an empty collection, regardless of whether the job is running, failed or succeeded. How can I get at least some indication of what's going on?
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonElasticMapReduceClient client = new AmazonElasticMapReduceClient(credentials);
client.setEndPoint("elasticmapreduce.us-east-1.amazonaws.com");
StepFactory stepFactory = new StepFactory();
StepConfig enableDebugging = new StepConfig()
.withActionOnFailure("TERMINATE_JOB_FLOW")
.withHadoopjJarStep(stepFactory.newEnableDebuggingStep());
String[] arguments={...} // Custom jar arguments
HadoopJarStepConfig jarConfig = new HadoopJarStepConfig();
jarConfig.setJar(JAR_NAME);
jarConfig.setArgs(Arrays.asList(arguments));
StepConfig runJar = new StepConfig(JAR_NAME.substring(JAR_NAME.indexOf('/')+1),jarConfig);
RunJobFlowRequest request = new RunJobFlowRequest()
.withName("...")
.withSteps(runJar)
.withLogUri("...")
.withInstances(
new JobFlowInstancesCOnfig()
.withHadoopVersion("1.0.3")
.withInstanceCount(5)
.withKeepJobFlowAliveWhenNoSteps(false)
.withMasterInstanceType("m1.small")
.withSlaveInstanceType("m1.small");
RunJobFlowResult result = client.runJobFlow(request);
String jobFlowID=result.getJobFlowID();
List<String> describeJobFlowIdList=new ArrayList<String>(1);
describeJobFlowIdList.add(jobFlowID);
String lastState="";
boolean jobMonitoringNotDone=true;
while(jobMonitoringNotDone){
SescribeJobFlowsRequest describeJobFlowsRequest=
new DescribeJobFlowsRequest(describeJobFlowIdList);
// Call to describeJobFlowsRequest.getJobFlowStates() always returns
// empty list even when job succeeds or fails.
for(String state : describeJobFlowsRequest.getJobFlowStates()){
if(DONE_STATES.contains(state)){
jobMonitoringNotDone=false;
} else if(!lastState.equals(state)){
lastState = state;
System.out.println("Job "+state + " at "+ new Date().toString());
}
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
The code above was missing a call similar to
DescribeJobFlowsResult describeJobFlowsResult = client.describeJobFlows(describeJobFlowsRequest);
This got me a solution that works, but unfortunately Amazon deprecated the method but didn't provide an alternative. I wish I had a non deprecated solution so this is only a partial answer.

WRONG_DOCUMENT_ERR Error after login to sugarCRM from java Axis 1.4

I want to import data from java web application to sugarCRM. I created client stub using AXIS and then I am trying to connect, it seems it is getting connected, since I can get server information. But after login, it gives me error while getting sessionID:
Error is: "faultString: org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it."
Here is my code:
private static final String ENDPOINT_URL = " http://localhost/sugarcrm/service/v3/soap.php";
java.net.URL url = null;
try {
url = new URL(ENDPOINT_URL);
} catch (MalformedURLException e1) {
System.out.println("URL endpoing creation failed. Message: "+e1.getMessage());
e1.printStackTrace();
}
> System.out.println("URL endpoint created successfully!");
Sugarsoap service = new SugarsoapLocator();
SugarsoapPortType port = service.getsugarsoapPort(url);
Get_server_info_result result = port.get_server_info();
System.out.println(result.getGmt_time());
System.out.println(result.getVersion());
//I am getting right answers
User_auth userAuth=new User_auth();
userAuth.setUser_name(USER_NAME);
MessageDigest md =MessageDigest.getInstance("MD5");
String password=convertToHex(md.digest(USER_PASSWORD.getBytes()));
userAuth.setPassword(password);
Name_value nameValueListLogin[] = null;
Entry_value loginResponse = null;
loginResponse=port.login (userAuth, "sugarcrm",nameValueListLogin);
String sessionID = loginResponse.getId(); // <--- Get error on this one
The nameValueListLogin could be be from a different document context (coming from a different source). See if this link helps.
You may need to get more debugging/logging information so we can see what nameValueListLogin consists of and where it is coming from.

Categories

Resources