1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package ca.uhn.hl7v2.llp;
29
30 import java.io.BufferedOutputStream;
31 import java.io.IOException;
32 import java.io.OutputStream;
33 import java.io.OutputStreamWriter;
34 import java.nio.charset.Charset;
35
36 import static ca.uhn.hl7v2.llp.MllpConstants.CHARSET_KEY;
37
38
39
40
41
42
43
44
45
46
47
48
49
50 abstract class HL7EncoderWriter<T extends MllpEncoder> implements HL7Writer {
51
52 private OutputStream out;
53 private final T encoder;
54 private Charset charset;
55 protected boolean omitBOM;
56
57
58
59
60
61 public HL7EncoderWriter() {
62 encoder = initEncoder();
63 }
64
65
66
67
68 public HL7EncoderWriter(OutputStream out) throws IOException {
69 setOutputStream(out);
70 encoder = initEncoder();
71 }
72
73
74
75
76 public HL7EncoderWriter(OutputStream out, Charset charset, boolean omitBOM) {
77 this.out = out;
78 this.charset = charset;
79 this.omitBOM = omitBOM;
80 encoder = initEncoder();
81 }
82
83 protected abstract T initEncoder();
84
85
86
87
88 public synchronized void setOutputStream(OutputStream out) {
89 if (out == null) throw new NullPointerException("OutputStream must not be null");
90 this.out = new BufferedOutputStream(out);
91 }
92
93
94
95
96
97 public synchronized void writeMessage(String message) throws LLPException, IOException {
98 if (message == null) {
99 throw new NullPointerException("Message must not be null");
100 }
101 encoder.putMessage(message, out);
102 }
103
104
105
106
107
108 public synchronized void writeMessage(String message, String charset) throws IOException {
109 if (message == null) {
110 throw new NullPointerException("Message may not be null");
111 }
112 OutputStreamWriter writer = new OutputStreamWriter(out, charset);
113 writer.write(MllpConstants.START_BYTE);
114 writer.write(message);
115 writer.write(MllpConstants.END_BYTE1);
116 writer.write(MllpConstants.END_BYTE2);
117 writer.flush();
118 }
119
120 public synchronized void close() throws IOException {
121 if (out != null) out.close();
122 }
123
124 protected Charset getCharset() {
125 if (charset == null) {
126 String charsetString = System.getProperty(CHARSET_KEY, "US-ASCII");
127 if (charsetString.equals("default")) {
128 charset = Charset.defaultCharset();
129 } else {
130 charset = Charset.forName(charsetString);
131 }
132 }
133 return charset;
134 }
135 }