fix StringUtils test
[fanfix.git] / src / be / nikiroo / utils / serial / server / ServerBridge.java
CommitLineData
8537d55a
NR
1package be.nikiroo.utils.serial.server;
2
08f80ac5 3import java.io.ByteArrayInputStream;
8537d55a 4import java.io.IOException;
08f80ac5 5import java.io.InputStream;
452f38c8 6import java.lang.reflect.Array;
8537d55a 7import java.net.Socket;
f4053377 8import java.net.UnknownHostException;
8537d55a 9
452f38c8 10import be.nikiroo.utils.StringUtils;
8537d55a 11import be.nikiroo.utils.TraceHandler;
8537d55a
NR
12import be.nikiroo.utils.serial.Importer;
13
14/**
15 * This class implements a simple server that can bridge two other
16 * {@link Server}s.
17 * <p>
18 * It can, of course, inspect the data that goes through it (by default, it
19 * prints traces of the data).
20 * <p>
21 * Note: this {@link ServerBridge} has to be discarded after use (cannot be
22 * started twice).
23 *
24 * @author niki
25 */
26public class ServerBridge extends Server {
27 private final String forwardToHost;
28 private final int forwardToPort;
8468bb79 29 private final String forwardToKey;
8537d55a
NR
30
31 /**
32 * Create a new server that will start listening on the network when
33 * {@link ServerBridge#start()} is called.
34 *
35 * @param port
36 * the port to listen on, or 0 to assign any unallocated port
37 * found (which can later on be queried via
38 * {@link ServerBridge#getPort()}
8468bb79
NR
39 * @param key
40 * an optional key to encrypt all the communications (if NULL,
41 * everything will be sent in clear text)
452f38c8
NR
42 * @param forwardToHost
43 * the host server to forward the calls to
44 * @param forwardToPort
45 * the host port to forward the calls to
8468bb79
NR
46 * @param forwardToKey
47 * an optional key to encrypt all the communications (if NULL,
48 * everything will be sent in clear text)
8537d55a
NR
49 *
50 * @throws IOException
51 * in case of I/O error
f4053377
NR
52 * @throws UnknownHostException
53 * if the IP address of the host could not be determined
54 * @throws IllegalArgumentException
55 * if the port parameter is outside the specified range of valid
56 * port values, which is between 0 and 65535, inclusive
8537d55a 57 */
8468bb79
NR
58 public ServerBridge(int port, String key, String forwardToHost,
59 int forwardToPort, String forwardToKey) throws IOException {
60 super(port, key);
8537d55a
NR
61 this.forwardToHost = forwardToHost;
62 this.forwardToPort = forwardToPort;
8468bb79 63 this.forwardToKey = forwardToKey;
8537d55a
NR
64 }
65
66 /**
67 * Create a new server that will start listening on the network when
68 * {@link ServerBridge#start()} is called.
69 *
70 * @param name
71 * the server name (only used for debug info and traces)
72 * @param port
73 * the port to listen on
8468bb79
NR
74 * @param key
75 * an optional key to encrypt all the communications (if NULL,
76 * everything will be sent in clear text)
452f38c8
NR
77 * @param forwardToHost
78 * the host server to forward the calls to
79 * @param forwardToPort
80 * the host port to forward the calls to
8468bb79
NR
81 * @param forwardToKey
82 * an optional key to encrypt all the communications (if NULL,
83 * everything will be sent in clear text) use an SSL connection
84 * for the forward server or not
8537d55a
NR
85 *
86 * @throws IOException
87 * in case of I/O error
f4053377
NR
88 * @throws UnknownHostException
89 * if the IP address of the host could not be determined
90 * @throws IllegalArgumentException
91 * if the port parameter is outside the specified range of valid
92 * port values, which is between 0 and 65535, inclusive
8537d55a 93 */
8468bb79
NR
94 public ServerBridge(String name, int port, String key,
95 String forwardToHost, int forwardToPort, String forwardToKey)
8537d55a 96 throws IOException {
8468bb79 97 super(name, port, key);
8537d55a
NR
98 this.forwardToHost = forwardToHost;
99 this.forwardToPort = forwardToPort;
8468bb79 100 this.forwardToKey = forwardToKey;
8537d55a
NR
101 }
102
103 /**
104 * The traces handler for this {@link Server}.
105 * <p>
452f38c8 106 * The trace levels are handled as follow:
8537d55a 107 * <ul>
452f38c8
NR
108 * <li>1: it will only print basic IN/OUT messages with length</li>
109 * <li>2: it will try to interpret it as an object (SLOW) and print the
110 * object class if possible</li>
111 * <li>3: it will try to print the {@link Object#toString()} value, or the
112 * data if it is not an object</li>
113 * <li>4: it will also print the unzipped serialised value if it is an
114 * object</li>
8537d55a
NR
115 * </ul>
116 *
117 * @param tracer
118 * the new traces handler
119 */
120 @Override
121 public void setTraceHandler(TraceHandler tracer) {
122 super.setTraceHandler(tracer);
123 }
124
125 @Override
126 protected ConnectActionServer createConnectActionServer(Socket s) {
08f80ac5 127 // Bad impl, not up to date (should work, but not efficient)
8468bb79 128 return new ConnectActionServerString(s, key) {
8537d55a 129 @Override
08f80ac5
NR
130 public void action() throws Exception {
131 onClientContact();
8537d55a
NR
132 final ConnectActionServerString bridge = this;
133
f4053377
NR
134 try {
135 new ConnectActionClientString(forwardToHost, forwardToPort,
08f80ac5 136 forwardToKey) {
f4053377 137 @Override
08f80ac5
NR
138 public void action() throws Exception {
139 onServerContact();
8537d55a 140
f4053377
NR
141 for (String fromClient = bridge.rec(); fromClient != null; fromClient = bridge
142 .rec()) {
08f80ac5 143 onRec(fromClient);
f4053377 144 String fromServer = send(fromClient);
08f80ac5 145 onSend(fromServer);
f4053377
NR
146 bridge.send(fromServer);
147 }
d827da2a 148
f4053377
NR
149 getTraceHandler().trace("=== DONE", 1);
150 getTraceHandler().trace("", 1);
151 }
0ff71477 152
f4053377
NR
153 @Override
154 protected void onError(Exception e) {
155 ServerBridge.this.onError(e);
156 }
157 }.connect();
158 } catch (Exception e) {
159 ServerBridge.this.onError(e);
160 }
8537d55a
NR
161 }
162 };
163 }
164
165 /**
166 * This is the method that is called each time a client contact us.
8537d55a 167 */
08f80ac5
NR
168 protected void onClientContact() {
169 getTraceHandler().trace(">>> CLIENT ");
8537d55a
NR
170 }
171
172 /**
173 * This is the method that is called each time a client contact us.
8537d55a 174 */
08f80ac5
NR
175 protected void onServerContact() {
176 getTraceHandler().trace("<<< SERVER");
217a3310 177 getTraceHandler().trace("");
8537d55a
NR
178 }
179
180 /**
181 * This is the method that is called each time a client contact us.
182 *
8537d55a
NR
183 * @param data
184 * the data sent by the client
185 */
08f80ac5
NR
186 protected void onRec(String data) {
187 trace(">>> CLIENT", data);
8537d55a
NR
188 }
189
190 /**
191 * This is the method that is called each time the forwarded server contact
192 * us.
193 *
8537d55a
NR
194 * @param data
195 * the data sent by the client
196 */
08f80ac5
NR
197 protected void onSend(String data) {
198 trace("<<< SERVER", data);
8537d55a
NR
199 }
200
340e6065
NR
201 @Override
202 protected ConnectActionClient getConnectionToMe()
203 throws UnknownHostException, IOException {
204 return new ConnectActionClientString(new Socket((String) null,
205 getPort()), key);
206 }
207
f4053377
NR
208 @Override
209 public void run() {
210 getTraceHandler().trace(
211 getName() + ": will forward to " + forwardToHost + ":"
212 + forwardToPort + " ("
8468bb79
NR
213 + (forwardToKey != null ? "encrypted" : "plain text")
214 + ")");
f4053377
NR
215 super.run();
216 }
217
8537d55a
NR
218 /**
219 * Trace the data with the given prefix.
220 *
221 * @param prefix
222 * the prefix (client, server, version...)
223 * @param data
224 * the data to trace
225 */
226 private void trace(String prefix, String data) {
08f80ac5 227 // TODO: we convert to string and back
f8f2afb4 228 int size = data == null ? 0 : data.length();
8468bb79 229 String ssize = StringUtils.formatNumber(size) + "bytes";
452f38c8
NR
230
231 getTraceHandler().trace(prefix + ": " + ssize, 1);
8537d55a
NR
232
233 if (getTraceHandler().getTraceLevel() >= 2) {
234 try {
a359464f
NR
235 while (data.startsWith("ZIP:") || data.startsWith("B64:")) {
236 if (data.startsWith("ZIP:")) {
a6a73de3 237 data = StringUtils.unzip64s(data.substring(4));
a359464f 238 } else if (data.startsWith("B64:")) {
a6a73de3 239 data = StringUtils.unzip64s(data.substring(4));
a359464f 240 }
452f38c8
NR
241 }
242
08f80ac5 243 InputStream stream = new ByteArrayInputStream(
f8147a0e 244 StringUtils.getBytes(data));
08f80ac5
NR
245 try {
246 Object obj = new Importer().read(stream).getValue();
247 if (obj == null) {
248 getTraceHandler().trace("NULL", 2);
249 getTraceHandler().trace("NULL", 3);
250 getTraceHandler().trace("NULL", 4);
452f38c8 251 } else {
08f80ac5
NR
252 if (obj.getClass().isArray()) {
253 getTraceHandler().trace(
254 "(" + obj.getClass() + ") with "
255 + Array.getLength(obj)
256 + "element(s)", 3);
257 } else {
258 getTraceHandler().trace("(" + obj.getClass() + ")",
259 2);
260 }
261 getTraceHandler().trace("" + obj.toString(), 3);
262 getTraceHandler().trace(data, 4);
452f38c8 263 }
08f80ac5
NR
264 } finally {
265 stream.close();
8537d55a 266 }
452f38c8
NR
267 } catch (NoSuchMethodException e) {
268 getTraceHandler().trace("(not an object)", 2);
269 getTraceHandler().trace(data, 3);
270 getTraceHandler().trace("", 4);
271 } catch (NoSuchFieldException e) {
272 getTraceHandler().trace(
217a3310 273 "(incompatible: " + e.getMessage() + ")", 2);
452f38c8
NR
274 getTraceHandler().trace(data, 3);
275 getTraceHandler().trace("", 4);
276 } catch (ClassNotFoundException e) {
277 getTraceHandler().trace(
278 "(unknown object: " + e.getMessage() + ")", 2);
279 getTraceHandler().trace(data, 3);
280 getTraceHandler().trace("", 4);
8537d55a 281 } catch (Exception e) {
217a3310
NR
282 getTraceHandler().trace(
283 "(decode error: " + e.getMessage() + ")", 2);
452f38c8
NR
284 getTraceHandler().trace(data, 3);
285 getTraceHandler().trace("", 4);
8537d55a
NR
286 }
287
452f38c8 288 getTraceHandler().trace("", 2);
8537d55a
NR
289 }
290 }
8537d55a 291}