printing HL7 message in console - java

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.

Related

Can I change the setting of command line in the current process from Java code?

I am developing a Java code. Now I need to use a REST function for translation with command line and I need to bring the standard out from it to Java code.
My problem is that I cannot get correct Japanese words from the REST function because character code of the command line is inappropriate for Japanese.
The followings are the example code.
private String getFirstLineOfStdOut(Process p) {
String first_line_value = "";
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
first_line_value = br.readLine(); // because it is one line output.
} catch (IOException e) {
e.printStackTrace();
}
return first_line_value;
}
public void runCommandLine(String[] commands) {
ProcessBuilder pb_check_char_code = new ProcessBuilder(commands);
Process process_check_char_code = null;
try {
process_check_char_code = pb_check_char_code.start();
} catch (IOException e) {
e.printStackTrace();
}
try {
process_check_char_code.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
String result = getFirstLineOfStdOut(process_check_char_code);
System.out.println(result);
}
I run the following code.
runCommandLine(new String[]{"C:\\Windows\\System32\\chcp.com"});
runCommandLine(new String[]{"C:\\Windows\\System32\\chcp.com", "65001"});
runCommandLine(new String[]{"sudo_translate_function", "English", "to", "Japanese", "hello"});
runCommandLine(new String[]{"C:\\Windows\\System32\\chcp.com"});
And their results.
現在のコード ページ: 932 // It means Active code page: 932
Active code page: 65001
壊れた文字 // broken words because of the inappropriate character code, 932
現在のコード ページ: 932 // It means Active code page: 932
The appropriate words should be "こんにちは" but not to be "壊れた文字".
I am afraid that they cannot share the change of character code across sub-process.
What should I do to share the change of character code?
Thank you very much.

Connect to remote server via telnet and update a file programmatically

I want to change the settings of a PROROUTE wireless cellular router (H685) from the web application.
The only way to change the settings, is to login to the router via telnet and change a file in the editor (i.e. vi) and reboot.
I want to do it programmatically from server side using JAVA,
I can connect to the router and send command, using TelnetClient
Here is the sample code to connect to the router via telnet and send command
public class Test
{
private TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
private String prompt = "#";
public Test(String server, String user, String password) {
try {
// Connect to the specified server
telnet.connect(server, 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("Login:");
write(user);
readUntil("Password:");
write(password);
// Advance to a prompt
readUntil(prompt + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length() - 1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar) {
if (sb.toString().endsWith(pattern)) {
return sb.toString();
}
}
ch = (char) in.read();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + " ");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
Test telnet = new Test("192.168.1.1", "username", "pwd");
telnet.sendCommand("ls");
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
But I have to update the file in the editor.
Send command to open the file in vi
$vi /flash/.disable_fun_list
function_dtu:
function_wifi:
function_gps:
.
.
.
.
function_wifi:on (this line needs to be changed)
and then send command to restart the router.
$reboot
Any idea, how this can be done.
What you're thinking to do sounds a terrible idea.
I feel there is no need to open this file in vi editor. In such cases, people generally suggest to create a temporary file and replace it with the original.
Suggested approach :
Open the file which you want to modify using BufferedReader on top of FileReader.
Modify the string, if you've to replace the currently read line; if not, then simply proceed to step 3.
Now, once you've string ready(whether changed OR unchanged) to be written to a file, then create a temporary file, and write the read string(line) to this temporary file.
Once, you're done with all the line of the original file, then close the BufferedReader, and delete(or, better rename to something else) the original file. Rename the temp file to the original filename, and move this temp file to the location of the original file from where you've copied(and modified) the content!
Code should flow like :
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
//Step 2 : do modification with the string read
//Step 3 : write the final modified string inside a temp file.
// Step 4 : close the br, and rename/delete the old file; rename the temp file to this original file.
}
you can use vi from command line without actually opening the vi as an app
you can pass args to vi to do a string replace for what you need
and you can pass args to save the file, plus the file path of course.
so you might end up executing this command via telnet connection
vi -c "%s/function_wifi:on/function_wifi:off/g|wq" /path/to/config/file
this will replace the string function_wifi:on with function_wifi:off and save the file.
simply then send a reboot command.
for more check this link
change above program to
private String prompt = ">";
instead of
private String prompt = "#";

Search word in text file and print the line

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

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());

String to Text - Line Break instead of comma

I need help before I'm totally despaired :D
As you will see I tried it in different ways even if there are just a really few differences. My problem is that I have a string which I want (or have) to output. This means I need it in a text file. Not that big problem, eh? But the actual problem is that I want line breaks instead of commas. I know I could just replace them after the file is written but it's just unnecessary when there is another way.
The Output looks like this
[/rechtschreibung/_n, /rechtschreibung/_nauf, /rechtschreibung/_naus,
/rechtschreibung/_Ndrangheta, ....]
I want it to look like this
/rechtschreibung/_n
/rechtschreibung/_nauf
/rechtschreibung/_naus
/rechtschreibung/_Ndrangheta
Anyway even when I don't need this method later because I will store this and some other information into a database like sql. It will help me to build up the program step by step and learn some more Java ;)
So here is my code snippet
BufferedWriter bw = null;
//PrintWriter out
//= new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
try {
bw = new BufferedWriter(new FileWriter("bfwr.txt"));
bw.write(test5.getWoerterListe().toString());
bw.newLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
try {
PrintWriter out = new PrintWriter(new FileWriter("prwr.txt"));
out.print(test5.getWoerterListe());
out.close();
System.out.printf("Testing String");
} catch (IOException e) {
e.printStackTrace();
}
*/
/*
try {
FileWriter test10 = new FileWriter("test.txt");
test10.write(test5.getWoerterListe().toString());
test10.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
Please be nice to me :D
Assistance appreciated =)
EDIT #1
Code directly before first one.
Oberordner test2 = new Oberordner("http://www.duden.de/definition");
Unterordner test3 = new Unterordner(test2.getOberOrdner());
WoerterListe test5 = new WoerterListe(test3.getUnterOrdnerURL());
test5.setWoerterListe();
and from WoerterListe.java the really end part
public ArrayList<String> getWoerterListe(){
return WoerterListe;
}
Additional Information: the string is not stored in the code because there are tenthousands of words like '/rechtschreibung/*'
By the way the language here is german unfortunately I have to use german words =(
I'm not a Java developer and you didn't state what getWoerterListe() returns, but here's my guess.
getWoerterListe() probably return a list of strings, and the default behaviour of toString() in this case is to convert the list to comma seperated values. So instead of calling toString() on the list, loop through it and write out each line followed by a carriage return (or whatever Java uses to end lines).
Code:
String s = "[/rechtschreibung/_n, /rechtschreibung/_nauf, "
+ "/rechtschreibung/_naus, /rechtschreibung/_Ndrangheta, ....]";
String srp = s.replaceAll("\\[|\\]|\\.+" ,"");
String[] sp = srp.split(",");
for (int i = 0; i < sp.length; i++) {
System.out.println(sp[i].trim());
}
Output:
/rechtschreibung/_n
/rechtschreibung/_nauf
/rechtschreibung/_naus
/rechtschreibung/_Ndrangheta
Explanation:
I assumed [/rechtschreibung/_n, /rechtschreibung/_nauf, /rechtschreibung/_naus, /rechtschreibung/_Ndrangheta, ....] is a String. I removed all uncessary character like [ , ] , and any number of . form it. After that, I splited by , and print each element of splited string on the output.

Categories

Resources