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 package ca.uhn.hl7v2.protocol.impl;
28
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.util.Properties;
32
33 import ca.uhn.hl7v2.llp.LLPException;
34 import ca.uhn.hl7v2.llp.MinLLPReader;
35 import ca.uhn.hl7v2.llp.MinLLPWriter;
36 import ca.uhn.hl7v2.protocol.StreamSource;
37 import ca.uhn.hl7v2.protocol.TransportException;
38 import ca.uhn.hl7v2.protocol.TransportLayer;
39 import ca.uhn.hl7v2.protocol.Transportable;
40
41
42
43
44
45
46
47
48
49 public class MLLPTransport extends AbstractTransport implements TransportLayer {
50
51 private MinLLPReader myReader;
52 private MinLLPWriter myWriter;
53
54 private final StreamSource myStreamSource;
55 private final Properties myCharsetMappings;
56
57
58
59
60
61 public MLLPTransport(StreamSource theStreamSource) throws TransportException {
62 myStreamSource = theStreamSource;
63 myCharsetMappings = loadCharsetMappings();
64 }
65
66 private static Properties loadCharsetMappings() throws TransportException {
67 Properties mappings = new Properties();
68 String resource = "ca/uhn/hl7v2/protocol/impl/charset_map.properties";
69 InputStream in = MLLPTransport.class.getClassLoader().getResourceAsStream(resource);
70 try {
71 mappings.load(in);
72 } catch (IOException e) {
73 throw new TransportException("Can't load character set mappings from " + resource, e);
74 }
75 return mappings;
76 }
77
78 public void doSend(Transportable theMessage) throws TransportException {
79 try {
80 String charset = (String) theMessage.getMetadata().get("MSH-18");
81 if (charset != null) {
82 charset = myCharsetMappings.getProperty(charset, charset);
83 myWriter.writeMessage(theMessage.getMessage(), charset);
84 } else {
85 myWriter.writeMessage(theMessage.getMessage());
86 }
87 } catch (LLPException | IOException e) {
88 throw new TransportException(e);
89 }
90 }
91
92
93
94
95 public Transportable doReceive() throws TransportException {
96 Transportable result = null;
97 try {
98 String message = myReader.getMessage();
99 if (message != null) {
100 result = new TransportableImpl(message);
101 }
102 } catch (LLPException | IOException e) {
103 throw new TransportException(e);
104 }
105 return result;
106 }
107
108 public void doConnect() throws TransportException {
109 myStreamSource.connect();
110 try {
111 myReader = new MinLLPReader(myStreamSource.getInboundStream());
112 myWriter = new MinLLPWriter(myStreamSource.getOutboundStream());
113 } catch (IOException e) {
114 throw new TransportException(e);
115 }
116 }
117
118
119
120
121 public void doDisconnect() throws TransportException {
122 try {
123 if (myReader != null) myReader.close();
124 if (myWriter != null) myWriter.close();
125 } catch (IOException e) {
126 throw new TransportException(e);
127 } finally {
128 myReader = null;
129 myWriter = null;
130 }
131 myStreamSource.disconnect();
132 }
133
134 }