diff --git a/.baseline/copyright/999_palantir.txt b/.baseline/copyright/999_palantir.txt new file mode 100644 index 000000000..2f090b19b --- /dev/null +++ b/.baseline/copyright/999_palantir.txt @@ -0,0 +1 @@ +(c) Copyright ${today.year} Palantir Technologies Inc. All rights reserved. diff --git a/conjure-java-jaxrs-client/src/test/java/com/palantir/conjure/java/client/jaxrs/TracerTest.java b/conjure-java-jaxrs-client/src/test/java/com/palantir/conjure/java/client/jaxrs/TracerTest.java index e2a0db9fc..2432bd811 100644 --- a/conjure-java-jaxrs-client/src/test/java/com/palantir/conjure/java/client/jaxrs/TracerTest.java +++ b/conjure-java-jaxrs-client/src/test/java/com/palantir/conjure/java/client/jaxrs/TracerTest.java @@ -78,12 +78,12 @@ public void testClientIsInstrumentedWithTracer() throws InterruptedException { Tracer.unsubscribe(TracerTest.class.getName()); assertThat(observedSpans).containsExactlyInAnyOrder( - Maps.immutableEntry(SpanType.LOCAL, "OkHttp: GET /{param}"), - Maps.immutableEntry(SpanType.LOCAL, "OkHttp: attempt 0"), - Maps.immutableEntry(SpanType.LOCAL, "OkHttp: client-side-concurrency-limiter 0/10"), - Maps.immutableEntry(SpanType.LOCAL, "OkHttp: dispatcher"), - Maps.immutableEntry(SpanType.CLIENT_OUTGOING, "OkHttp: wait-for-headers"), - Maps.immutableEntry(SpanType.CLIENT_OUTGOING, "OkHttp: wait-for-body")); + Maps.immutableEntry(SpanType.LOCAL, "OkHttp: GET /{param}"), + Maps.immutableEntry(SpanType.LOCAL, "OkHttp: attempt 0"), + Maps.immutableEntry(SpanType.LOCAL, "OkHttp: client-side-concurrency-limiter 0/10"), + Maps.immutableEntry(SpanType.LOCAL, "OkHttp: dispatcher"), + Maps.immutableEntry(SpanType.CLIENT_OUTGOING, "OkHttp: wait-for-headers"), + Maps.immutableEntry(SpanType.CLIENT_OUTGOING, "OkHttp: wait-for-body")); RecordedRequest request = server.takeRequest(); assertThat(request.getHeader(TraceHttpHeaders.TRACE_ID)).isEqualTo(traceId); diff --git a/keystores/src/main/java/com/palantir/conjure/java/config/ssl/KeyStores.java b/keystores/src/main/java/com/palantir/conjure/java/config/ssl/KeyStores.java index b7761de8e..117b946ba 100644 --- a/keystores/src/main/java/com/palantir/conjure/java/config/ssl/KeyStores.java +++ b/keystores/src/main/java/com/palantir/conjure/java/config/ssl/KeyStores.java @@ -52,14 +52,16 @@ final class KeyStores { * (everything that occurs between the header and footer). */ private static final Pattern KEY_PATTERN = Pattern.compile( - "-----BEGIN RSA PRIVATE KEY-----\n?(.+?)\n?-----END RSA PRIVATE KEY-----", Pattern.DOTALL); + "-----BEGIN RSA PRIVATE KEY-----\n?(.+?)\n?-----END RSA PRIVATE KEY-----", + Pattern.DOTALL); /** * Pattern that matches a single certificate in a PEM file. Has a capture group that captures the content of the * certificate (everything that occurs between the header and footer). */ private static final Pattern CERT_PATTERN = Pattern.compile( - "-----BEGIN CERTIFICATE-----\n?(.+?)\n?-----END CERTIFICATE-----", Pattern.DOTALL); + "-----BEGIN CERTIFICATE-----\n?(.+?)\n?-----END CERTIFICATE-----", + Pattern.DOTALL); private static final FileFilter VISIBLE_FILE_FILTER = new FileFilter() { @Override @@ -68,8 +70,7 @@ public boolean accept(File pathname) { } }; - private KeyStores() { - } + private KeyStores() {} /** * Returns a {@link KeyStore} created by loading the certificate or certificates specified by the provided path. @@ -91,10 +92,12 @@ static KeyStore createTrustStoreFromCertificates(Path path) { keyStore.setCertificateEntry(currFile.getName(), readX509Certificate(in)); } catch (IOException e) { throw new RuntimeException(String.format( - "IOException encountered when opening '%s'", currFile.toPath()), e); + "IOException encountered when opening '%s'", + currFile.toPath()), e); } catch (CertificateException | KeyStoreException e) { throw new RuntimeException(String.format( - "Could not read file at \"%s\" as an X.509 certificate", currFile.toPath()), e); + "Could not read file at \"%s\" as an X.509 certificate", + currFile.toPath()), e); } } @@ -119,7 +122,8 @@ static KeyStore createTrustStoreFromCertificates(Map throw Throwables.propagate(e); } catch (KeyStoreException | CertificateException e) { throw new RuntimeException(String.format( - "Could not read certificate alias \"%s\" as an X.509 certificate", entry.getKey()), e); + "Could not read certificate alias \"%s\" as an X.509 certificate", + entry.getKey()), e); } } diff --git a/keystores/src/main/java/com/palantir/conjure/java/config/ssl/SslSocketFactories.java b/keystores/src/main/java/com/palantir/conjure/java/config/ssl/SslSocketFactories.java index 1f63d7e72..3694b0e77 100644 --- a/keystores/src/main/java/com/palantir/conjure/java/config/ssl/SslSocketFactories.java +++ b/keystores/src/main/java/com/palantir/conjure/java/config/ssl/SslSocketFactories.java @@ -90,7 +90,7 @@ public static SSLContext createSslContext(SslConfiguration config) { */ public static SSLContext createSslContext(Map trustCertificatesByAlias) { TrustManager[] trustManagers = createTrustManagers(trustCertificatesByAlias); - return createSslContext(trustManagers, new KeyManager[]{}); + return createSslContext(trustManagers, new KeyManager[] {}); } private static SSLContext createSslContext(TrustManager[] trustManagers, KeyManager[] keyManagers) { @@ -144,7 +144,8 @@ public static TrustContext createTrustContext(SslConfiguration config) { */ public static TrustContext createTrustContext(Map trustCertificatesByAlias) { return TrustContext.of( - createSslSocketFactory(trustCertificatesByAlias), createX509TrustManager(trustCertificatesByAlias)); + createSslSocketFactory(trustCertificatesByAlias), + createX509TrustManager(trustCertificatesByAlias)); } /** @@ -171,7 +172,8 @@ public static X509TrustManager createX509TrustManager(Map PKCS1_READER_SUPPLIER = Suppliers.memoize(() -> { Pkcs1Reader reader = Iterators.getNext(PKCS1_READER_LOADER.iterator(), null); - Preconditions.checkState(reader != null, "No Pkcs1Reader services were present. Ensure that a Pkcs1Reader " - + "with a properly configured META-INF/services/ entry is present on the classpath."); + Preconditions.checkState(reader != null, + "No Pkcs1Reader services were present. Ensure that a Pkcs1Reader " + + "with a properly configured META-INF/services/ entry is present on the classpath."); return reader; }); @@ -38,7 +39,6 @@ public static Pkcs1Reader getInstance() { return PKCS1_READER_SUPPLIER.get(); } - private Pkcs1Readers() { - } + private Pkcs1Readers() {} } diff --git a/keystores/src/test/java/com/palantir/conjure/java/config/ssl/KeyStoresTests.java b/keystores/src/test/java/com/palantir/conjure/java/config/ssl/KeyStoresTests.java index 79aa0f5a1..2c1efd7f0 100644 --- a/keystores/src/test/java/com/palantir/conjure/java/config/ssl/KeyStoresTests.java +++ b/keystores/src/test/java/com/palantir/conjure/java/config/ssl/KeyStoresTests.java @@ -88,7 +88,7 @@ public void testCreateTrustStoreFromDirectoryFailsWithNonCertFiles() throws IOEx .isInstanceOf(RuntimeException.class) .hasCauseInstanceOf(CertificateParsingException.class) .hasMessageContaining(String.format("Could not read file at \"%s\" as an X.509 certificate", - tempCertFile.getAbsolutePath())); + tempCertFile.getAbsolutePath())); } @Test @@ -102,7 +102,7 @@ public void testCreateTrustStoreFromDirectoryFailsWithDirectories() throws IOExc .isInstanceOf(RuntimeException.class) .hasCauseInstanceOf(CertificateException.class) .hasMessageContaining(String.format("Could not read file at \"%s\" as an X.509 certificate", - tempDirFile.getAbsolutePath())); + tempDirFile.getAbsolutePath())); } @Test @@ -120,9 +120,10 @@ public void createTrustStoreFromCertificatesFromCertificatesByAliasInvalidCert() assertThatThrownBy(() -> KeyStores.createTrustStoreFromCertificates( ImmutableMap.of("invalid.crt", PemX509Certificate.of(cert)))) - .isInstanceOf(RuntimeException.class) - .hasCauseInstanceOf(CertificateParsingException.class) - .hasMessageContaining("Could not read certificate alias \"invalid.crt\" as an X.509 certificate"); + .isInstanceOf(RuntimeException.class) + .hasCauseInstanceOf(CertificateParsingException.class) + .hasMessageContaining( + "Could not read certificate alias \"invalid.crt\" as an X.509 certificate"); } @Test @@ -136,7 +137,7 @@ public void testCreateKeyStoreFromPemFile() throws GeneralSecurityException, IOE assertThat(keyStore.size()).isEqualTo(1); assertThat(keyStore.getCertificate( TestConstants.SERVER_KEY_CERT_COMBINED_PEM_PATH.getFileName().toString()).toString()) - .contains("CN=testCA"); + .contains("CN=testCA"); assertThat(keyStore.getKey(TestConstants.SERVER_KEY_CERT_COMBINED_PEM_PATH.getFileName().toString(), password.toCharArray()).getFormat()).isEqualTo("PKCS#8"); } @@ -179,7 +180,7 @@ public void testCreateKeyStoreFromDirectoryFailsWithNonKeyFiles() throws IOExcep .isInstanceOf(RuntimeException.class) .hasCauseInstanceOf(GeneralSecurityException.class) .hasMessageContaining(String.format("Failed to read private key from file at \"%s\"", - tempCertFile.getAbsolutePath())); + tempCertFile.getAbsolutePath())); } @Test @@ -214,14 +215,14 @@ public void testCreateKeyStoreFromPemDirectoriesFailsIfCertMissing() throws IOEx Files.copy(TestConstants.SERVER_KEY_PEM_PATH.toFile(), keyFolder.toPath().resolve("server.key").toFile()); assertThatThrownBy(() -> KeyStores.createKeyStoreFromPemDirectories( - keyFolder.toPath(), - ".key", - certFolder.toPath(), - ".cer", - password)) - .hasCauseInstanceOf(NoSuchFileException.class) - .hasMessageContaining(String.format("Failed to read certificates from file at \"%s\"", - certFolder.toPath().resolve("server.cer").toString())); + keyFolder.toPath(), + ".key", + certFolder.toPath(), + ".cer", + password)) + .hasCauseInstanceOf(NoSuchFileException.class) + .hasMessageContaining(String.format("Failed to read certificates from file at \"%s\"", + certFolder.toPath().resolve("server.cer").toString())); } @Test @@ -231,15 +232,23 @@ public void testCreateKeyStoreFromPemDirectoriesFailsIfArgIsNotDirectory() throw File file = tempFolder.newFile(); assertThatThrownBy(() -> KeyStores.createKeyStoreFromPemDirectories( - file.toPath(), ".key", folder.toPath(), ".cer", password)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining(String.format("keyDirPath is not a directory: \"%s\"", - file.toPath().toString())); + file.toPath(), + ".key", + folder.toPath(), + ".cer", + password)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(String.format("keyDirPath is not a directory: \"%s\"", + file.toPath().toString())); assertThatThrownBy(() -> KeyStores.createKeyStoreFromPemDirectories( - folder.toPath(), ".key", file.toPath(), ".cer", password)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining(String.format("certDirPath is not a directory: \"%s\"", - file.toPath().toString())); + folder.toPath(), + ".key", + file.toPath(), + ".cer", + password)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(String.format("certDirPath is not a directory: \"%s\"", + file.toPath().toString())); } } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/QosExceptionResponseMapper.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/QosExceptionResponseMapper.java index a37ac1e5e..b7e001684 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/QosExceptionResponseMapper.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/QosExceptionResponseMapper.java @@ -32,11 +32,11 @@ public final class QosExceptionResponseMapper { private static final Logger log = LoggerFactory.getLogger(QosExceptionResponseMapper.class); - private QosExceptionResponseMapper() { - } + private QosExceptionResponseMapper() {} public static Optional mapResponseCodeHeaderStream( - int code, Function> headerFn) { + int code, + Function> headerFn) { return mapResponseCode(code, header -> headerFn.apply(header).findFirst().orElse(null)); } @@ -65,7 +65,8 @@ private static Optional map308(Function headerFn) return Optional.of(QosException.retryOther(new URL(locationHeader))); } catch (MalformedURLException e) { log.error("Failed to parse location header, not performing redirect", - UnsafeArg.of("locationHeader", locationHeader), e); + UnsafeArg.of("locationHeader", locationHeader), + e); return Optional.empty(); } } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConcurrencyLimiters.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConcurrencyLimiters.java index 5ce3d3752..66dbab1fd 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConcurrencyLimiters.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConcurrencyLimiters.java @@ -165,7 +165,9 @@ private Key limiterKey(Request request) { @Value.Immutable interface Key { String hostname(); + Optional method(); + Optional pathTemplate(); } @@ -202,8 +204,10 @@ public String spanName() { static final class NoOpLimiterListener implements Limiter.Listener { @Override public void onSuccess() {} + @Override public void onIgnore() {} + @Override public void onDropped() {} } @@ -256,7 +260,9 @@ synchronized void processQueue() { if (!maybeAcquired.isPresent()) { if (!timeoutScheduled()) { timeoutCleanup = scheduledExecutorService.schedule( - this::resetLimiter, timeout.toMillis(), TimeUnit.MILLISECONDS); + this::resetLimiter, + timeout.toMillis(), + TimeUnit.MILLISECONDS); } return; } @@ -283,8 +289,8 @@ private synchronized boolean timeoutScheduled() { private synchronized void resetLimiter() { log.warn("Timed out waiting to get permits for concurrency. In most cases this would indicate some kind of " - + "deadlock. We expect that either this is caused by either service overloading, or not " - + "closing response bodies (consider using the try-with-resources pattern).", + + "deadlock. We expect that either this is caused by either service overloading, or not " + + "closing response bodies (consider using the try-with-resources pattern).", SafeArg.of("serviceClass", serviceClass), UnsafeArg.of("hostname", limiterKey.hostname()), SafeArg.of("method", limiterKey.method()), @@ -312,8 +318,7 @@ public void onSuccess(Limiter.Listener _result) { } @Override - public void onFailure(Throwable _error) { - } + public void onFailure(Throwable _error) {} }, MoreExecutors.directExecutor()); } @@ -350,7 +355,8 @@ private static final class QueuedRequest { private final Optional allocationStackTrace; private QueuedRequest( - SettableFuture future, Optional allocationStackTrace) { + SettableFuture future, + Optional allocationStackTrace) { this.future = future; this.allocationStackTrace = allocationStackTrace; } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConcurrencyLimitingInterceptor.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConcurrencyLimitingInterceptor.java index 8bf4d6719..b877cb241 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConcurrencyLimitingInterceptor.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConcurrencyLimitingInterceptor.java @@ -57,7 +57,7 @@ final class ConcurrencyLimitingInterceptor implements Interceptor { private static final ImmutableSet DROPPED_CODES = ImmutableSet.of(429, 503); - ConcurrencyLimitingInterceptor() { } + ConcurrencyLimitingInterceptor() {} @Override public Response intercept(Chain chain) throws IOException { @@ -111,7 +111,7 @@ private static Response wrapResponse(Limiter.Listener listener, Response respons private static BufferedSource wrapSource(BufferedSource currentSource, Limiter.Listener listener) { return (BufferedSource) Proxy.newProxyInstance( BufferedSource.class.getClassLoader(), - new Class[] { BufferedSource.class }, + new Class[] {BufferedSource.class}, new ReleaseConcurrencyLimitProxy(currentSource, listener)); } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConjureWindowedLimit.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConjureWindowedLimit.java index 9c41db2c8..2fba0c907 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConjureWindowedLimit.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ConjureWindowedLimit.java @@ -90,7 +90,10 @@ public void onSample(long startTime, long rtt, int inflight, boolean didDrop) { MAX_WINDOW_TIME); // +1 ensures that average rtt in nanos is never 0, which has a precond check in VegasLimit. delegate.onSample( - startTime, current.getAverageRttNanos() + 1, current.getMaxInFlight(), didDrop); + startTime, + current.getAverageRttNanos() + 1, + current.getMaxInFlight(), + didDrop); } } } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/DistinguishedNameParser.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/DistinguishedNameParser.java index d473e420d..f128232bd 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/DistinguishedNameParser.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/DistinguishedNameParser.java @@ -55,8 +55,7 @@ final class DistinguishedNameParser { private String nextAT() { // skip preceding space chars, they can present after // comma or semicolon (compatibility with RFC 1779) - for (; pos < length && chars[pos] == ' '; pos++) { - } + for (; pos < length && chars[pos] == ' '; pos++) {} if (pos == length) { return null; // reached the end of DN } @@ -80,8 +79,7 @@ private String nextAT() { // skip trailing space chars between attribute type and '=' // (compatibility with RFC 1779) if (chars[pos] == ' ') { - for (; pos < length && chars[pos] != '=' && chars[pos] == ' '; pos++) { - } + for (; pos < length && chars[pos] != '=' && chars[pos] == ' '; pos++) {} if (chars[pos] != '=' || pos == length) { throw new IllegalStateException("Unexpected end of DN: " + dn); @@ -92,8 +90,7 @@ private String nextAT() { // skip space chars between '=' and attribute value // (compatibility with RFC 1779) - for (; pos < length && chars[pos] == ' '; pos++) { - } + for (; pos < length && chars[pos] == ' '; pos++) {} // in case of oid attribute type skip its prefix: "oid." or "OID." // (compatibility with RFC 1779) @@ -133,8 +130,7 @@ private String quotedAV() { // skip trailing space chars before comma or semicolon. // (compatibility with RFC 1779) - for (; pos < length && chars[pos] == ' '; pos++) { - } + for (; pos < length && chars[pos] == ' '; pos++) {} return new String(chars, beg, end - beg); } @@ -151,7 +147,8 @@ private String hexAV() { while (true) { // check for end of attribute value // looks for space and component separators - if (pos == length || chars[pos] == '+' || chars[pos] == ',' + if (pos == length || chars[pos] == '+' + || chars[pos] == ',' || chars[pos] == ';') { end = pos; break; @@ -162,8 +159,7 @@ private String hexAV() { pos++; // skip trailing space chars before comma or semicolon. // (compatibility with RFC 1779) - for (; pos < length && chars[pos] == ' '; pos++) { - } + for (; pos < length && chars[pos] == ' '; pos++) {} break; } else if (chars[pos] >= 'A' && chars[pos] <= 'F') { chars[pos] += 32; //to low case @@ -220,7 +216,8 @@ private String escapedAV() { for (; pos < length && chars[pos] == ' '; pos++) { chars[end++] = ' '; } - if (pos == length || chars[pos] == ',' || chars[pos] == '+' + if (pos == length || chars[pos] == ',' + || chars[pos] == '+' || chars[pos] == ';') { // separator char or the end of DN has been found return new String(chars, beg, cur - beg); @@ -396,8 +393,7 @@ public String findMostSpecific(String attributeType) { return null; } - if (chars[pos] == ',' || chars[pos] == ';') { - } else if (chars[pos] != '+') { + if (chars[pos] == ',' || chars[pos] == ';') {} else if (chars[pos] != '+') { throw new IllegalStateException("Malformed DN: " + dn); } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ForwardingOkHttpClient.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ForwardingOkHttpClient.java index 2729f20e3..e10376a9c 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ForwardingOkHttpClient.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ForwardingOkHttpClient.java @@ -47,7 +47,7 @@ class ForwardingOkHttpClient extends OkHttpClient { this.delegate = delegate; } - protected OkHttpClient getDelegate() { + protected OkHttpClient getDelegate() { return delegate; } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/HostMetricsRegistry.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/HostMetricsRegistry.java index 49764d92a..6dbc897d1 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/HostMetricsRegistry.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/HostMetricsRegistry.java @@ -75,8 +75,13 @@ public Collection getMetrics() { @Value.Immutable @ImmutablesStyle interface ServiceHostAndPort { - @Value.Parameter String serviceName(); - @Value.Parameter String hostname(); - @Value.Parameter int port(); + @Value.Parameter + String serviceName(); + + @Value.Parameter + String hostname(); + + @Value.Parameter + int port(); } } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ImmutableSampleWindow.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ImmutableSampleWindow.java index bdeb8ee32..6110baac0 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ImmutableSampleWindow.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/ImmutableSampleWindow.java @@ -87,10 +87,16 @@ public boolean didDrop() { @Override public String toString() { return "ImmutableSampleWindow [" - + "minRtt=" + TimeUnit.NANOSECONDS.toMicros(minRtt) / 1000.0 - + ", avgRtt=" + TimeUnit.NANOSECONDS.toMicros(getAverageRttNanos()) / 1000.0 - + ", maxInFlight=" + maxInFlight - + ", sampleCount=" + sampleCount - + ", didDrop=" + didDrop + "]"; + + "minRtt=" + + TimeUnit.NANOSECONDS.toMicros(minRtt) / 1000.0 + + ", avgRtt=" + + TimeUnit.NANOSECONDS.toMicros(getAverageRttNanos()) / 1000.0 + + ", maxInFlight=" + + maxInFlight + + ", sampleCount=" + + sampleCount + + ", didDrop=" + + didDrop + + "]"; } } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/InstrumentedInterceptor.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/InstrumentedInterceptor.java index 11bf112a9..639b81598 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/InstrumentedInterceptor.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/InstrumentedInterceptor.java @@ -68,7 +68,9 @@ public Response intercept(Chain chain) throws IOException { } static InstrumentedInterceptor create( - TaggedMetricRegistry registry, HostEventsSink hostEventsSink, Class serviceClass) { + TaggedMetricRegistry registry, + HostEventsSink hostEventsSink, + Class serviceClass) { return new InstrumentedInterceptor(registry, hostEventsSink, serviceClass.getSimpleName()); } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/LeakDetector.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/LeakDetector.java index 3b0d4add6..f74664a2c 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/LeakDetector.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/LeakDetector.java @@ -37,7 +37,7 @@ final class LeakDetector { private final List> references = new ArrayList<>(); LeakDetector(Class resourceType) { - this(resourceType, unused -> { }); + this(resourceType, unused -> {}); } @VisibleForTesting @@ -84,15 +84,15 @@ private synchronized void pruneAndLog() { private void logLeak(Optional stackTrace) { if (stackTrace.isPresent()) { log.warn("Resource leak detected - did you forget to close a resource properly? " - + "This will likely hurt performance. Stack trace is of the call where " - + "the acquire happened.", + + "This will likely hurt performance. Stack trace is of the call where " + + "the acquire happened.", SafeArg.of("resourceType", resourceType.getName()), stackTrace.get()); } else { log.warn("Leak detected in Conjure call - did you forget to close a resource properly? " - + "This will likely hurt performance. To get a " - + "stack trace for the call where the acquire happened, set log " - + "level to TRACE.", + + "This will likely hurt performance. To get a " + + "stack trace for the call where the acquire happened, set log " + + "level to TRACE.", SafeArg.of("resourceType", resourceType.getName()), SafeArg.of("loggerToSetToTrace", log.getName())); } diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/OkHttpClients.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/OkHttpClients.java index 440d3d315..c671ae1bf 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/OkHttpClients.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/OkHttpClients.java @@ -58,11 +58,11 @@ public final class OkHttpClients { static final int NUM_SCHEDULING_THREADS = 5; private static final ThreadFactory executionThreads = new ThreadFactoryBuilder() - .setUncaughtExceptionHandler((thread, uncaughtException) -> - log.error("An exception was uncaught in an execution thread. " - + "This likely left a thread blocked, and is as such a serious bug " - + "which requires debugging.", - uncaughtException)) + .setUncaughtExceptionHandler((thread, uncaughtException) -> log.error( + "An exception was uncaught in an execution thread. " + + "This likely left a thread blocked, and is as such a serious bug " + + "which requires debugging.", + uncaughtException)) .setNameFormat("remoting-okhttp-dispatcher-%d") // This diverges from the OkHttp default value, allowing the JVM to cleanly exit // while idle dispatcher threads are still alive. @@ -116,11 +116,10 @@ public final class OkHttpClients { * #executionExecutor}, {@code corePoolSize} must not be zero for a {@link ScheduledThreadPoolExecutor}, see its * Javadoc. Since this executor will never hit zero threads, it must use daemon threads. */ - private static final Supplier schedulingExecutor = Suppliers.memoize(() -> - Tracers.wrap(Executors.newScheduledThreadPool(NUM_SCHEDULING_THREADS, + private static final Supplier schedulingExecutor = + Suppliers.memoize(() -> Tracers.wrap(Executors.newScheduledThreadPool(NUM_SCHEDULING_THREADS, Util.threadFactory("conjure-java-runtime/OkHttp Scheduler", true)))); - private OkHttpClients() {} /** @@ -128,7 +127,10 @@ private OkHttpClients() {} * ClientConfiguration#uris URIs} are initialized in random order. */ public static OkHttpClient create( - ClientConfiguration config, UserAgent userAgent, HostEventsSink hostEventsSink, Class serviceClass) { + ClientConfiguration config, + UserAgent userAgent, + HostEventsSink hostEventsSink, + Class serviceClass) { boolean reshuffle = !config.nodeSelectionStrategy().equals(NodeSelectionStrategy.PIN_UNTIL_ERROR_WITHOUT_RESHUFFLE); return createInternal(config, userAgent, hostEventsSink, serviceClass, RANDOMIZE, reshuffle); @@ -136,7 +138,10 @@ public static OkHttpClient create( @VisibleForTesting static RemotingOkHttpClient withStableUris( - ClientConfiguration config, UserAgent userAgent, HostEventsSink hostEventsSink, Class serviceClass) { + ClientConfiguration config, + UserAgent userAgent, + HostEventsSink hostEventsSink, + Class serviceClass) { return createInternal(config, userAgent, hostEventsSink, serviceClass, !RANDOMIZE, !RESHUFFLE); } @@ -168,7 +173,7 @@ private static RemotingOkHttpClient createInternal( // TODO(rfink): Should this go into the call itself? client.addInterceptor(new MeshProxyInterceptor(config.meshProxy().get())); } - client.followRedirects(false); // We implement our own redirect logic. + client.followRedirects(false); // We implement our own redirect logic. // SSL client.sslSocketFactory(config.sslSocketFactory(), config.trustManager()); @@ -199,7 +204,8 @@ private static RemotingOkHttpClient createInternal( if (config.proxyCredentials().isPresent()) { BasicCredentials basicCreds = config.proxyCredentials().get(); final String credentials = Credentials.basic(basicCreds.username(), basicCreds.password()); - client.proxyAuthenticator((route, response) -> response.request().newBuilder() + client.proxyAuthenticator((route, response) -> response.request() + .newBuilder() .header(HttpHeaders.PROXY_AUTHORIZATION, credentials) .build()); } @@ -213,8 +219,11 @@ private static RemotingOkHttpClient createInternal( client.dispatcher(dispatcher); // global metrics (addMetrics is idempotent, so this works even when multiple clients are created) - config.taggedMetricRegistry().addMetrics( - "from", DispatcherMetricSet.class.getSimpleName(), dispatcherMetricSet); + config.taggedMetricRegistry() + .addMetrics( + "from", + DispatcherMetricSet.class.getSimpleName(), + dispatcherMetricSet); return new RemotingOkHttpClient( client.build(), diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/Okhttp39HostnameVerifier.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/Okhttp39HostnameVerifier.java index 704a79e5a..6e93e5191 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/Okhttp39HostnameVerifier.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/Okhttp39HostnameVerifier.java @@ -48,8 +48,7 @@ final class Okhttp39HostnameVerifier implements HostnameVerifier { private static final int ALT_DNS_NAME = 2; private static final int ALT_IPA_NAME = 7; - private Okhttp39HostnameVerifier() { - } + private Okhttp39HostnameVerifier() {} @Override public boolean verify(String host, SSLSession session) { @@ -150,12 +149,14 @@ private static List getSubjectAltNames(X509Certificate certificate, int public boolean verifyHostname(String hostname, String pattern) { // Basic sanity checks // Check length == 0 instead of .isEmpty() to support Java 5. - if ((hostname == null) || (hostname.length() == 0) || (hostname.startsWith(".")) + if ((hostname == null) || (hostname.length() == 0) + || (hostname.startsWith(".")) || (hostname.endsWith(".."))) { // Invalid domain name return false; } - if ((pattern == null) || (pattern.length() == 0) || (pattern.startsWith(".")) + if ((pattern == null) || (pattern.length() == 0) + || (pattern.startsWith(".")) || (pattern.endsWith(".."))) { // Invalid pattern/domain name return false; diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/OkhttpTraceInterceptor.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/OkhttpTraceInterceptor.java index d27cf9ddf..b77ab3b2c 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/OkhttpTraceInterceptor.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/OkhttpTraceInterceptor.java @@ -42,7 +42,8 @@ public Response intercept(Chain chain) throws IOException { } finally { // when we reach this point, we've got a 'Response' object (so the headers have come back), but the server // hasn't necessarily filled in the request body. - DetachedSpan waitForBody = chain.request().tag(Tags.AttemptSpan.class) + DetachedSpan waitForBody = chain.request() + .tag(Tags.AttemptSpan.class) .attemptSpan() .childDetachedSpan("OkHttp: wait-for-body", SpanType.CLIENT_OUTGOING); diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/RemotingOkHttpCall.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/RemotingOkHttpCall.java index b549744c7..1a1a609bb 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/RemotingOkHttpCall.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/RemotingOkHttpCall.java @@ -216,20 +216,22 @@ public void onFailure(Call call, IOException exception) { // Fail call if backoffs are exhausted or if no retry URL can be determined. Optional backoff = backoffStrategy.nextBackoff(); if (!shouldRetry(exception, backoff)) { - callback.onFailure(call, new SafeIoException( - "Failed to complete the request due to an IOException", - exception, - UnsafeArg.of("requestUrl", call.request().url().toString()))); + callback.onFailure(call, + new SafeIoException( + "Failed to complete the request due to an IOException", + exception, + UnsafeArg.of("requestUrl", call.request().url().toString()))); return; } Optional redirectTo = urls.redirectToNext(request().url()); if (!redirectTo.isPresent()) { - callback.onFailure(call, new SafeIoException( - "Failed to determine valid failover URL", - exception, - UnsafeArg.of("requestUrl", call.request().url().toString()), - UnsafeArg.of("baseUrls", urls.getBaseUrls()))); + callback.onFailure(call, + new SafeIoException( + "Failed to determine valid failover URL", + exception, + UnsafeArg.of("requestUrl", call.request().url().toString()), + UnsafeArg.of("baseUrls", urls.getBaseUrls()))); return; } @@ -294,8 +296,9 @@ public void onResponse(Call call, Response response) throws IOException { return; } - callback.onFailure(call, new SafeIoException("Failed to handle request, " - + "this is an conjure-java-runtime bug.")); + callback.onFailure(call, + new SafeIoException("Failed to handle request, " + + "this is an conjure-java-runtime bug.")); } }); } @@ -325,7 +328,9 @@ private boolean shouldRetry(IOException exception, Optional backoff) { @SuppressWarnings("FutureReturnValueIgnored") private void scheduleExecution( - Duration backoff, Tags.AttemptSpan attemptSpan, Runnable execution) { + Duration backoff, + Tags.AttemptSpan attemptSpan, + Runnable execution) { DetachedSpan backoffSpan = attemptSpan.attemptSpan().childDetachedSpan("OkHttp: backoff-with-jitter"); // TODO(rfink): Investigate whether ignoring the ScheduledFuture is safe, #629. @@ -349,10 +354,11 @@ public Void visit(QosException.Throttle exception) { Optional nonAdvertizedBackoff = backoffStrategy.nextBackoff(); if (!nonAdvertizedBackoff.isPresent()) { - callback.onFailure(call, new SafeIoException( - "Failed to complete the request due to QosException.Throttle", - exception, - UnsafeArg.of("requestUrl", call.request().url().toString()))); + callback.onFailure(call, + new SafeIoException( + "Failed to complete the request due to QosException.Throttle", + exception, + UnsafeArg.of("requestUrl", call.request().url().toString()))); return null; } @@ -376,22 +382,24 @@ public Void visit(QosException.Throttle exception) { @Override public Void visit(QosException.RetryOther exception) { if (maxNumRelocations <= 0) { - callback.onFailure(call, new SafeIoException( - "Exceeded the maximum number of allowed redirects", - exception, - UnsafeArg.of("requestUrl", call.request().url().toString()))); + callback.onFailure(call, + new SafeIoException( + "Exceeded the maximum number of allowed redirects", + exception, + UnsafeArg.of("requestUrl", call.request().url().toString()))); return null; } // Redirect to the URL specified by the exception. Optional redirectTo = urls.redirectTo(request().url(), exception.getRedirectTo().toString()); if (!redirectTo.isPresent()) { - callback.onFailure(call, new SafeIoException( - "Failed to determine valid redirect URL after receiving QosException.RetryOther", - exception, - UnsafeArg.of("requestUrl", call.request().url().toString()), - UnsafeArg.of("redirectToUrl", exception.getRedirectTo().toString()), - UnsafeArg.of("baseUrls", urls.getBaseUrls()))); + callback.onFailure(call, + new SafeIoException( + "Failed to determine valid redirect URL after receiving QosException.RetryOther", + exception, + UnsafeArg.of("requestUrl", call.request().url().toString()), + UnsafeArg.of("redirectToUrl", exception.getRedirectTo().toString()), + UnsafeArg.of("baseUrls", urls.getBaseUrls()))); return null; } @@ -421,20 +429,22 @@ public Void visit(QosException.Unavailable exception) { Optional backoff = backoffStrategy.nextBackoff(); if (!backoff.isPresent()) { - callback.onFailure(call, new SafeIoException( - "Failed to complete the request due to QosException.Unavailable", - exception, - UnsafeArg.of("requestUrl", call.request().url().toString()))); + callback.onFailure(call, + new SafeIoException( + "Failed to complete the request due to QosException.Unavailable", + exception, + UnsafeArg.of("requestUrl", call.request().url().toString()))); return null; } // Redirect to the "next" URL, whichever that may be, after backing off. Optional redirectTo = urls.redirectToNext(request().url()); if (!redirectTo.isPresent()) { - callback.onFailure(call, new SafeIoException( - "Failed to determine valid redirect URL after receiving QosException.Unavailable", - UnsafeArg.of("requestUrl", call.request().url().toString()), - UnsafeArg.of("baseUrls", urls.getBaseUrls()))); + callback.onFailure(call, + new SafeIoException( + "Failed to determine valid redirect URL after receiving QosException.Unavailable", + UnsafeArg.of("requestUrl", call.request().url().toString()), + UnsafeArg.of("baseUrls", urls.getBaseUrls()))); return null; } @@ -497,8 +507,17 @@ private static void propagateResponse(Callback callback, Call call, Response res // TODO(rfink): Consider removing RemotingOkHttpCall#doClone method, #627 @Override public RemotingOkHttpCall doClone() { - return new RemotingOkHttpCall(getDelegate().clone(), backoffStrategy, urls, client, schedulingExecutor, - executionExecutor, limiter, maxNumRelocations, serverQoS, retryOnTimeout, retryOnSocketException); + return new RemotingOkHttpCall(getDelegate().clone(), + backoffStrategy, + urls, + client, + schedulingExecutor, + executionExecutor, + limiter, + maxNumRelocations, + serverQoS, + retryOnTimeout, + retryOnSocketException); } private Tags.AttemptSpan createNextAttempt() { diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/RemotingOkHttpClient.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/RemotingOkHttpClient.java index c135d67da..ab1aca68b 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/RemotingOkHttpClient.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/RemotingOkHttpClient.java @@ -87,7 +87,9 @@ public Builder newBuilder() { } RemotingOkHttpCall newCallWithMutableState( - Request request, BackoffStrategy backoffStrategy, int maxNumRelocations) { + Request request, + BackoffStrategy backoffStrategy, + int maxNumRelocations) { return new RemotingOkHttpCall( getDelegate().newCall(request), backoffStrategy, diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/Tags.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/Tags.java index 68bd1153c..d65f61efa 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/Tags.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/Tags.java @@ -59,6 +59,7 @@ default AttemptSpan nextAttempt(DetachedSpan entireSpan) { interface SettableDispatcherSpan { DetachedSpan dispatcherSpan(); + SettableDispatcherSpan setDispatcherSpan(DetachedSpan span); static SettableDispatcherSpan create() { @@ -70,6 +71,7 @@ static SettableDispatcherSpan create() { @ImmutablesStyle interface SettableWaitForBodySpan { DetachedSpan waitForBodySpan(); + SettableWaitForBodySpan setWaitForBodySpan(DetachedSpan span); static SettableWaitForBodySpan create() { diff --git a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/UrlSelectorImpl.java b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/UrlSelectorImpl.java index aa126ed9c..77c737aca 100644 --- a/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/UrlSelectorImpl.java +++ b/okhttp-clients/src/main/java/com/palantir/conjure/java/okhttp/UrlSelectorImpl.java @@ -50,7 +50,10 @@ final class UrlSelectorImpl implements UrlSelector { private final Duration failedUrlCooldown; private UrlSelectorImpl( - ImmutableList baseUrls, boolean reshuffle, Duration failedUrlCooldown, Clock clock) { + ImmutableList baseUrls, + boolean reshuffle, + Duration failedUrlCooldown, + Clock clock) { Preconditions.checkArgument(!baseUrls.isEmpty(), "Must specify at least one URL"); Preconditions.checkArgument(!failedUrlCooldown.isNegative(), "Cache expiration must be non-negative"); if (reshuffle) { @@ -82,8 +85,11 @@ private UrlSelectorImpl( * time. */ static UrlSelectorImpl createWithFailedUrlCooldown( - Collection baseUrls, boolean reshuffle, Duration failedUrlCooldown, Clock clock) { - ImmutableSet.Builder canonicalUrls = ImmutableSet.builder(); // ImmutableSet maintains insert order + Collection baseUrls, + boolean reshuffle, + Duration failedUrlCooldown, + Clock clock) { + ImmutableSet.Builder canonicalUrls = ImmutableSet.builder(); // ImmutableSet maintains insert order baseUrls.forEach(url -> { HttpUrl httpUrl = HttpUrl.parse(switchWsToHttp(url)); Preconditions.checkArgument(httpUrl != null, "Not a valid URL", UnsafeArg.of("url", url)); @@ -151,7 +157,7 @@ private Optional redirectTo(HttpUrl requestUrl, HttpUrl redirectBaseUrl .host(redirectBaseUrl.host()) .port(redirectBaseUrl.port()) .encodedPath( - redirectBaseUrl.encodedPath() // matching prefix + redirectBaseUrl.encodedPath() // matching prefix + requestUrl.encodedPath().substring(redirectBaseUrl.encodedPath().length())) .build()); } diff --git a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/CatchThrowableInterceptorTest.java b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/CatchThrowableInterceptorTest.java index fcdc66dfc..becdc5916 100644 --- a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/CatchThrowableInterceptorTest.java +++ b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/CatchThrowableInterceptorTest.java @@ -29,7 +29,8 @@ @RunWith(MockitoJUnitRunner.class) public final class CatchThrowableInterceptorTest { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) private Interceptor.Chain chain; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private Interceptor.Chain chain; @Test public void rethrowsIoException() throws IOException { diff --git a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/ConcurrencyLimitingInterceptorTest.java b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/ConcurrencyLimitingInterceptorTest.java index 20edf300d..580cfb82b 100644 --- a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/ConcurrencyLimitingInterceptorTest.java +++ b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/ConcurrencyLimitingInterceptorTest.java @@ -42,9 +42,12 @@ public final class ConcurrencyLimitingInterceptorTest { private static final ConcurrencyLimitingInterceptor interceptor = new ConcurrencyLimitingInterceptor(); - @Mock private BufferedSource mockSource; - @Mock private Interceptor.Chain chain; - @Mock private Limiter.Listener listener; + @Mock + private BufferedSource mockSource; + @Mock + private Interceptor.Chain chain; + @Mock + private Limiter.Listener listener; private Request request; private Response response; @@ -137,7 +140,8 @@ public void ignoresIfNoContent() throws IOException { @Test public void marksSuccessIfContentEmpty() throws IOException { - Response empty = response.newBuilder().code(204) + Response empty = response.newBuilder() + .code(204) .body(ResponseBody.create(MediaType.parse("application/json"), new byte[0])) .build(); when(chain.proceed(request)).thenReturn(empty); diff --git a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/FlowControlTest.java b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/FlowControlTest.java index 7cddb5914..2418a2276 100644 --- a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/FlowControlTest.java +++ b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/FlowControlTest.java @@ -94,7 +94,8 @@ public void test16ThreadsRateLimit20() throws ExecutionException, InterruptedExc sleep(1000); log.info("Average rate is {}, 1 minute rate is {}", rate.getMeanRate(), rate.getOneMinuteRate()); log.info("Average number of retries is {}, max is {}", - avgRetries.getSnapshot().getMean(), avgRetries.getSnapshot().getMax()); + avgRetries.getSnapshot().getMean(), + avgRetries.getSnapshot().getMax()); if (Duration.between(start, Instant.now()).compareTo(GRACE) > 0) { assertThat(rate.getMeanRate()).isGreaterThan(0.75 * rateLimit); } @@ -103,7 +104,11 @@ public void test16ThreadsRateLimit20() throws ExecutionException, InterruptedExc } private Stream createWorkers( - Meter rate, Histogram avgRetries, int numThreads, int rateLimit, Duration delay) { + Meter rate, + Histogram avgRetries, + int numThreads, + int rateLimit, + Duration delay) { RateLimiter rateLimiter = RateLimiter.create(rateLimit); return IntStream.range(0, numThreads) .mapToObj(unused -> new Worker( @@ -143,7 +148,7 @@ private Worker( @Override public void run() { - for (int i = 0; i < REQUESTS_PER_THREAD; ) { + for (int i = 0; i < REQUESTS_PER_THREAD;) { Limiter.Listener listener = Futures.getUnchecked(limiters.acquireLimiterInternal(KEY).acquire()); boolean gotRateLimited = !rateLimiter.tryAcquire(100, TimeUnit.MILLISECONDS); if (!gotRateLimited) { diff --git a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/HostMetricsTest.java b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/HostMetricsTest.java index d80708bff..690535dbf 100644 --- a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/HostMetricsTest.java +++ b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/HostMetricsTest.java @@ -41,7 +41,8 @@ public final class HostMetricsTest { private static final long secondInstant = 1; private DefaultHostMetrics hostMetrics; - @Mock private Clock clock; + @Mock + private Clock clock; @Before public void before() { diff --git a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/InstrumentedInterceptorTest.java b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/InstrumentedInterceptorTest.java index 1e9186dc9..3a9239012 100644 --- a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/InstrumentedInterceptorTest.java +++ b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/InstrumentedInterceptorTest.java @@ -48,7 +48,8 @@ public final class InstrumentedInterceptorTest { private static final Request REQUEST_A = new Request.Builder().url(URL_A).build(); private static final Request REQUEST_B = new Request.Builder().url(URL_B).build(); - @Mock private Interceptor.Chain chain; + @Mock + private Interceptor.Chain chain; private TaggedMetricRegistry registry; private InstrumentedInterceptor interceptor; diff --git a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/IoExceptionResponseHandlerTest.java b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/IoExceptionResponseHandlerTest.java index ea1f89f72..3f68b675b 100644 --- a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/IoExceptionResponseHandlerTest.java +++ b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/IoExceptionResponseHandlerTest.java @@ -52,7 +52,9 @@ public void extractsIoExceptionForAllErrorCodes() { IOException exception = decode(MediaType.APPLICATION_JSON, code, "body").get(); assertThat(exception.getMessage()).isEqualTo( "Failed to parse response body as SerializableError: " - + "{code=" + code + ", body=body, contentType=application/json}"); + + "{code=" + + code + + ", body=body, contentType=application/json}"); } } diff --git a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/MeshProxyInterceptorTest.java b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/MeshProxyInterceptorTest.java index bb44a4e5e..87f37bd21 100644 --- a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/MeshProxyInterceptorTest.java +++ b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/MeshProxyInterceptorTest.java @@ -85,7 +85,8 @@ public void intercept_stripsUserinfoFromAuthority() throws Exception { interceptor.intercept(chain); verify(chain).proceed(request.capture()); - assertThat(request.getValue().url()).isEqualTo(HttpUrl.parse("https://user:pass@localhost:456/foo/bar?baz=norf")); + assertThat(request.getValue().url()) + .isEqualTo(HttpUrl.parse("https://user:pass@localhost:456/foo/bar?baz=norf")); assertThat(request.getValue().header(HttpHeaders.HOST)).isEqualTo("foo.com"); } } diff --git a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/OkHttpClientsTest.java b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/OkHttpClientsTest.java index 672bcb105..6110bface 100644 --- a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/OkHttpClientsTest.java +++ b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/OkHttpClientsTest.java @@ -198,7 +198,8 @@ public void verifyResponseMetricsAreRegistered() throws IOException { server.enqueue(new MockResponse().setBody("pong")); createRetryingClient(1).newCall(new Request.Builder().url(url).build()).execute(); - List hostMetrics = hostEventsSink.getMetrics().stream() + List hostMetrics = hostEventsSink.getMetrics() + .stream() .filter(metrics -> metrics.hostname().equals("localhost")) .filter(metrics -> metrics.serviceName().equals("OkHttpClientsTest")) .filter(metrics -> metrics.port() == server.getPort()) @@ -232,7 +233,8 @@ public void verifyIoExceptionMetricsAreRegistered() { assertThatExceptionOfType(IOException.class) .isThrownBy(call::execute); - List hostMetrics = hostEventsSink.getMetrics().stream() + List hostMetrics = hostEventsSink.getMetrics() + .stream() .filter(metrics -> metrics.hostname().equals("bogus")) .filter(metrics -> metrics.serviceName().equals("OkHttpClientsTest")) .collect(Collectors.toList()); @@ -274,7 +276,7 @@ public void successfulCallDoesNotInvokeFailureHandler() throws Exception { call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException ioException) { - failureHandlerExecuted.release(); // should never happen + failureHandlerExecuted.release(); // should never happen } @Override @@ -284,7 +286,8 @@ public void onResponse(Call call, Response response) throws IOException { }); assertThat(successHandlerExecuted.tryAcquire(500, TimeUnit.MILLISECONDS)).isTrue(); assertThat(failureHandlerExecuted.tryAcquire(500, TimeUnit.MILLISECONDS)) - .as("onFailure was executed").isFalse(); + .as("onFailure was executed") + .isFalse(); } @Test @@ -302,11 +305,12 @@ public void onFailure(Call call, IOException ioException) { @Override public void onResponse(Call call, Response response) throws IOException { - successHandlerExecuted.release(); // should never happen + successHandlerExecuted.release(); // should never happen } }); assertThat(successHandlerExecuted.tryAcquire(100, TimeUnit.MILLISECONDS)) - .as("onSuccess was executed").isFalse(); + .as("onSuccess was executed") + .isFalse(); assertThat(failureHandlerExecuted.tryAcquire(100, TimeUnit.MILLISECONDS)).isTrue(); } @@ -682,6 +686,7 @@ public void handlesConnectTimeouts_alwaysRetry() throws IOException, Interrupted assertThat(server.takeRequest().getPath()).isEqualTo("/foo?bar"); } + @Test public void handlesSocketExceptions_disabled() throws IOException { server.shutdown(); diff --git a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/RemoteExceptionResponseHandlerTest.java b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/RemoteExceptionResponseHandlerTest.java index 1d7c78c2e..c7155ca4e 100644 --- a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/RemoteExceptionResponseHandlerTest.java +++ b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/RemoteExceptionResponseHandlerTest.java @@ -84,14 +84,20 @@ public void handlesWebApplicationExceptions() { javax.ws.rs.core.Response.Status.NOT_MODIFIED); } - private static void testEncodingAndDecodingWebException(Class exceptionClass, + private static void testEncodingAndDecodingWebException( + Class exceptionClass, Response.Status status) { WebApplicationException exceptionToProcess; try { - exceptionToProcess = exceptionClass.getConstructor(String.class, Response.Status.class).newInstance(message, - status); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException - | NoSuchMethodException | SecurityException e) { + exceptionToProcess = exceptionClass.getConstructor(String.class, Response.Status.class) + .newInstance(message, + status); + } catch (InstantiationException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException + | NoSuchMethodException + | SecurityException e) { throw new RuntimeException(e); } @@ -113,7 +119,9 @@ public void extractsRemoteExceptionForAllErrorCodes() throws Exception { assertThat(exception.getError().errorName()).isEqualTo(ErrorType.FAILED_PRECONDITION.name()); assertThat(exception.getMessage()).isEqualTo( "RemoteException: " + ErrorType.FAILED_PRECONDITION.code().name() - + " (" + ErrorType.FAILED_PRECONDITION.name() + ") with instance ID " + + " (" + + ErrorType.FAILED_PRECONDITION.name() + + ") with instance ID " + SERVICE_EXCEPTION.getErrorInstanceId()); } } @@ -129,7 +137,8 @@ public void handlesNotAuthorizedException() throws Exception { assertThat(exception.getError().errorCode()).isEqualTo(NotAuthorizedException.class.getName()); assertThat(exception.getError().errorName()).isEqualTo(message); assertThat(exception.getMessage()) - .isEqualTo("RemoteException: javax.ws.rs.NotAuthorizedException (" + message + ") with instance ID " + .isEqualTo("RemoteException: javax.ws.rs.NotAuthorizedException (" + message + + ") with instance ID " + exception.getError().errorInstanceId()); } diff --git a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/UrlSelectorImplTest.java b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/UrlSelectorImplTest.java index 8859db1ee..2e9226047 100644 --- a/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/UrlSelectorImplTest.java +++ b/okhttp-clients/src/test/java/com/palantir/conjure/java/okhttp/UrlSelectorImplTest.java @@ -69,7 +69,7 @@ public void baseUrlsMustBeCanonical() { for (String url : new String[] { "http://user:pass@foo.com/path", "http://foo.com/path?bar", - }) { + }) { Assertions.assertThatLoggableExceptionThrownBy(() -> UrlSelectorImpl.create(list(url), false)) .isInstanceOf(IllegalArgumentException.class) .hasLogMessage( @@ -81,7 +81,7 @@ public void baseUrlsMustBeCanonical() { "http://foo.com/path", "http://foo.com:80/path", "http://foo.com:8080", - }) { + }) { UrlSelectorImpl.create(list(url), false); } } @@ -217,7 +217,10 @@ public void testMarkUrlAsFailed_roundRobin_withCooldown() { Duration failedUrlCooldown = Duration.ofMillis(100); UrlSelectorImpl selector = UrlSelectorImpl.createWithFailedUrlCooldown( - list("http://foo/a", "http://bar/a"), false, failedUrlCooldown, clock); + list("http://foo/a", "http://bar/a"), + false, + failedUrlCooldown, + clock); HttpUrl requestUrl = HttpUrl.parse("http://ignored/a/b/path"); selector.markAsFailed(HttpUrl.parse("http://bar/a/b/path")); @@ -245,7 +248,10 @@ public void testAllUrlsFailed_roundRobin_withCooldown() { Duration failedUrlCooldown = Duration.ofMillis(100); UrlSelectorImpl selector = UrlSelectorImpl.createWithFailedUrlCooldown( - list("http://foo/a", "http://bar/a"), false, failedUrlCooldown, clock); + list("http://foo/a", "http://bar/a"), + false, + failedUrlCooldown, + clock); HttpUrl requestUrl = HttpUrl.parse("http://ignored/a/b/path"); selector.markAsFailed(HttpUrl.parse("http://foo/a/b/path")); @@ -267,7 +273,10 @@ public void testMarkUrlAsFailed_pinUntilError_withCooldown() { Duration failedUrlCooldown = Duration.ofMillis(100); UrlSelectorImpl selector = UrlSelectorImpl.createWithFailedUrlCooldown( - list("http://foo/a", "http://bar/a"), false, failedUrlCooldown, clock); + list("http://foo/a", "http://bar/a"), + false, + failedUrlCooldown, + clock); HttpUrl requestUrl = HttpUrl.parse("http://ignored/a/b/path"); selector.markAsFailed(HttpUrl.parse("http://bar/a/b/path")); @@ -295,7 +304,10 @@ public void testAllUrlsFailed_pinUntilError_withCooldown() { Duration failedUrlCooldown = Duration.ofMillis(100); UrlSelectorImpl selector = UrlSelectorImpl.createWithFailedUrlCooldown( - list("http://foo/a", "http://bar/a"), false, failedUrlCooldown, clock); + list("http://foo/a", "http://bar/a"), + false, + failedUrlCooldown, + clock); HttpUrl requestUrl = HttpUrl.parse("http://ignored/a/b/path"); selector.markAsFailed(HttpUrl.parse("http://foo/a/b/path")); diff --git a/pkcs1-reader-bouncy-castle/src/test/java/com/palantir/conjure/java/config/ssl/pkcs1/TestConstants.java b/pkcs1-reader-bouncy-castle/src/test/java/com/palantir/conjure/java/config/ssl/pkcs1/TestConstants.java index 684654525..aaa34cf4b 100644 --- a/pkcs1-reader-bouncy-castle/src/test/java/com/palantir/conjure/java/config/ssl/pkcs1/TestConstants.java +++ b/pkcs1-reader-bouncy-castle/src/test/java/com/palantir/conjure/java/config/ssl/pkcs1/TestConstants.java @@ -55,6 +55,5 @@ final class TestConstants { + "76718033796744915561248742011679284609107207243507370062983896261255054214388348309684926003840116764584" + "66964468281893086051962169614195259591633", 10); - private TestConstants() { - } + private TestConstants() {} } diff --git a/pkcs1-reader-sun/src/test/java/com/palantir/conjure/java/config/ssl/pkcs1/TestConstants.java b/pkcs1-reader-sun/src/test/java/com/palantir/conjure/java/config/ssl/pkcs1/TestConstants.java index 684654525..aaa34cf4b 100644 --- a/pkcs1-reader-sun/src/test/java/com/palantir/conjure/java/config/ssl/pkcs1/TestConstants.java +++ b/pkcs1-reader-sun/src/test/java/com/palantir/conjure/java/config/ssl/pkcs1/TestConstants.java @@ -55,6 +55,5 @@ final class TestConstants { + "76718033796744915561248742011679284609107207243507370062983896261255054214388348309684926003840116764584" + "66964468281893086051962169614195259591633", 10); - private TestConstants() { - } + private TestConstants() {} }