Skip to content

Commit

Permalink
Javadoc and reduce boilerplate
Browse files Browse the repository at this point in the history
- Use final
- package-private methods can throw more precise exception
- Add missing Javadoc comments
- Use lambdas
- Better StringBuilder allocation
- Make private final class a static class
- Make private instance variable final in test
- Single lambda parameter does not need parentheses
- Package-private class constructor can be package-private
  • Loading branch information
garydgregory authored and ok2c committed Sep 12, 2024
1 parent 25f080f commit d9a78ce
Show file tree
Hide file tree
Showing 27 changed files with 380 additions and 188 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ public byte[] serialize(final HttpCacheStorageEntry storageEntry) throws Resourc
final RequestLine requestLine = new RequestLine(cacheEntry.getRequestMethod(), cacheEntry.getRequestURI(), HttpVersion.HTTP_1_1);
lineFormatter.formatRequestLine(line, requestLine);
outputBuffer.writeLine(line, out);
for (Iterator<Header> it = cacheEntry.requestHeaderIterator(); it.hasNext(); ) {
for (final Iterator<Header> it = cacheEntry.requestHeaderIterator(); it.hasNext(); ) {
line.clear();
lineFormatter.formatHeader(line, it.next());
outputBuffer.writeLine(line, out);
Expand All @@ -193,7 +193,7 @@ public byte[] serialize(final HttpCacheStorageEntry storageEntry) throws Resourc
final StatusLine statusLine = new StatusLine(HttpVersion.HTTP_1_1, cacheEntry.getStatus(), "");
lineFormatter.formatStatusLine(line, statusLine);
outputBuffer.writeLine(line, out);
for (Iterator<Header> it = cacheEntry.headerIterator(); it.hasNext(); ) {
for (final Iterator<Header> it = cacheEntry.headerIterator(); it.hasNext(); ) {
line.clear();
lineFormatter.formatHeader(line, it.next());
outputBuffer.writeLine(line, out);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ String generateViaHeader(final VersionInfo vi, final ProtocolVersion pv) {
}

String lookup(final ProtocolVersion pv) {
return internalCache.computeIfAbsent(pv, (v) -> {
return internalCache.computeIfAbsent(pv, v -> {
final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.hc.client5", getClass().getClassLoader());
return generateViaHeader(vi, v);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,7 @@ void testRequestCancellation() throws Exception {
.setPath("/random/1000")
.build(), null);

executorService.schedule(new Runnable() {

@Override
public void run() {
future.cancel(true);
}
}, i % 5, TimeUnit.MILLISECONDS);
executorService.schedule(() -> future.cancel(true), i % 5, TimeUnit.MILLISECONDS);

try {
future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
Expand All @@ -181,13 +175,7 @@ public void run() {
.setPath("/random/1000")
.build(), null);

executorService.schedule(new Runnable() {

@Override
public void run() {
future.cancel(true);
}
}, rnd.nextInt(200), TimeUnit.MILLISECONDS);
executorService.schedule(() -> future.cancel(true), rnd.nextInt(200), TimeUnit.MILLISECONDS);

try {
future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class TestFluent {
public static final Timeout TIMEOUT = Timeout.ofMinutes(1);

@RegisterExtension
private TestClientResources testResources = new TestClientResources(URIScheme.HTTP, ClientProtocolLevel.STANDARD, TIMEOUT);
private final TestClientResources testResources = new TestClientResources(URIScheme.HTTP, ClientProtocolLevel.STANDARD, TIMEOUT);

@BeforeEach
void setUp() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ abstract class AbstractIntegrationTestBase {
public static final Timeout TIMEOUT = Timeout.ofMinutes(1);

@RegisterExtension
private TestClientResources testResources;
private final TestClientResources testResources;

protected AbstractIntegrationTestBase(final URIScheme scheme, final ClientProtocolLevel clientProtocolLevel) {
this.testResources = new TestClientResources(scheme, clientProtocolLevel, TIMEOUT);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
Expand All @@ -47,8 +46,6 @@
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.testing.extension.sync.ClientProtocolLevel;
import org.apache.hc.client5.testing.extension.sync.TestClient;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HeaderElement;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpStatus;
Expand All @@ -58,7 +55,6 @@
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.MessageSupport;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

Expand All @@ -83,19 +79,7 @@ protected TestContentCodings(final URIScheme scheme) {
@Test
void testResponseWithNoContent() throws Exception {
configureServer(bootstrap -> bootstrap
.register("*", new HttpRequestHandler() {

/**
* {@inheritDoc}
*/
@Override
public void handle(
final ClassicHttpRequest request,
final ClassicHttpResponse response,
final HttpContext context) {
response.setCode(HttpStatus.SC_NO_CONTENT);
}
}));
.register("*", (request, response, context) -> response.setCode(HttpStatus.SC_NO_CONTENT)));

final HttpHost target = startServer();

Expand Down Expand Up @@ -326,43 +310,33 @@ void deflateResponsesWorkWithBasicResponseHandler() throws Exception {
*/
private HttpRequestHandler createDeflateEncodingRequestHandler(
final String entityText, final boolean rfc1951) {
return new HttpRequestHandler() {

/**
* {@inheritDoc}
*/
@Override
public void handle(
final ClassicHttpRequest request,
final ClassicHttpResponse response,
final HttpContext context) {
response.setEntity(new StringEntity(entityText));
response.addHeader("Content-Type", "text/plain");
final Iterator<HeaderElement> it = MessageSupport.iterate(request, "Accept-Encoding");
while (it.hasNext()) {
final HeaderElement element = it.next();
if ("deflate".equalsIgnoreCase(element.getName())) {
response.addHeader("Content-Encoding", "deflate");

/* Gack. DeflaterInputStream is Java 6. */
// response.setEntity(new InputStreamEntity(new DeflaterInputStream(new
// ByteArrayInputStream(
// entityText.getBytes("utf-8"))), -1));
final byte[] uncompressed = entityText.getBytes(StandardCharsets.UTF_8);
final Deflater compressor = new Deflater(Deflater.DEFAULT_COMPRESSION, rfc1951);
compressor.setInput(uncompressed);
compressor.finish();
final byte[] output = new byte[100];
final int compressedLength = compressor.deflate(output);
final byte[] compressed = new byte[compressedLength];
System.arraycopy(output, 0, compressed, 0, compressedLength);
response.setEntity(new InputStreamEntity(
new ByteArrayInputStream(compressed), compressedLength, null));
return;
}
}
return (request, response, context) -> {
response.setEntity(new StringEntity(entityText));
response.addHeader("Content-Type", "text/plain");
final Iterator<HeaderElement> it = MessageSupport.iterate(request, "Accept-Encoding");
while (it.hasNext()) {
final HeaderElement element = it.next();
if ("deflate".equalsIgnoreCase(element.getName())) {
response.addHeader("Content-Encoding", "deflate");

/* Gack. DeflaterInputStream is Java 6. */
// response.setEntity(new InputStreamEntity(new DeflaterInputStream(new
// ByteArrayInputStream(
// entityText.getBytes("utf-8"))), -1));
final byte[] uncompressed = entityText.getBytes(StandardCharsets.UTF_8);
final Deflater compressor = new Deflater(Deflater.DEFAULT_COMPRESSION, rfc1951);
compressor.setInput(uncompressed);
compressor.finish();
final byte[] output = new byte[100];
final int compressedLength = compressor.deflate(output);
final byte[] compressed = new byte[compressedLength];
System.arraycopy(output, 0, compressed, 0, compressedLength);
response.setEntity(new InputStreamEntity(
new ByteArrayInputStream(compressed), compressedLength, null));
return;
}
}
};
};
}

/**
Expand All @@ -374,57 +348,47 @@ public void handle(
* @return a non-null {@link HttpRequestHandler}
*/
private HttpRequestHandler createGzipEncodingRequestHandler(final String entityText) {
return new HttpRequestHandler() {

/**
* {@inheritDoc}
return (request, response, context) -> {
response.setEntity(new StringEntity(entityText));
response.addHeader("Content-Type", "text/plain");
response.addHeader("Content-Type", "text/plain");
final Iterator<HeaderElement> it = MessageSupport.iterate(request, "Accept-Encoding");
while (it.hasNext()) {
final HeaderElement element = it.next();
if ("gzip".equalsIgnoreCase(element.getName())) {
response.addHeader("Content-Encoding", "gzip");

/*
* We have to do a bit more work with gzip versus deflate, since
* Gzip doesn't appear to have an equivalent to DeflaterInputStream in
* the JDK.
*
* UPDATE: DeflaterInputStream is Java 6 anyway, so we have to do a bit
* of work there too!
*/
@Override
public void handle(
final ClassicHttpRequest request,
final ClassicHttpResponse response,
final HttpContext context) throws IOException {
response.setEntity(new StringEntity(entityText));
response.addHeader("Content-Type", "text/plain");
response.addHeader("Content-Type", "text/plain");
final Iterator<HeaderElement> it = MessageSupport.iterate(request, "Accept-Encoding");
while (it.hasNext()) {
final HeaderElement element = it.next();
if ("gzip".equalsIgnoreCase(element.getName())) {
response.addHeader("Content-Encoding", "gzip");

/*
* We have to do a bit more work with gzip versus deflate, since
* Gzip doesn't appear to have an equivalent to DeflaterInputStream in
* the JDK.
*
* UPDATE: DeflaterInputStream is Java 6 anyway, so we have to do a bit
* of work there too!
*/
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
final OutputStream out = new GZIPOutputStream(bytes);

final ByteArrayInputStream uncompressed = new ByteArrayInputStream(
entityText.getBytes(StandardCharsets.UTF_8));

final byte[] buf = new byte[60];

int n;
while ((n = uncompressed.read(buf)) != -1) {
out.write(buf, 0, n);
}

out.close();

final byte[] arr = bytes.toByteArray();
response.setEntity(new InputStreamEntity(new ByteArrayInputStream(arr),
arr.length, null));

return;
}
}
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
final OutputStream out = new GZIPOutputStream(bytes);

final ByteArrayInputStream uncompressed = new ByteArrayInputStream(
entityText.getBytes(StandardCharsets.UTF_8));

final byte[] buf = new byte[60];

int n;
while ((n = uncompressed.read(buf)) != -1) {
out.write(buf, 0, n);
}

out.close();

final byte[] arr = bytes.toByteArray();
response.setEntity(new InputStreamEntity(new ByteArrayInputStream(arr),
arr.length, null));

return;
}
}
};
};
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ void shouldExecuteMultipleCallsAndCallback() throws Exception {
}
}

private final class CountingCallback implements FutureCallback<Boolean> {
private static final class CountingCallback implements FutureCallback<Boolean> {

private final CountDownLatch latch;

Expand All @@ -190,7 +190,7 @@ public void cancelled() {
}


private final class OkidokiHandler implements HttpClientResponseHandler<Boolean> {
private static final class OkidokiHandler implements HttpClientResponseHandler<Boolean> {
@Override
public Boolean handleResponse(
final ClassicHttpResponse response) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@
import org.apache.hc.client5.testing.extension.sync.ClientProtocolLevel;
import org.apache.hc.client5.testing.extension.sync.TestClient;
import org.apache.hc.client5.testing.redirect.Redirect;
import org.apache.hc.core5.function.Decorator;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ConnectionClosedException;
Expand All @@ -72,7 +71,6 @@
import org.apache.hc.core5.http.ProtocolException;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.io.HttpRequestHandler;
import org.apache.hc.core5.http.io.HttpServerRequestHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;
Expand Down Expand Up @@ -607,26 +605,19 @@ void testDefaultHeadersRedirect() throws Exception {
void testCompressionHeaderRedirect() throws Exception {
final Queue<String> values = new ConcurrentLinkedQueue<>();
configureServer(bootstrap -> bootstrap
.setExchangeHandlerDecorator(new Decorator<HttpServerRequestHandler>() {
.setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator(
requestHandler,
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY)) {

@Override
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
return new RedirectingDecorator(
requestHandler,
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY)) {

@Override
public void handle(final ClassicHttpRequest request,
final ResponseTrigger responseTrigger,
final HttpContext context) throws HttpException, IOException {
final Header header = request.getHeader(HttpHeaders.ACCEPT_ENCODING);
if (header != null) {
values.add(header.getValue());
}
super.handle(request, responseTrigger, context);
}

};
public void handle(final ClassicHttpRequest request,
final ResponseTrigger responseTrigger,
final HttpContext context) throws HttpException, IOException {
final Header header = request.getHeader(HttpHeaders.ACCEPT_ENCODING);
if (header != null) {
values.add(header.getValue());
}
super.handle(request, responseTrigger, context);
}

})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ final class SimpleAsyncEntityConsumer extends AbstractBinAsyncEntityConsumer<byt

private final ByteArrayBuffer buffer;

public SimpleAsyncEntityConsumer() {
SimpleAsyncEntityConsumer() {
super();
this.buffer = new ByteArrayBuffer(1024);
}
Expand Down
Loading

0 comments on commit d9a78ce

Please sign in to comment.