Search word in text file and print the line - java

How can i search certain text in a text file and then print the line that contains it?
i already was using tries, here's my code:
Collection<Emit> emits = t.parseText("text to look in");
String results = "Found lines: ";
for (Emit e : emits) {
results += "\r\nWord: "+e.getKeyword();
}
System.out.println(results);
try {
sendEmail(results);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
How can i change the code or what approach should i take? I am using the code to monitor the apache logs every half hour looking for HTTP request that may contain SQL injection.
thank you in advance

Related

Log Statements work in try block but not it catch block Java

I have the following code:
try {
Log.debug("TEST 1");
InputStream input = loadTemplate(template);
String ofmt = template.getOutputFormat() != null ? template.getOutputFormat().trim().toLowerCase() : "";
if ("prn".equals(ofmt)) {
report = createPrinterProcess(template, input);
} else if (IsImageFormat(ofmt)) {
report = createImageProcess(ofmt, template, input);
} else {
report = createProcess(ofmt, input, new ByteArrayOutputStream());
}
return report;
} catch (Exception e) {
ControllerBase.getRepository().saveError(template, new ServiceError(e));
Log.warn(String.format("Generate(template, %1$s)", template.getGuid()), e);
return null;
}
The log statement in the try gets hit and shows up in the log file, but the log statements in the catch block get hit but don't show up in the log file. They are both using the same logger. Any ideas as to what is happening? I just dont understand why logs would work in the try but not the catch. I tried all different levels of logging, all work in the try, none work in the catch.
EDIT
My log config, both console and log file are set up the same:
and this is what saveError looks like, all its doing is saving the error to a .error file, and it is not breaking in the method (i stepped through it):

ChunkedOutput returning response on browser all at once

I am using org.glassfish.jersey.server.ChunkedOutput to get the chunked response to my request.
When I hit the URL through browser, instead of getting output as separate chunks, I am getting all the chunks at once.
But when I use a Test Client to hit the resource, I get the output as separate chunks.
Server Used: Glassfish 4.0
Jersey version 2.13
Resource method is as follows:
#GET
#Path("chunk")
public ChunkedOutput<String> getChunkedResponse(#Context HttpServletRequest request) {
final ChunkedOutput<String> output = new ChunkedOutput<String>(
String.class);
new Thread() {
public void run() {
try {
Thread.sleep(2000);
String chunk;
String arr[] = { "America\r\n", "London\r\n", "Delhi\r\n", "null" };
int i = 0;
while (!(chunk = arr[i]).equals("null")) {
output.write(chunk);
i++;
Thread.sleep(2000);
}
} catch (IOException e) {
logger.error("IOException : ", e);
} catch (InterruptedException e) {
logger.error("InterruptedException : ", e);
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error("IOException IN finally : ", e);
}
}
}
}.start();
// the output will be probably returned even before
// a first chunk is written by the new thread
return output;
}
Test Client method is as follows:
private static void testChunkedResponse(WebTarget target){
final Response response = target.path("restRes").path("chunk")
.request().get();
final ChunkedInput<String> chunkedInput =
response.readEntity(new GenericType<ChunkedInput<String>>() {});
String chunk;
while ((chunk = chunkedInput.read()) != null) {
logger.info("Next chunk received: " + chunk);
}
}
Can someone please help me understand why response is not getting chunked on browser and what can be done about it?
I am also working on the client to process the chunkedouput response. From my knowledge,
For browser, you need to write longer string, i am not sure why, but seems for firefox, there is a buffer, so unless the buffer size get met, the browser wont rendering the html. From my test on Chrome, you can see the effect for short strings.
for the chunkedInput, there is a parser keep searching for separator for the string. Since using Jersey, ChunkedInput wont be able to how to split the stream. it use the parser to split and return splited substring when you call read(). By default, the separator is '\r\n', if you write '\r\n' to your chunkedoutput, you should see the client code run as you expected.
I had the same problem. Adding line separator when writing solved the problem.
output.write(chunk + System.lineSeparator());

How and where can I interpret a Java error message of "3" returned from java.lang.String?

I am running a Java program that parses BufferedReader input into a delimited string for output to a file. After successfully reading 24 lines from the source file and saving them to the destination file, I get an error message of 3 (using the getMessage()) method in the catch paired with the "read the next line of the file" try.
When I change the catch to the following,
catch (Exception e)
{
System.err.println("Error: " + e.getMessage().getClass().getName());
}
the catch results in the Error: java.lang.String being returned...but no further explanation. Bad characters in the file? Inorrect casting? OutOfBounds as another comment suggested? any other ideas how to extract further information from this error?
I have reviewed the input file in a hex editor and there are no unexpected EOF or null characters between the rows, the input data displays as expected in a hex or text editor, and I cannot find any documentation about how to interpret a 3 error message, or even how to determine if it's an OS or Java exception.
Instead of using e.getMessage(), try using e.printStackTrace(). This will show the full details of the exception and should point you in the right direction.
catch (Exception e)
{
System.err.print("Error: ");
e.printStackTrace();
}
You can also try:
catch (Exception e)
{
System.err.println("Error: " + e);
}

printing HL7 message in console

