Reputation: 37
I am trying to read a file line by line and look out for lines that contain the string "Inside /buyairtime" in it, then get the AppSessionId from that line, after that use the AppSessionId to get the requestBody that should be in the next line and retrieve the transactionId.
I am able to read the file and get the AppSessionId but I am not able to get the "requestBody", please any help will be appreciated.
here is what I have tried.
try(BufferedReader br = new BufferedReader(fileReader)) {
br.lines().forEach((line) -> {
if (line.contains("Inside /buyairtime")) {
String[] item = line.split("\\|");
String AppSessionId = item[1].trim();
logger.info("SessionId =" + sessionId + " AppSessionId =" + AppSessionId);
if (line.contains(AppSessionId) && line.contains("requestBody")) {
String[] request = line.split("\\|");
String requestBody = request[2].replace("#", "").trim();
logger.info("SessionId =" + sessionId + " requestBody =" + requestBody);
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
Ex: here is an example of lines to read
[http-nio-8090-exec-66] g.c.v.M.controller.ApiController : AppSessionId | MB-9672588DE0304D7 | ######## Inside /buyairtime Route
g.c.v.M.controller.ApiController : AppSessionId | MB-9672588DE0304D7 | ######## requestBody = {"amount":"4.0","msisdn":"233200906179","transactionid":"0000001853861312"}
g.c.v.M.controller.ApiController : AppSessionId | MB-9672588DE0304D7 | ######## Client IP = 127.0.0.1
here is an image of the part of the file
Upvotes: 1
Views: 170
Reputation: 4710
I would change the whole code to a non forEach
loop like this (taking into consideration that the next line will have the request body!)
try(BufferedReader br = new BufferedReader(fileReader))
{
for(String line = br.readLine(); line != null; line = br.readLine())
{
if (line.contains("Inside /buyairtime"))
{
String[] item = line.split("\\|");
String AppSessionId = item[1].trim();
logger.info("SessionId =" + sessionId + " AppSessionId =" + AppSessionId);
line = br.readLine(); // Jump to the next line
if (line.contains(AppSessionId) && line.contains("requestBody"))
{
String[] request = line.split("\\|");
String requestBody = request[2].replace("#", "").trim(); // Replace everything and get only the request body...
logger.info("SessionId =" + sessionId + " requestBody =" + requestBody);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
As you can see, I jump into the next line to get the ReqBody, your logic was not correct before, since you supposed to read the both lines at the same time.
Upvotes: 3