jborgers / PMD-jPinpoint-rules

PMD rule set for responsible Java and Kotlin coding: performance, sustainability, multi-threading, data mixup and more.
Apache License 2.0
43 stars 10 forks source link

Fix Request: HttpClientBuilderWithoutTimeouts, not valid for HttpClient 5 #282

Closed jborgers closed 9 months ago

jborgers commented 9 months ago

The API of HttpClient 5 is different from HttpClient 4, for this rule relevant:

Example:

class ExampleTimeouts {
    @Bean
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient());
        // alternative way to set the 3 timeouts:
        //factory.setConnectionRequestTimeout(connectTimeoutInMillis); // 1
        //factory.setConnectTimeout(connectTimeoutInMillis); // 2
        return new RestTemplate(factory);
    }

    private CloseableHttpClient httpClient() {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(connectTimeoutInMillis, TimeUnit.MILLISECONDS) // 1
                    .setResponseTimeout(readTimeoutInMillis, TimeUnit.MILLISECONDS) // 3
                    .build();

            final ConnectionConfig connConfig = ConnectionConfig.custom()
                    .setConnectTimeout(connectTimeoutInMillis, TimeUnit.MILLISECONDS) // 2
                    .setSocketTimeout(readTimeoutInMillis, TimeUnit.MILLISECONDS).build(); // 3

            final PoolingHttpClientConnectionManager connectionManager =
                    new BasicHttpClientConnectionManager(socketFactoryRegistry);
            connectionManager.setConnectionConfig(connConfig);

            return HttpClients.custom()
                    .setDefaultRequestConfig(requestConfig)
                    .setConnectionManager(connectionManager)
                    .disableConnectionState()
                    .build();
    }
}
jborgers commented 9 months ago

Fix: The rule now checks if an import of Apache HttpClient 4 is used. We need a new rule for version 5