quickfixj Integration with External OMS - integration

I am doing a development to integrate a non Java OMS system with QuickFIX/J to send buy/sell orders to multiple brokerage systems .
I have written the belog logic to send the messages
I have written this under main function which is in the same class created by implementing Application "public class Initiator implements Application"
InputStream inp = InitiatorSocket.class.getResourceAsStream("test.cfg");
SessionSettings sessionSetting = new SessionSettings(inp);
Application myApp = new Initiator();
FileStoreFactory factory = new FileStoreFactory(sessionSetting);
ScreenLogFactory sfactory = new ScreenLogFactory(sessionSetting);
DefaultMessageFactory defaultMsgFactory = new DefaultMessageFactory();
initiator = new SocketInitiator(myApp, factory, sessionSetting,sfactory,defaultMsgFactory);
initiator.start();
SessionID sessionId = initiator.getSessions().get(0);
I am using the below code to send messages after continuously listening a directory using while Loop.
while(true)
{
readFilefromSrcDirectory();
prepareFixMessage();
Session.sendToTarget(fixMessage, sessionId);
}
My above code is getting executed while debugging but when I run it normally, the Session.sendToTarget(fixMessage, sessionId); and other file read related logic which is next to initiator.start(); is not getting executed.
Kindly note that the same above code is getting executed if we add some console print statements such as System.out.print("Test");
Please help me.

Are your test.cfg settings between debug and run different? I would add console print statements everywhere and work out exactly where the runtime is failing.

Related

API Testing / REST Assured Automation Testing Advice and or suggestions

Really looking for some practical advice and general guidance.
Below is the current scenario.
I have an excel document each row would be considered a test with inputs.
There would be hundreds if not thousands of rows.
Lets for example say Row1 would look like
Col1----------|Col2---------------|Col3
TestingUser|TestingSurname|1980/01/01
This needs to me mapped to a JSON object then sent / POST to an API end point.
I then need to assert the data that is coming back to make sure it’s the correct values.
The tools I have looked at is:
ReadyAPI
rest-assured.io
Would you recommend any other tool or framework for this type of testing.
If you have worked with something and you can provide an example that would be great.
I wouldn't be able to provide recommendation as i haven't worked on RestAssured.However below are few advantages of ReadyAPI:
Learning curve is shallow,any Tester will be able to build test
case without dependency on any programming language. ReadyAPI has
inbuild feature to read data from different datasources(DB, XML,
json,csv,excel etc.) and invoke REST endpoint by passing these
fields to Header,query and Json Body of the end point.
The response for each call can be dumped to a file using DataSink option for a
test step for each of the request calls made for the records from the file.
Tool is structured to easily build test Cases with multiple test
Steps. It more like drag and drop to build your test cases.Hierarchy
is Project -> Test Suite -> Test Case -> Test Step.
Easy integration with Jenkins CI/CD pipeline using testRunner with wide
variety of test reporting capabilities. Test reports are available as Allure,
jasper reports, junit Style reporting.
For more technical testers who need more control can use Groovy,javascript
language to build frameworks.
VirtServer and LoadUI are other tools by SmartBear that can be used to mock
services and run performance tests as desired.
I have an important comment to make here, if the file is huge(even 1000 lines) i have seen Ready API struggling as the tool does the heavylifting in the back. Hence would recommend to use groovy script utilizing Java API's for any file operations.
Ok so I have created a class using velocity as a json template engine.
I have created a test and within that test i have a normal java loop.
This will loop through the entire xls, map values and and post to the API.
This is all working as expected.
The problem is the runner displays
Default Suite
Total tests run: 1, Passes: 0,
However the loop does run x amount of times.
How can i update it the when i execute the test its shows total tests run 10 or the same amount that is from the loop.
Hope this makes sense
#Test
public void generatePostData() throws IOException {
Workbook wb = WorkbookFactory.create(new File("data\\sc1.xlsx"));
Sheet sheet = wb.getSheetAt(0);
for (int i = 1; i < 10; i++) {
//Get Excel Data
Cell testNumber = sheet.getRow(i).getCell(1);
System.out.println(testNumber.getNumericCellValue());
//Velocity
VelocityEngine ve = new VelocityEngine();
ve.init();
//get the template
Template t = ve.getTemplate("post.json");
//create context and add data
VelocityContext context = new VelocityContext();
//map data
context.put("tpltestNumber", testNumber);
//render to stringWriter
StringWriter writer = new StringWriter();
t.merge(context, writer);
baseURI = "someURL";
Response response =
given()
.contentType("application/json")
.body(String.valueOf(writer))
.when()
.post()
.then()
.assertThat()
.statusCode(200)
.extract()
.response();
}
}
This is the answer to the question asked in the answers sesction by the reporter of the main question. (How to get the executed excel row count, for total executed test case count)
For that you have to pass the data using a method with DataProvider annotation.
TestNG documentation
DataProvider in TestNG
#DataProvider(name = "dp")
private Object[][] dataProvider() {
Workbook wb;
Sheet sheet = null;
Object[][] excelRowArray = new Object[10][]; //this 10 the row count in the excel file
try {
wb = WorkbookFactory.create(new File("data\\sc1.xlsx"));
sheet = wb.getSheetAt(0);
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 1; i < 10; i++) {// Here 10 is the row count in the excel sheet
//Get Excel Data row by row
Cell testNumber = sheet.getRow(i).getCell(1);
System.out.println(testNumber.getNumericCellValue());
// Create a object array with the values taken from a singe excel row
Object[] excelRow = new Object[]{testNumber};
// Add the created object array to the 'excelRowArray'
excelRowArray[i - 1] = excelRow;
}
return excelRowArray;
}
#Test(dataProvider = "dp")
public void generatePostData(Object[] excelRow) {
// Here single excelRow will be passed each time.
// And this will run till all object[] in excelRowArray are finished.
// Total tests executed will be the number of 'excelRow' object arrays in
// excelRowArray. (Or excel row count in the sheet)
//Velocity
VelocityEngine ve = new VelocityEngine();
ve.init();
//get the template
Template t = ve.getTemplate("post.json");
//create context and add data
VelocityContext context = new VelocityContext();
//map data
context.put("tpltestNumber", excelRow); // Here excelRow is used as the value
//render to stringWriter
StringWriter writer = new StringWriter();
t.merge(context, writer);
String baseURI = "someURL";
Response response =
given()
.contentType("application/json")
.body(String.valueOf(writer))
.when()
.post()
.then()
.assertThat()
.statusCode(200)
.extract()
.response();
}

