-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathNetworkGateway.java
More file actions
390 lines (350 loc) · 15.3 KB
/
NetworkGateway.java
File metadata and controls
390 lines (350 loc) · 15.3 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package com.global.api.gateways;
import com.global.api.entities.enums.Host;
import com.global.api.entities.enums.HostError;
import com.global.api.entities.enums.Target;
import com.global.api.entities.exceptions.GatewayComsException;
import com.global.api.entities.exceptions.GatewayException;
import com.global.api.entities.exceptions.GatewayTimeoutException;
import com.global.api.gateways.events.*;
import com.global.api.serviceConfigs.NetworkGatewayConfig;
import com.global.api.terminals.abstractions.IDeviceMessage;
import com.global.api.utils.NtsUtils;
import com.global.api.utils.StringUtils;
import com.global.api.utils.GnapUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.*;
public class NetworkGateway {
private SSLSocket client;
private DataOutputStream out;
private InputStream in;
private int connectionFaults = 0;
private String primaryEndpoint;
private Integer primaryPort;
private String secondaryEndpoint;
private Integer secondaryPort;
protected Host currentHost;
private boolean enableLogging = false;
private HashMap<Host, ArrayList<HostError>> simulatedHostErrors;
private int timeout;
private String connectorName = "NetworkGateway";
private IGatewayEventHandler gatewayEventHandler;
@Getter @Setter
private Target target;
private ExecutorService executorService = null;
@Getter @Setter
private int connectionTimeout;
@Getter @Setter
public NetworkGatewayConfig config;
public String getPrimaryEndpoint() {
return primaryEndpoint;
}
public void setPrimaryEndpoint(String primaryEndpoint) {
this.primaryEndpoint = primaryEndpoint;
}
public Integer getPrimaryPort() {
return primaryPort;
}
public void setPrimaryPort(Integer primaryPort) {
this.primaryPort = primaryPort;
}
public String getSecondaryEndpoint() {
return secondaryEndpoint;
}
public void setSecondaryEndpoint(String secondaryEndpoint) {
this.secondaryEndpoint = secondaryEndpoint;
}
public Integer getSecondaryPort() {
return secondaryPort;
}
public void setSecondaryPort(Integer secondaryPort) {
this.secondaryPort = secondaryPort;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
protected boolean isEnableLogging() {
return enableLogging;
}
public void setEnableLogging(boolean enableLogging) {
this.enableLogging = enableLogging;
if(target.equals(Target.GNAP))
{
GnapUtils.enableLogging(enableLogging);
} else if(target.equals(Target.NTS)){
NtsUtils.enableLogging();
}
}
public void setGatewayEventHandler(IGatewayEventHandler eventHandler) { this.gatewayEventHandler = eventHandler; }
public HashMap<Host, ArrayList<HostError>> getSimulatedHostErrors() {
return simulatedHostErrors;
}
public void setSimulatedHostErrors(HashMap<Host, ArrayList<HostError>> simulatedHostErrors) {
this.simulatedHostErrors = simulatedHostErrors;
}
private boolean isForcedError(HostError error) {
if(simulatedHostErrors != null && simulatedHostErrors.containsKey(currentHost)) {
return simulatedHostErrors.get(currentHost).contains(error);
}
return false;
}
// establish connection
private void connect(String endpoint, Integer port) throws GatewayComsException {
executorService = Executors.newCachedThreadPool();
currentHost = endpoint.equals(primaryEndpoint) ? Host.Primary : Host.Secondary;
// create the connection event
ConnectionEvent connectionEvent = new ConnectionEvent(connectorName);
connectionEvent.setEndpoint(endpoint);
connectionEvent.setPort(port.toString());
connectionEvent.setHost(currentHost.getValue());
connectionEvent.setConnectionAttempts(connectionFaults);
raiseGatewayEvent(connectionEvent);
DateTime connectionStarted = DateTime.now(DateTimeZone.UTC);
if(client == null || out == null || in == null || !client.isConnected()) {
if(client != null) {
disconnect();
}
try {
// connection started
connectionEvent.setConnectionStarted(connectionStarted);
logResponse(connectionEvent.getEventMessage());
// check for simulated connection error
if(!isForcedError(HostError.Connection)) {
try {
SSLSocketFactory factory = new SSLSocketFactoryEx();
client = (SSLSocket) factory.createSocket();
Callable<Integer> task = () -> {
client.connect(new InetSocketAddress(endpoint, port), 5000);
return 0;
};
Future<Integer> future = executorService.submit(task);
future.get(connectionTimeout, TimeUnit.MILLISECONDS);
client.startHandshake();
raiseGatewayEvent(new SslHandshakeEvent(connectorName, null));
logResponse(new SslHandshakeEvent(connectorName, null).getEventMessage());
}
catch (TimeoutException | InterruptedException e) {
throw new GatewayTimeoutException();
}
catch(Exception exc) {
raiseGatewayEvent(new SslHandshakeEvent(connectorName, exc));
logResponse(new SslHandshakeEvent(connectorName, exc).getEventMessage());
if(client != null && client.isConnected()) {
disconnect();
}
}
}
if(client != null && client.isConnected()) {
// connection completed
raiseGatewayEvent(new ConnectionCompleteEvent(connectorName, connectionStarted, DateTime.now(DateTimeZone.UTC)));
logResponse(new ConnectionCompleteEvent(connectorName, connectionStarted, DateTime.now(DateTimeZone.UTC)).getEventMessage());
out = new DataOutputStream(client.getOutputStream());
in = client.getInputStream();
client.setKeepAlive(true);
connectionFaults = 0;
}
else {
// connection fail over
raiseGatewayEvent(new FailOverEvent(connectorName, connectionStarted, DateTime.now(DateTimeZone.UTC)));
logResponse(new FailOverEvent(connectorName, connectionStarted, DateTime.now(DateTimeZone.UTC)).getEventMessage());
if(connectionFaults++ != 3) {
if(endpoint.equals(primaryEndpoint) && secondaryEndpoint != null) {
connect(secondaryEndpoint, secondaryPort);
}
else {
connect(primaryEndpoint, primaryPort);
}
}
else {
throw new IOException("Failed to connect to primary or secondary processing endpoints.");
}
}
}
catch(Exception exc) {
throw new GatewayComsException(exc);
}
}
}
// close connection
private void disconnect() {
try {
if (client != null && !client.isClosed()) {
if(in != null) {
in.close();
}
if(out != null) {
out.close();
}
client.close();
}
client = null;
}
catch(IOException exc) {
// eat the close exception
}
}
@SneakyThrows
public byte[] send(IDeviceMessage message) throws GatewayException {
/*
1) if the initial attempt to connect fails (on both hosts) a GatewayComsException is thrown
2) if the send/receive fails, no exception is thrown (timeout flag is tripped) and fail over occurs
3) if timeout flag is set, Failure to connect to secondary host will throw GatewayTimeoutException
4) if timeout flag is not set, failure to connect to the secondary host will throw GatewayComsException
5) if connection to secondary host is successful, return to step 2
6) if no response from the secondary host, GatewayTimeoutException is thrown
*/
boolean timeout = false;
connect(getPrimaryEndpoint(), getPrimaryPort());
byte[] buffer = message.getSendBuffer();
try {
for (int i = 0; i < 2; i++) {
raiseGatewayEvent(new RequestSentEvent(connectorName));
DateTime requestSent = DateTime.now(DateTimeZone.UTC);
logResponse(new RequestSentEvent(connectorName).getEventMessage());
try {
if (!isForcedError(HostError.SendFailure)) {
out.write(buffer);
} else throw new IOException("Simulated IO Exception on request send.");
byte[] rvalue = getGatewayResponse();
if (rvalue != null && !isForcedError(HostError.Timeout)) {
raiseGatewayEvent(new ResponseReceivedEvent(connectorName, requestSent));
logResponse(new ResponseReceivedEvent(connectorName, requestSent).getEventMessage());
return rvalue;
}
timeout = true;
} catch (IOException exc) {
/* Exception occurred on message send, do not trip timeout */
}
// did not get a response, switch endpoints and try again
if (!currentHost.equals(Host.Secondary) && !StringUtils.isNullOrEmpty(secondaryEndpoint) && i < 1) {
raiseGatewayEvent(new TimeoutEvent(connectorName, GatewayEventType.TimeoutFailOver));
logResponse(new TimeoutEvent(connectorName, GatewayEventType.TimeoutFailOver).getEventMessage());
disconnect();
connect(getSecondaryEndpoint(), getSecondaryPort());
}
}
raiseGatewayEvent(new TimeoutEvent(connectorName, GatewayEventType.Timeout));
logResponse(new TimeoutEvent(connectorName, GatewayEventType.Timeout).getEventMessage());
if (timeout) {
throw new GatewayTimeoutException();
} else throw new GatewayComsException();
} catch (GatewayComsException exc) {
if (timeout) {
throw new GatewayTimeoutException(exc);
}
throw exc;
} finally {
disconnect();
shutdownExecutorService();
// remove the force timeout
raiseGatewayEvent(new DisconnectEvent(connectorName));
logResponse(new DisconnectEvent(connectorName).getEventMessage());
// remove simulated errors
if (simulatedHostErrors != null) {
simulatedHostErrors = null;
}
}
}
private byte[] getGatewayResponse() throws IOException, GatewayException {
byte[] buffer = new byte[2048];
int bytesReceived = awaitResponse(in, buffer);
if(bytesReceived > 0) {
byte[] rec_buffer = new byte[bytesReceived];
System.arraycopy(buffer, 0, rec_buffer, 0, bytesReceived);
return rec_buffer;
}
return null;
}
private int awaitResponse(InputStream in, byte[] buffer) throws GatewayException {
Callable<Integer> task = () -> {
long startTime = System.currentTimeMillis();
int position = 0;
Integer messageLength = null;
do {
try {
if (messageLength == null) {
byte[] lengthBuffer = new byte[2];
int length = in.read(lengthBuffer, 0, 2);
if (length == 2) {
messageLength = target != null && target.equals(Target.GNAP)
? new BigInteger(lengthBuffer).intValue()
: new BigInteger(lengthBuffer).intValue() - 2;
}
else {
throw new IOException("Failed to read message length.");
}
}
if (messageLength != null) {
int currLength = in.read(buffer, position, messageLength - position);
if (currLength == -1) {
throw new IOException("End of stream reached unexpectedly.");
}
position += currLength;
if (position == messageLength) {
return messageLength;
}
}
Thread.sleep(50);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new GatewayException("Thread interrupted while waiting for response.");
}
catch (IOException e) {
throw new GatewayException("Error while reading response: " + e.getMessage());
}
} while ((System.currentTimeMillis() - startTime) <= timeout);
throw new GatewayTimeoutException("Response timed out after " + timeout + " milliseconds.");
};
Future<Integer> future = executorService.submit(task);
try {
return future.get(timeout, TimeUnit.MILLISECONDS);
}
catch (TimeoutException e) {
throw new GatewayTimeoutException("Response timed out after " + timeout + " milliseconds.");
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new GatewayException("Thread interrupted while waiting for response.");
}
catch (ExecutionException e) {
throw new GatewayException("Error while executing response task: " + e.getCause().getMessage());
}
}
public void shutdownExecutorService(){
executorService.shutdown();
try {
if(!executorService.awaitTermination(1,TimeUnit.SECONDS)){
executorService.shutdownNow();
}
}
catch (InterruptedException e) {
executorService.shutdownNow();
}
}
private void raiseGatewayEvent(final IGatewayEvent event) {
if(gatewayEventHandler != null) {
new Thread(new Runnable() {
public void run() {
gatewayEventHandler.eventRaised(event);
}
}).start();
}
}
protected void logResponse(String response) throws IOException {
config.getRequestLogger().ResponseReceived(response);
}
}