001package ca.uhn.hl7v2.llp; 002 003import static ca.uhn.hl7v2.llp.MinLLPReader.END_MESSAGE; 004import static ca.uhn.hl7v2.llp.MinLLPReader.LAST_CHARACTER; 005import static ca.uhn.hl7v2.llp.MinLLPReader.START_MESSAGE; 006 007import java.io.IOException; 008import java.io.OutputStream; 009import java.io.OutputStreamWriter; 010import java.nio.charset.Charset; 011 012import org.slf4j.Logger; 013import org.slf4j.LoggerFactory; 014 015import ca.uhn.hl7v2.HL7Exception; 016import ca.uhn.hl7v2.parser.EncodingNotSupportedException; 017import ca.uhn.hl7v2.preparser.PreParser; 018 019/** 020 * MLLP writer which uses the charset from the message being transmitted 021 */ 022public class ExtendedMinLLPWriter implements HL7Writer { 023 024 private static final Logger ourLog = LoggerFactory.getLogger(ExtendedMinLLPWriter.class); 025 private OutputStream myOutputStream; 026 027 public ExtendedMinLLPWriter(OutputStream theOut) { 028 myOutputStream = theOut; 029 } 030 031 /** 032 * {@inheritDoc} 033 */ 034 public synchronized void writeMessage(String theMessage) throws LLPException, IOException { 035 Charset javaCs; 036 String[] fields; 037 try { 038 fields = PreParser.getFields(theMessage, "MSH-18(0)"); 039 String charset = fields[0]; 040 try { 041 javaCs = CharSetUtil.convertHL7CharacterEncodingToCharSetvalue(charset); 042 } catch (EncodingNotSupportedException e) { 043 ourLog.warn("Nonvalid charset \"" + charset + "\"- defaulting to US-ASCII", e); 044 javaCs = Charset.forName("US-ASCII"); 045 } 046 } catch (HL7Exception e1) { 047 ourLog.warn("Could not detect charset - defaulting to US-ASCII", e1); 048 javaCs = Charset.forName("US-ASCII"); 049 } 050 051 OutputStreamWriter writer = new OutputStreamWriter(myOutputStream, javaCs); 052 053// writer.write(START_MESSAGE); 054// writer.append(theMessage); 055// writer.write(END_MESSAGE); 056// writer.write(LAST_CHARACTER); 057// writer.flush(); 058 059 myOutputStream.write(START_MESSAGE); 060 myOutputStream.flush(); 061 062 writer.append(theMessage); 063 writer.flush(); 064 065 myOutputStream.write(END_MESSAGE); 066 myOutputStream.write(LAST_CHARACTER); 067 myOutputStream.flush(); 068 069 } 070 071 /** 072 * {@inheritDoc} 073 */ 074 public synchronized void setOutputStream(OutputStream theOut) throws IOException { 075 myOutputStream = theOut; 076 } 077 078 /** 079 * {@inheritDoc} 080 */ 081 public synchronized void close() throws IOException { 082 myOutputStream.close(); 083 } 084 085}