Showing error or success message on same page

this is my first time posting here since I couldn't figure the issue out, please keep in mind im fairly new to Spring and not that good at Java and coding in general.
I'm trying to program a Server application with Java Spring where you're able to create different accounts with specific roles. I want my users to be able to see a success or error message on the same page if the creation of an account succeded or failed.
Right now I'm using the error.param th:if tag from https://spring.io/guides/gs/securing-web/
the specific code in my HTML file is:
<div id="error" th:if="${param.error}">
Benutzername existiert bereits.
</div>
<div id="success" th:if="${param.success}">
Das Konto wurde erfolgreich erstellt.
</div>
Which works when I manually put ?success or ?error behind my URL.
I map my POST to the database by this method:
#PostMapping("/create/lieferant/fahrer")
public String submitDriver(#ModelAttribute Driver driver){
if(userRepository.existsByUsername(driver.getUsername())){
return "create/lieferant/fahrer?error";
}
Driver d = new Driver();
User n = new User();
Role r = new Role();
d.setName(driver.getName());
d.setTelnum(driver.getTelnum());
d.setUsername(driver.getUsername());
n.setUsername(driver.getUsername());
n.setPassword(encoder().encode(driver.getPassword()));
r.setUsername(driver.getUsername());
r.setAuthority("LIEFERANT");
userRepository.save(n);
driverRepository.save(d);
roleRepository.save(r);
return "create/lieferant/fahrer?success";
}
The idea is to check if the username is already registered and if so, returning the create/lieferant/fahrer?error but it says
Error resolving template "create/lieferant/fahrer?error", template
might not exist or might not be accessible by any of the configured
Template Resolvers
and the same for ?success.
What I don't understand is: it's working for the login which I've gotten from the Spring getting started guide and it seems to be working without any heavy configurations or so. Atleast I don't see any.
I'd be glad if anyone could help me figuring my issue out.
Thanks a lot.
You could do something like this:
#PostMapping("/create/lieferant/fahrer")
public ModelAndView submitDriver(#ModelAttribute Driver driver){
ModelAndView mav = new ModelAndView();
mav.setViewName("create/lieferant/fahrer");
try {
if(userRepository.existsByUsername(driver.getUsername())){
return "create/lieferant/fahrer?error";
}
Driver d = new Driver();
User n = new User();
Role r = new Role();
d.setName(driver.getName());
d.setTelnum(driver.getTelnum());
d.setUsername(driver.getUsername());
n.setUsername(driver.getUsername());
n.setPassword(encoder().encode(driver.getPassword()));
r.setUsername(driver.getUsername());
r.setAuthority("LIEFERANT");
userRepository.save(n);
driverRepository.save(d);
roleRepository.save(r);
mav.addObject("success", "All was ok");
} catch (Exception e) {
mav.addObject("error", "Error message to change");
}
return "create/lieferant/fahrer?success";
}
You could retrieve messages on page with the two keys "success" and "error"

