I have a below method in Java 8 which checks for message pattern and finds the line number from the message.
private LawfirmInvoice getInvoiceForErrormessage(InvoiceParcel parcel, String message) {
if (parcel.getInvoices() != null) {
if (parcel.getInvoices().size() == 1)
return parcel.getInvoices().get(0);
else {
String regex1 = "^Line\\s+\\:\\s+\\d.+";
String regex2 = "^Line\\s\\d\\s\\:\\s+.+";
Pattern p = Pattern.compile("\\d+");
Matcher m;
int lineNumber = -1;
if (message.matches(regex1)) {
m = p.matcher(message);
if (m.find()) {
lineNumber = Integer.parseInt(m.group());
} else if (message.matches(regex2)) {
m = p.matcher(message);
if (m.find()) {
lineNumber = Integer.parseInt(m.group()) - 2;
}
}
}
if (lineNumber != -1)
return parcel.getInvoices().get(lineNumber);
}
}
return null;
}
Example : message can be of below types
msg1 = "Line : 1 Invoice does not foot Reported"
msg2 = "Line 3 : Could not parse ADJUSTMENT_AMOUNT value"
The above method finds the line number from the message and returns the instance of invoice from the arraylist.
Since Java 8 has some new features am wondering whether my code can be optimized further.