1 package ca.uhn.hl7v2.hoh.llp;
2
3 import java.io.DataOutputStream;
4 import java.io.IOException;
5 import java.io.OutputStream;
6 import java.nio.charset.Charset;
7
8 import ca.uhn.hl7v2.hoh.api.EncodeException;
9 import ca.uhn.hl7v2.hoh.encoder.AbstractHl7OverHttpEncoder;
10 import ca.uhn.hl7v2.hoh.encoder.Hl7OverHttpRequestEncoder;
11 import ca.uhn.hl7v2.hoh.encoder.Hl7OverHttpResponseEncoder;
12 import ca.uhn.hl7v2.hoh.util.ServerRoleEnum;
13 import ca.uhn.hl7v2.llp.HL7Writer;
14 import ca.uhn.hl7v2.llp.LLPException;
15
16 class HohLlpWriter implements HL7Writer {
17
18 private OutputStream myOutputStream;
19 private Charset myPreferredCharset;
20 private final Hl7OverHttpLowerLayerProtocol myProtocol;
21 private Charset myCharsetForNextMessage;
22
23
24
25
26 public HohLlpWriter(Hl7OverHttpLowerLayerProtocol theProtocol) {
27 myProtocol = theProtocol;
28 }
29
30
31
32
33 public void close() throws IOException {
34 myOutputStream.close();
35 }
36
37 OutputStream getOutputStream() {
38 return myOutputStream;
39 }
40
41
42
43
44 public Charset getPreferredCharset() {
45 return myPreferredCharset;
46 }
47
48
49
50
51 @Override
52 public void setOutputStream(OutputStream theOutputStream) throws IOException {
53 myOutputStream = theOutputStream;
54 }
55
56
57
58
59
60 public void setPreferredCharset(Charset thePreferredCharset) {
61 myPreferredCharset = thePreferredCharset;
62 }
63
64
65
66
67 @Override
68 public void writeMessage(String theRawMessage) throws LLPException, IOException {
69
70 AbstractHl7OverHttpEncoder e;
71 if (myProtocol.getRole() == ServerRoleEnum.CLIENT) {
72 Hl7OverHttpRequestEncoder encoder = new Hl7OverHttpRequestEncoder();
73 if (myProtocol.getHost() != null) {
74 encoder.setHost(myProtocol.getHost());
75 }
76 e = encoder;
77 if (myProtocol.getAuthorizationClientCallback() != null) {
78 e.setUsername(myProtocol.getAuthorizationClientCallback().provideUsername(myProtocol.getUriPath()));
79 e.setPassword(myProtocol.getAuthorizationClientCallback().providePassword(myProtocol.getUriPath()));
80 }
81 } else {
82 e = new Hl7OverHttpResponseEncoder();
83 }
84
85 if (myProtocol.getRole() == ServerRoleEnum.CLIENT) {
86 e.setSigner(myProtocol.getSigner());
87 }
88
89 e.setMessage(theRawMessage);
90 if (myCharsetForNextMessage != null) {
91 e.setCharset(myCharsetForNextMessage);
92 myCharsetForNextMessage = null;
93 } else if (getPreferredCharset() != null) {
94 e.setCharset(getPreferredCharset());
95 }
96
97 e.setPath(myProtocol.getUriPath());
98 DataOutputStream dos = new DataOutputStream(myOutputStream);
99 try {
100 e.encodeToOutputStream(dos);
101 } catch (EncodeException e1) {
102 throw new LLPException("Failed to encode message", e1);
103 }
104
105 dos.flush();
106
107 }
108
109 void setCharsetForNextMessage(Charset theCharset) {
110 myCharsetForNextMessage = theCharset;
111 }
112
113 }