Creating a NService Bus Ticket using SSIS Package

Is there a way to create a NService Bus ticket within SSIS package.
I am new at using SSIS packages (MSSQL 2012) and was thinking of serializing an NServiceBus ticket using a SCRIPT TASK and sending it to a MSMQ queue using a Messaging Task.
Am I thinking in the right direction?
We have done this internally, you just have to make sure you get the serialization right. You also have to be aware of what gets sent in the message label. Here is what is working on v2.5 which may have to be modified for 3.x:
String label = String.Format("<CorrId></CorrId><WinIdName>{0}\\Administrator</WinIdName>", Environment.MachineName);
Message message = new Message();
XmlSerializer serializer = new XmlSerializer(typeof(IMyMessage));
serializer.Serialize(message.BodyStream, command);
message.Label = label;
MessageQueue q = new MessageQueue(queueName);
if (q != null )
{
q.Send(message, MessageQueueTransactionType.Single);
}

groovyPagesTemplateEngine failing in quartz job with error

We are using Quartz scheduling in our application to schedule jobs to generate and send self-audit emails.
I am trying to generate the processed emailBody from the email Template using GroovyPagesTemplateEngine.
The emailTemplate is processed properly into EmailBody when the processing does not use Quartz scheduling. But when a job is run using Quartz for emailtemplate processing the
groovyPagesTemplateEngine is failing in quartz job with error
[12:10:55 AM] Mandar: java.lang.IllegalStateException: TemplateEngine not initialised correctly, no [resourceLoader] specified!
this what I am trying to do
def getInfo(){
MockHttpServletRequest servletRequest = new MockHttpServletRequest()
GrailsWebRequest grailsWebRequest = new GrailsWebRequest(servletRequest, new MockHttpServletResponse(), new MockServletContext())
grailsWebRequest.setAttribute(GrailsApplicationAttributes.WEB_REQUEST, grailsWebRequest, 0)
RequestContextHolder.requestAttributes = grailsWebRequest
GroovyPagesTemplateEngine engine = new GroovyPagesTemplateEngine()
StringWriter sw = new StringWriter()
PrintWriter pw = new PrintWriter(sw)
engine.createTemplate('myteplate').make(model).writeTo(pw)
println sw.toString()
return sw.toString()
}
I am aware that the Quartz scheduler does not have a WebRequest associated with it. and I am thinking that the email processing is failing due to this.
How can I process the emailtemplate to generate the emailBody content when the scheduled job is run, and not by logging into the application from UI.
Thanks in advance.
The resourceLoader is not initialized in the groovyPagesTemplateEngine as you are just creating a new instance of it directly. Instead, you should let Spring's dependency injection do the job for you.
Add the following line to your service:
class YourService {
def groovyPagesTemplateEngine
def getInfo(){
GroovyPagesTemplateEngine engine = groovyPagesTemplateEngine
//your code here
}
}
You can try using the steps mentioned in http://www.intelligrape.com/blog/2010/12/27/request-mocking-to-use-groovypagestemplateengine-in-backend-threads/
If you are on Grails 2.0.x, you get a bean named groovyPageRenderer, which can be used outside the context of a web request as well. For more details, http://mrhaki.blogspot.in/2012/03/grails-goodness-render-gsp-views-and.html

Symfony 1.4 - forward404 pass message to error404 template in production mode

In my app I want to use $this->forward404("Data not found"); to output individual error messages when necessary.
In the dev mode it works fine. When I run my app in production mode - where debug is set to false in getApplicationConfiguration() - I don't get the messages anymore.
in settings.yml I set a custom 404 action.
all:
.actions:
error_404_module: main
error_404_action: custom404
How can I pass the forward404 to my custom404Success.php template???
If you are able to get code of method you can see that method throws an sfError404Exception, that handles respect of enviroment. In dev it simple throws an exception and in prod it might be handle via set_exception_handler("my_handle").
You can override this method(it's public)
public function forward404($message = null)
{
// write to session and call from 404_template via <?php echo $sf_user->getFlash("404message") ?>
$this->getUser()->setFlash("404message", $message);
parent::forward404($message);
}
The 404 handling is completely different between prod and dev. In prod, the message you pass to the forward404 is simply written to the log and not passed to the handler action.
There are many ways to get round this, but the quickest (albeit dirtiest) would be to store the message in a static variable somewhere so the 404 handler can access it once the process gets there, e.g.
In your action,
<?php
CommonActions::$message404 = 'My message';
$this->forward404();
And in your 404 handler (assuming it's in CommonActions),
<?php
if (self::$message404) {
$this->message = self::$message404;
}