View Javadoc

1   package ca.uhn.hl7v2.llp;
2   
3   import static ca.uhn.hl7v2.llp.MinLLPReader.END_MESSAGE;
4   import static ca.uhn.hl7v2.llp.MinLLPReader.LAST_CHARACTER;
5   import static ca.uhn.hl7v2.llp.MinLLPReader.START_MESSAGE;
6   
7   import java.io.IOException;
8   import java.io.OutputStream;
9   import java.io.OutputStreamWriter;
10  import java.nio.charset.Charset;
11  
12  import org.slf4j.Logger;
13  import org.slf4j.LoggerFactory;
14  
15  import ca.uhn.hl7v2.HL7Exception;
16  import ca.uhn.hl7v2.parser.EncodingNotSupportedException;
17  import ca.uhn.hl7v2.preparser.PreParser;
18  
19  /**
20   * MLLP writer which uses the charset from the message being transmitted
21   */
22  public class ExtendedMinLLPWriter implements HL7Writer {
23  
24  	private static final Logger ourLog = LoggerFactory.getLogger(ExtendedMinLLPWriter.class);
25  	private OutputStream myOutputStream;
26  
27  	public ExtendedMinLLPWriter(OutputStream theOut) {
28  		myOutputStream = theOut;
29  	}
30  
31  	/**
32  	 * {@inheritDoc}
33  	 */
34  	public synchronized void writeMessage(String theMessage) throws LLPException, IOException {
35  		Charset javaCs;
36  		String[] fields;
37  		try {
38  			fields = PreParser.getFields(theMessage, "MSH-18(0)");
39  			String charset = fields[0];
40  			try {
41  				javaCs = CharSetUtil.convertHL7CharacterEncodingToCharSetvalue(charset);
42  			} catch (EncodingNotSupportedException e) {
43  				ourLog.warn("Nonvalid charset \"" + charset + "\"- defaulting to US-ASCII", e);
44  				javaCs = Charset.forName("US-ASCII");
45  			}
46  		} catch (HL7Exception e1) {
47  			ourLog.warn("Could not detect charset - defaulting to US-ASCII", e1);
48  			javaCs = Charset.forName("US-ASCII");
49  		}
50  
51  		OutputStreamWriter writer = new OutputStreamWriter(myOutputStream, javaCs);
52  		
53  //		writer.write(START_MESSAGE);
54  //		writer.append(theMessage);
55  //		writer.write(END_MESSAGE);
56  //		writer.write(LAST_CHARACTER);
57  //		writer.flush();
58  
59  		myOutputStream.write(START_MESSAGE);
60  		myOutputStream.flush();
61  		
62  		writer.append(theMessage);
63  		writer.flush();
64  		
65  		myOutputStream.write(END_MESSAGE);
66  		myOutputStream.write(LAST_CHARACTER);
67  		myOutputStream.flush();
68  		
69  	}
70  
71  	/**
72  	 * {@inheritDoc}
73  	 */
74  	public synchronized void setOutputStream(OutputStream theOut) throws IOException {
75  		myOutputStream = theOut;
76  	}
77  
78  	/**
79  	 * {@inheritDoc}
80  	 */
81  	public synchronized void close() throws IOException {
82  		myOutputStream.close();
83  	}
84  
85  }