I'm passing an object to constructor and then adding parameters of this object to HL7.
ORU_R01 is the type of HL7.
When i print HL7 to console, only the last OBX is printed.
What is wrong with my code?
How can i write this HL7 message to socket?
Is there simpler way in java to handel HL7?
public class FlexSMessageHL7 {
private FileWriter writeHL7ToFile;
private PrismaflexSMessage sMessage;
private ORU_R01 message;
private int i = 0;
private OBX obx = null;
public FlexSMessageHL7(FlexSMessage sMessage) {
this.sMessage = sMessage;
this.message = new ORU_R01();
createHL7SMessage();
}
public void createHL7SMessage() {
// Populate the MSH Segment
MSH msh = message.getMSH();
try {
msh.getFieldSeparator().setValue("|");
msh.getEncodingCharacters().setValue("^~\\&");
msh.getDateTimeOfMessage().setValue(sMessage.getTime().toString());
msh.getSendingApplication().getNamespaceID().setValue(String.valueOf(sMessage.getMachID()));
} catch (DataTypeException e) {
e.printStackTrace();
}
// Populate the OBR Segment:time
OBR obr = message.getPATIENT_RESULT().getORDER_OBSERVATION().getOBR();
try {
obr.getObservationDateTime().setValue(String.valueOf(sMessage.getTime()));
} catch (DataTypeException e) {
e.printStackTrace();
}
// Populate the PID Segment:PatientId
PID pid = message.getPATIENT_RESULT().getPATIENT().getPID();
try {
pid.getPatientID().getIDNumber().setValue(sMessage.getPatID());
} catch (HL7Exception e) {
e.printStackTrace();
}
// Populate the OBX Segment:Param_Code, time, Measure_Value
while (i < sMessage.getMsgInfo()) {
for (PrismaflexSRecord sRecord : sMessage.getsRecordCollection()) {
try {
obx = message.getPATIENT_RESULT().getORDER_OBSERVATION().getOBSERVATION(i).getOBX();
obx.getSetIDOBX().setValue(String.valueOf(i));
obx.getObservationIdentifier().getIdentifier().setValue(sRecord.getParamCode());
obx.getDateTimeOfTheObservation().setValue(String.valueOf(sRecord.getTimeStamp()));
obx.getObservationIdentifier().getNameOfCodingSystem().setValue(String.valueOf(sRecord.getMeasureValue()));
i++;
} catch (HL7Exception e) {
e.printStackTrace();
}
}
}
try {
writeHL7ToFile = new FileWriter(File.createTempFile("prismaflexOutputFrom3001HL7", "txt", new File
("c:\\tmp\\prismaflex")));
writeHL7ToFile.write(message.getMSH().toString());
writeHL7ToFile.flush();
} catch (IOException e) {
e.printStackTrace();
}
// Now, Encode the message and look at the output
try {
Parser parser = new PipeParser();
String encodedMessage = parser.encode(message);
System.out.println("Printing HL7 Encoded Message:");
System.out.println(encodedMessage);
} catch (HL7Exception e) {
e.printStackTrace();
}
}
}
As Nicholas Orlowski pointed out, the problem is in the line ending characters, which according to the HL7 standard are CR characters which make a Windows command prompt only reset the cursor to the beggining of the line and overwrite it with next line's content. Therefore for console output You need to replace the line-endings with something else.
For a recent HL7 app using HAPI, which You also seem to be using, I made a little helper method to achieve this function:
private static String replaceNewlines(String input) {
return input.replaceAll("\\r", "\n");
}
The function can be used on all platforms, as it replaces the CR characters with the OS-specific newline character(s).
Then I can use it to output to console as follows:
LOGGER.trace("Generated message contents:\n" + replaceNewlines(outMessage.encode()));
In this case I am using log4j for logging to console, not simple console printout, but the problem was the same for me.
Hope it helps!
Have you considered using the HAPI? It is written for java, it's counter part nHAPI is written for .net as well. Details here:
http://hl7api.sourceforge.net/
I have had a similar problem in my python HL7py library. Many times the console doesn't like printing characters. I had to write a helper that changed CR to LF (line feed) to display the lines correctly. Hope that helps.
It won't display in the console but it will when you write to the file. Try looking at the variable in debug mode and writing it to a file.

try, catch and if error in a combo box with java and netbeans

I assure you all that this is not homework.
I have a combo box:
try {
double input = Double.valueOf(input1.getText());
double output = 0;
My combo box code here:
if (output < 2.50){
answerField.setText("£2.50");
}
else{
answerField.setText("£" + String.valueOf (fmt.format(output)));
catch (Exception e) { JOptionPane.showMessageDialog(this,
"Please enter numbers in the fields.
Numbers are 1 2 3 4 5 etc.",
"Oooops!!!",
JOptionPane.ERROR_MESSAGE);
}
The problem I have is that when I run it like this it won't work.
if I take the if statement out and leave try catch in, it works
and also if I take the try and catch out it and leave only the if, it also works
When I run it using the above, I get this error:
catch without try
; expected
Can anyone help?
you must close your else bracket, and then your try bracket:
try {
if (..) {
...
} else {
...
}
} catch (Exception e) {..}

Categories

Resources