Skip to content

Commit 951146c

Browse files
authored
Merge pull request #19 from lwahlmeier/refact1
2 parents a4058b1 + bd1927b commit 951146c

File tree

13 files changed

+256
-234
lines changed

13 files changed

+256
-234
lines changed

README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ Here are some simple examples of using the HTTPClient call.
2222
```java
2323
HTTPClient httpClient = new HTTPClient();
2424
httpClient.start();
25-
HTTPRequestBuilder hrb = new HTTPRequestBuilder().setHost("www.google.com").setPort(80);
26-
ListenableFuture<HTTPResponseData> lfr1 = httpClient.requestAsync(hrb.buildHTTPAddress(false), hrb.build());
27-
ListenableFuture<HTTPResponseData> lfr2 = httpClient.requestAsync(hrb.buildHTTPAddress(false), hrb.build());
28-
ListenableFuture<HTTPResponseData> lfr3 = httpClient.requestAsync(hrb.buildHTTPAddress(false), hrb.build());
25+
HTTPRequestBuilder hrb = new HTTPRequestBuilder().setHost("www.google.com").setPort(80).setSSL(false);
26+
ListenableFuture<HTTPResponseData> lfr1 = httpClient.requestAsync(hrb.buildClientHTTPRequest());
27+
ListenableFuture<HTTPResponseData> lfr2 = httpClient.requestAsync(hrb.buildClientHTTPRequest());
28+
ListenableFuture<HTTPResponseData> lfr3 = httpClient.requestAsync(hrb.buildClientHTTPRequest());
2929
FutureCallback<HTTPResponseData> fc = new FutureCallback<HTTPResponseData>() {
3030
@Override
3131
public void handleResult(HTTPResponseData result) {

client/src/main/java/org/threadly/litesockets/client/http/HTTPClient.java

Lines changed: 19 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,13 @@
2727
import org.threadly.litesockets.TCPClient;
2828
import org.threadly.litesockets.buffers.MergedByteBuffers;
2929
import org.threadly.litesockets.buffers.ReuseableMergedByteBuffers;
30+
import org.threadly.litesockets.protocols.http.request.ClientHTTPRequest;
3031
import org.threadly.litesockets.protocols.http.request.HTTPRequest;
3132
import org.threadly.litesockets.protocols.http.request.HTTPRequestBuilder;
3233
import org.threadly.litesockets.protocols.http.response.HTTPResponse;
3334
import org.threadly.litesockets.protocols.http.response.HTTPResponseProcessor;
3435
import org.threadly.litesockets.protocols.http.response.HTTPResponseProcessor.HTTPResponseCallback;
3536
import org.threadly.litesockets.protocols.http.shared.HTTPAddress;
36-
import org.threadly.litesockets.protocols.http.shared.HTTPConstants;
3737
import org.threadly.litesockets.protocols.http.shared.HTTPParsingException;
3838
import org.threadly.litesockets.protocols.http.shared.HTTPRequestType;
3939
import org.threadly.litesockets.protocols.http.shared.HTTPResponseCode;
@@ -63,7 +63,7 @@ public class HTTPClient extends AbstractService {
6363
private final MainClientProcessor mcp = new MainClientProcessor();
6464
private final RunSocket runSocketTask;
6565
private final int maxConcurrent;
66-
private volatile int defaultTimeout = DEFAULT_TIMEOUT;
66+
private volatile int defaultTimeoutMS = HTTPRequest.DEFAULT_TIMEOUT_MS;
6767
private volatile SSLContext sslContext = SSLUtils.OPEN_SSL_CTX;
6868

6969
private NoThreadSocketExecuter ntse = null;
@@ -168,8 +168,8 @@ public void closeAllClients() {
168168
*
169169
* @param timeout time in milliseconds to wait for HTTPRequests to finish.
170170
*/
171-
public void setTimeout(int timeout) {
172-
this.defaultTimeout = timeout;
171+
public void setTimeout(TimeUnit unit, int timeout) {
172+
this.defaultTimeoutMS = (int)Math.min(Math.max(unit.toMillis(timeout),HTTPRequest.MIN_TIMEOUT_MS), HTTPRequest.MAX_TIMEOUT_MS);
173173
}
174174

175175
/**
@@ -208,31 +208,6 @@ public HTTPResponseData request(final URL url, final HTTPRequestType rt, final B
208208
return hr;
209209
}
210210

211-
/**
212-
* Sends a blocking HTTP request.
213-
*
214-
* @param ha the {@link HTTPAddress} to connect to, any hostname in the actual HTTPRequest will just be sent in the protocol.
215-
* @param request the {@link HTTPRequest} to send the server once connected.
216-
* @return an {@link HTTPResponseData} object containing the headers and content of the response.
217-
* @throws HTTPParsingException is thrown if the server sends back protocol or a response that is larger then allowed.
218-
*/
219-
public HTTPResponseData request(final HTTPAddress ha, final HTTPRequest request) throws HTTPParsingException{
220-
return request(ha, request, IOUtils.EMPTY_BYTEBUFFER);
221-
}
222-
223-
/**
224-
* Sends a blocking HTTP request.
225-
*
226-
* @param ha the {@link HTTPAddress} to connect to, any hostname in the actual HTTPRequest will just be sent in the protocol.
227-
* @param request the {@link HTTPRequest} to send the server once connected.
228-
* @param body the body to send with this request. You must have set the {@link HTTPRequest} correctly for this body.
229-
* @return an {@link HTTPResponseData} object containing the headers and content of the response.
230-
* @throws HTTPParsingException is thrown if the server sends back protocol or a response that is larger then allowed.
231-
*/
232-
public HTTPResponseData request(final HTTPAddress ha, final HTTPRequest request, final ByteBuffer body) throws HTTPParsingException {
233-
return request(ha, request, body, TimeUnit.MILLISECONDS, defaultTimeout);
234-
}
235-
236211
/**
237212
* Sends a blocking HTTP request.
238213
*
@@ -244,11 +219,10 @@ public HTTPResponseData request(final HTTPAddress ha, final HTTPRequest request,
244219
* @return an {@link HTTPResponseData} object containing the headers and content of the response.
245220
* @throws HTTPParsingException is thrown if the server sends back protocol or a response that is larger then allowed.
246221
*/
247-
public HTTPResponseData request(final HTTPAddress ha, final HTTPRequest request, final ByteBuffer body, final TimeUnit unit, final long timeout)
248-
throws HTTPParsingException {
222+
public HTTPResponseData request(final ClientHTTPRequest request) throws HTTPParsingException {
249223
HTTPResponseData hr = null;
250224
try {
251-
hr = requestAsync(ha, request, body, unit, timeout).get();
225+
hr = requestAsync(request).get();
252226
} catch (InterruptedException e) {
253227
Thread.currentThread().interrupt();
254228
} catch (Exception e) {
@@ -284,45 +258,12 @@ public ListenableFuture<HTTPResponseData> requestAsync(final URL url) {
284258
* successfully or with errors.
285259
*/
286260
public ListenableFuture<HTTPResponseData> requestAsync(final URL url, final HTTPRequestType rt, final ByteBuffer bb) {
287-
boolean ssl = false;
288-
int port = HTTPConstants.DEFAULT_HTTP_PORT;
289-
String host = url.getHost();
290-
if(url.getProtocol().equalsIgnoreCase("https")) {
291-
port = HTTPConstants.DEFAULT_HTTPS_PORT;
292-
ssl = true;
293-
}
294-
if(url.getPort() != -1) {
295-
port = url.getPort();
296-
}
297261
HTTPRequestBuilder hrb = new HTTPRequestBuilder(url);
298262
hrb.setRequestType(rt);
299-
return requestAsync(new HTTPAddress(host, port, ssl), hrb.build(), bb);
263+
hrb.setTimeout(TimeUnit.MILLISECONDS, this.defaultTimeoutMS);
264+
return requestAsync(hrb.buildClientHTTPRequest());
300265
}
301266

302-
/**
303-
* Sends an asynchronous HTTP request.
304-
*
305-
* @param ha the {@link HTTPAddress} to connect to, any hostname in the actual HTTPRequest will just be sent in the protocol.
306-
* @param request the {@link HTTPRequest} to send the server once connected.
307-
* @return an {@link ListenableFuture} containing a {@link HTTPResponseData} object that will be completed when the request is finished,
308-
* successfully or with errors.
309-
*/
310-
public ListenableFuture<HTTPResponseData> requestAsync(final HTTPAddress ha, final HTTPRequest request) {
311-
return requestAsync(ha, request, IOUtils.EMPTY_BYTEBUFFER);
312-
}
313-
314-
/**
315-
* Sends an asynchronous HTTP request.
316-
*
317-
* @param ha the {@link HTTPAddress} to connect to, any hostname in the actual HTTPRequest will just be sent in the protocol.
318-
* @param request the {@link HTTPRequest} to send the server once connected.
319-
* @param body the body to send with this request. You must have set the {@link HTTPRequest} correctly for this body.
320-
* @return an {@link ListenableFuture} containing a {@link HTTPResponseData} object that will be completed when the request is finished,
321-
* successfully or with errors.
322-
*/
323-
public ListenableFuture<HTTPResponseData> requestAsync(final HTTPAddress ha, final HTTPRequest request, final ByteBuffer body) {
324-
return requestAsync(ha, request, body, TimeUnit.MILLISECONDS, defaultTimeout);
325-
}
326267

327268
/**
328269
* Sends an asynchronous HTTP request.
@@ -335,9 +276,8 @@ public ListenableFuture<HTTPResponseData> requestAsync(final HTTPAddress ha, fin
335276
* @return an {@link ListenableFuture} containing a {@link HTTPResponseData} object that will be completed when the request is finished,
336277
* successfully or with errors.
337278
*/
338-
public ListenableFuture<HTTPResponseData> requestAsync(final HTTPAddress ha,
339-
final HTTPRequest request, final ByteBuffer body, final TimeUnit unit, final long timeout) {
340-
HTTPRequestWrapper hrw = new HTTPRequestWrapper(request, ha, body, unit.toMillis(timeout));
279+
public ListenableFuture<HTTPResponseData> requestAsync(final ClientHTTPRequest request) {
280+
HTTPRequestWrapper hrw = new HTTPRequestWrapper(request);
341281
final ListenableFuture<HTTPResponseData> lf = hrw.slf;
342282
queue.add(hrw);
343283
if(ntse != null) {
@@ -363,10 +303,10 @@ private void process(HTTPRequestWrapper hrw) {
363303
sei.watchFuture(hrw.slf, hrw.timeTillExpired()+1);
364304

365305
hrw.updateReadTime();
366-
hrw.client = getTCPClient(hrw.ha);
306+
hrw.client = getTCPClient(hrw.chr.getHTTPAddress());
367307
inProcess.put(hrw.client, hrw);
368-
hrw.client.write(hrw.hr.getByteBuffer());
369-
hrw.client.write(hrw.body.duplicate());
308+
hrw.client.write(hrw.chr.getHTTPRequest().getByteBuffer());
309+
hrw.client.write(hrw.chr.getBodyBuffer().duplicate());
370310
} catch (Exception e) {
371311
//Have to catch all here or we dont keep processing if NoThreadSE is in use
372312
//hrw.slf.setFailure(e);
@@ -505,29 +445,23 @@ public void onRead(Client client) {
505445
private class HTTPRequestWrapper implements HTTPResponseCallback {
506446
private final SettableListenableFuture<HTTPResponseData> slf = new SettableListenableFuture<>(false);
507447
private final HTTPResponseProcessor hrp = new HTTPResponseProcessor();
508-
private final HTTPRequest hr;
509-
private final HTTPAddress ha;
510-
private final long timeout;
511-
private final ByteBuffer body;
448+
private final ClientHTTPRequest chr;
512449
private HTTPResponse response;
513450
private ReuseableMergedByteBuffers responseMBB = new ReuseableMergedByteBuffers();
514451
private TCPClient client;
515452
private long lastRead = Clock.lastKnownForwardProgressingMillis();
516453

517-
public HTTPRequestWrapper(HTTPRequest hr, HTTPAddress ha, ByteBuffer body, long timeout) {
454+
public HTTPRequestWrapper(ClientHTTPRequest chr) {
518455
hrp.addHTTPResponseCallback(this);
519-
this.hr = hr;
520-
this.ha = ha;
521-
this.body = body;
522-
this.timeout = timeout;
456+
this.chr = chr;
523457
}
524458

525459
public void updateReadTime() {
526460
lastRead = Clock.lastKnownForwardProgressingMillis();
527461
}
528462

529463
public long timeTillExpired() {
530-
return timeout - (Clock.lastKnownForwardProgressingMillis() - lastRead);
464+
return chr.getTimeoutMS() - (Clock.lastKnownForwardProgressingMillis() - lastRead);
531465
}
532466

533467
@Override
@@ -546,10 +480,10 @@ public void bodyData(ByteBuffer bb) {
546480

547481
@Override
548482
public void finished() {
549-
slf.setResult(new HTTPResponseData(HTTPClient.this, hr, response, responseMBB.duplicateAndClean()));
483+
slf.setResult(new HTTPResponseData(HTTPClient.this, chr.getHTTPRequest(), response, responseMBB.duplicateAndClean()));
550484
hrp.removeHTTPResponseCallback(this);
551485
inProcess.remove(client);
552-
addBackTCPClient(ha, client);
486+
addBackTCPClient(chr.getHTTPAddress(), client);
553487
processQueue();
554488
}
555489

client/src/main/java/org/threadly/litesockets/client/ws/WebSocketClient.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public class WebSocketClient implements StreamingClient {
5050
.setHeader(HTTPConstants.HTTP_KEY_CONNECTION, "Upgrade")
5151
.setHeader(HTTPConstants.HTTP_KEY_WEBSOCKET_VERSION, "13")
5252
.setHeader(HTTPConstants.HTTP_KEY_WEBSOCKET_KEY, "")
53-
.build();
53+
.buildHTTPRequest();
5454
public static final String WSS_STRING = "wss";
5555
public static final String WS_STRING = "ws";
5656
public static final int WSS_PORT = 443;
@@ -287,7 +287,7 @@ public void setRequestResponseHeaders(HTTPRequest httpRequest, HTTPResponse http
287287

288288
@Override
289289
public ListenableFuture<?> write(final ByteBuffer bb) {
290-
return write(bb, this.wsoc.getValue(), defaultMask);
290+
return write(bb, this.wsoc, defaultMask);
291291
}
292292

293293
@Override
@@ -306,7 +306,7 @@ public Executor getClientsThreadExecutor() {
306306
* @param mask sets whether or not to mask the websocket data. true to mask, false to not.
307307
* @return a {@link ListenableFuture} that will be completed once the frame has been fully written to the socket.
308308
*/
309-
public ListenableFuture<?> write(final ByteBuffer bb, final byte opCode, final boolean mask) {
309+
public ListenableFuture<?> write(final ByteBuffer bb, final WebSocketOpCode opCode, final boolean mask) {
310310
if(connectFuture.isDone()) {
311311
WebSocketFrame wsFrame = WebSocketFrameParser.makeWebSocketFrame(bb.remaining(), opCode, mask);
312312
ByteBuffer data = bb;
@@ -330,11 +330,11 @@ public ListenableFuture<?> getLastWriteFuture() {
330330
public ListenableFuture<Boolean> connect() {
331331
if(sentRequest.compareAndSet(false, true)) {
332332
hsc.connect();
333-
hsc.writeRequest(hrb.build()).addCallback(new FutureCallback<HTTPResponse>() {
333+
hsc.writeRequest(hrb.buildHTTPRequest()).addCallback(new FutureCallback<HTTPResponse>() {
334334
@Override
335335
public void handleResult(HTTPResponse result) {
336336
if(result.getResponseHeader().getResponseCode() == HTTPResponseCode.SwitchingProtocols) {
337-
String orig = hrb.build().getHTTPHeaders().getHeader(HTTPConstants.HTTP_KEY_WEBSOCKET_KEY);
337+
String orig = hrb.buildHTTPRequest().getHTTPHeaders().getHeader(HTTPConstants.HTTP_KEY_WEBSOCKET_KEY);
338338
String resp = result.getHeaders().getHeader(HTTPConstants.HTTP_KEY_WEBSOCKET_ACCEPT);
339339
if(WebSocketFrameParser.validateKeyResponse(orig, resp)) {
340340
connectFuture.setResult(true);
@@ -398,7 +398,7 @@ public void handle(final ByteBuffer bb) {
398398
data = lastFrame.unmaskPayload(data);
399399
}
400400
if(autoReplyPings && lastFrame.getOpCode() == WebSocketOpCode.Ping.getValue()) {
401-
write(IOUtils.EMPTY_BYTEBUFFER, WebSocketOpCode.Pong.getValue(), false);
401+
write(IOUtils.EMPTY_BYTEBUFFER, WebSocketOpCode.Pong, false);
402402
} else {
403403
onData.onData(lastFrame, data);
404404
}

0 commit comments

Comments
 (0)