diff options
Diffstat (limited to 'common-app-api/src/main/java/org/openecomp/sdc/common/http/client')
12 files changed, 189 insertions, 194 deletions
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java index 7273a04bd0..21c0f45e24 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,11 +19,10 @@ */ package org.openecomp.sdc.common.http.client.api; - import org.apache.http.client.HttpRequestRetryHandler; public interface ComparableHttpRequestRetryHandler extends HttpRequestRetryHandler { - default <T extends HttpRequestRetryHandler> boolean compare(T handler) { + public default <T extends HttpRequestRetryHandler> boolean compare(T handler) { return (handler != null && getClass() == handler.getClass()); } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java index 9ed3efde11..66a7050821 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,13 +29,7 @@ import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.methods.*; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; @@ -52,19 +46,17 @@ import java.net.URI; import java.util.Properties; public class HttpClient { - private static final Logger LOGGER = Logger.getLogger(HttpClient.class.getName()); - public static final int HTTPS_PORT = 443; - public static final int HTTP_PORT = 80; - + private static final Logger logger = Logger.getLogger(HttpClient.class.getName()); + private final CloseableHttpClient client; private final HttpClientConfigImmutable configImmutable; - - HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) { + + public HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) { this.client = client; - this.configImmutable = configImmutable; + this.configImmutable = configImmutable; } - - <T> HttpResponse<T> get(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + + public <T> HttpResponse<T> get(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { HttpGet httpGet = new HttpGet(url); return execute(httpGet, headers, responseBuilder); } @@ -91,17 +83,18 @@ public class HttpClient { HttpDelete httpDelete = new HttpDelete(url); return execute(httpDelete, headers, responseBuilder); } - + void close() { try { client.close(); - } catch (IOException e) { - LOGGER.debug("Close http client failed with exception ", e); + } + catch (IOException e) { + logger.debug("Close http client failed with exception ", e); } } - + private <T> HttpResponse<T> execute(HttpRequestBase request, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { - if (configImmutable.getHeaders() != null) { + if(configImmutable.getHeaders() != null) { configImmutable.getHeaders().forEach(request::addHeader); } @@ -110,52 +103,57 @@ public class HttpClient { } HttpClientContext httpClientContext = null; - if (request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) { + if(request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) { httpClientContext = createHttpContext(request.getURI()); } - LOGGER.debug("Execute request {}", request.getRequestLine()); + logger.debug("Execute request {}", request.getRequestLine()); try (CloseableHttpResponse response = client.execute(request, httpClientContext)) { return responseBuilder.apply(response); - } catch (Exception e) { - String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage()); + } + catch (Exception e) { + String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage()); BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description, ErrorSeverity.ERROR); - LOGGER.debug("{}: ", description, e); + logger.debug("{}: ",description, e); throw new HttpExecuteException(description, e); - } + } } private HttpClientContext createHttpContext(URI uri) { - if (StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) { + if(StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) { return null; } CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); int port = getPort(uri); - credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port), + credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port), new UsernamePasswordCredentials(configImmutable.getBasicAuthUserName(), configImmutable.getBasicAuthPassword())); HttpClientContext localContext = HttpClientContext.create(); localContext.setCredentialsProvider(credentialsProvider); AuthCache authCache = new BasicAuthCache(); - authCache.put(new HttpHost(uri.getHost(), port), (AuthScheme) new BasicScheme()); + HttpHost target = new HttpHost(uri.getHost(), port, "https"); + authCache.put(target, (AuthScheme) new BasicScheme()); localContext.setAuthCache(authCache); return localContext; } private int getPort(URI uri) { - int port = uri.getPort(); - if (port < 0) { - if (Constants.HTTPS.equals(uri.getScheme())) { - port = HTTPS_PORT; - } else if (Constants.HTTP.equals(uri.getScheme())) { - port = HTTP_PORT; - } else { + int port = uri.getPort(); + if(port < 0) { + if(Constants.HTTPS.equals(uri.getScheme())) { + port = 443; + } + else + if (Constants.HTTP.equals(uri.getScheme())) { + port = 80; + } + else { port = AuthScope.ANY_PORT; - LOGGER.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port); + logger.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port); } } return port; diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java index f0fe09fe7c..9b21e1ac87 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,40 +29,46 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -final class HttpClientConfigImmutable { +public final class HttpClientConfigImmutable { private final Map<String, String> headers; private final BasicAuthorization basicAuthorization; private final ClientCertificate clientCertificate; private final Timeouts timeouts; + private boolean enableMetricLogging; /* - * use ComparableHttpRequestRetryHandler.compare instead of default generated equals + * use ComparableHttpRequestRetryHandler.compare instead of default generated equals */ private final ComparableHttpRequestRetryHandler retryHandler; private final int numOfRetries; - + static HttpClientConfigImmutable getOrCreate(HttpClientConfig httpClientConfig) { // TODO: retrieve from a pool if exist, otherwise create new - return new HttpClientConfigImmutable(httpClientConfig); + return new HttpClientConfigImmutable(httpClientConfig); } - HttpClientConfigImmutable(HttpClientConfig httpClientConfig) { + public HttpClientConfigImmutable(HttpClientConfig httpClientConfig) { timeouts = httpClientConfig.getTimeouts() != null ? new Timeouts(httpClientConfig.getTimeouts()) : null; basicAuthorization = httpClientConfig.getBasicAuthorization() != null ? new BasicAuthorization(httpClientConfig.getBasicAuthorization()) : null; clientCertificate = httpClientConfig.getClientCertificate() != null ? new ClientCertificate(httpClientConfig.getClientCertificate()) : null; headers = httpClientConfig.getHeaders() != null ? Collections.unmodifiableMap(new HashMap<>(httpClientConfig.getHeaders())) : null; retryHandler = httpClientConfig.getRetryHandler(); numOfRetries = httpClientConfig.getNumOfRetries(); + enableMetricLogging = httpClientConfig.isEnableMetricLogging(); + } + + public boolean isEnableMetricLogging() { + return enableMetricLogging; } Map<String, String> getHeaders() { return headers; } - int getNumOfRetries() { + public int getNumOfRetries() { return numOfRetries; } - + String getBasicAuthPassword() { return basicAuthorization != null ? basicAuthorization.getPassword() : null; } @@ -82,20 +88,20 @@ final class HttpClientConfigImmutable { ClientCertificate getClientCertificate() { return clientCertificate != null ? new ClientCertificate(clientCertificate) : null; } - - int getReadTimeoutMs() { + + public int getReadTimeoutMs() { return timeouts.getReadTimeoutMs(); } - int getConnectTimeoutMs() { + public int getConnectTimeoutMs() { return timeouts.getConnectTimeoutMs(); } - int getConnectPoolTimeoutMs() { + public int getConnectPoolTimeoutMs() { return timeouts.getConnectPoolTimeoutMs(); } - ComparableHttpRequestRetryHandler getRetryHandler() { + public ComparableHttpRequestRetryHandler getRetryHandler() { return retryHandler; } @@ -113,51 +119,43 @@ final class HttpClientConfigImmutable { @Override public boolean equals(Object obj) { - if (this == obj) { + if (this == obj) return true; - } - if (obj == null) { + if (obj == null) return false; - } - if (getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) return false; - } HttpClientConfigImmutable other = (HttpClientConfigImmutable) obj; if (basicAuthorization == null) { - if (other.basicAuthorization != null) { + if (other.basicAuthorization != null) return false; - } - } else if (!basicAuthorization.equals(other.basicAuthorization)) { - return false; } + else if (!basicAuthorization.equals(other.basicAuthorization)) + return false; if (clientCertificate == null) { - if (other.clientCertificate != null) { + if (other.clientCertificate != null) return false; - } - } else if (!clientCertificate.equals(other.clientCertificate)) { - return false; } + else if (!clientCertificate.equals(other.clientCertificate)) + return false; if (headers == null) { - if (other.headers != null) { + if (other.headers != null) return false; - } - } else if (!headers.equals(other.headers)) { - return false; } + else if (!headers.equals(other.headers)) + return false; if (retryHandler == null) { - if (other.retryHandler != null) { + if (other.retryHandler != null) return false; - } - } else if (!retryHandler.compare(other.retryHandler)) { - return false; } + else if (!retryHandler.compare(other.retryHandler)) + return false; if (timeouts == null) { - if (other.timeouts != null) { + if (other.timeouts != null) return false; - } - } else if (!timeouts.equals(other.timeouts)) { - return false; } + else if (!timeouts.equals(other.timeouts)) + return false; return true; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java index 24e2f909bc..982453246f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,33 +25,36 @@ import org.apache.http.client.UserTokenHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.http.config.ClientCertificate; +import org.openecomp.sdc.common.log.interceptors.ApacheClientLogRequestInterceptor; +import org.openecomp.sdc.common.log.interceptors.ApacheClientLogResponseInterceptor; import org.openecomp.sdc.common.log.wrappers.Logger; public class HttpClientFactory { - private static final Logger LOGGER = Logger.getLogger(HttpClientFactory.class.getName()); - private static final UserTokenHandler USER_TOKEN_HANDLER = context -> null; + private static final Logger logger = Logger.getLogger(HttpClientFactory.class.getName()); + private static final UserTokenHandler userTokenHandler = context -> null; private final HttpConnectionMngFactory connectionMngFactory; - + HttpClientFactory(HttpConnectionMngFactory connectionMngFactory) { this.connectionMngFactory = connectionMngFactory; } HttpClient createClient(String protocol, HttpClientConfigImmutable config) { - LOGGER.debug("Create {} client based on {}", protocol, config); + logger.debug("Create {} client based on {}", protocol, config); - ClientCertificate clientCertificate = Constants.HTTPS.equals(protocol) ? config.getClientCertificate() : null; + ClientCertificate clientCertificate = Constants.HTTPS.equals(protocol) ? config.getClientCertificate() : null; HttpClientConnectionManager connectionManager = connectionMngFactory.getOrCreate(clientCertificate); RequestConfig requestConfig = createClientTimeoutConfiguration(config); CloseableHttpClient client = HttpClients.custom() - .setDefaultRequestConfig(requestConfig) - .setConnectionManager(connectionManager) - .setUserTokenHandler(USER_TOKEN_HANDLER) - .setRetryHandler(resolveRetryHandler(config)) - .build(); + .setDefaultRequestConfig(requestConfig) + .setConnectionManager(connectionManager) + .setUserTokenHandler(userTokenHandler) + .setRetryHandler(resolveRetryHandler(config)) + .build(); return new HttpClient(client, config); } @@ -59,7 +62,7 @@ public class HttpClientFactory { private HttpRequestRetryHandler resolveRetryHandler(HttpClientConfigImmutable config) { return config.getNumOfRetries() > 0 ? config.getRetryHandler() : null; } - + private RequestConfig createClientTimeoutConfiguration(HttpClientConfigImmutable config) { return RequestConfig.custom() .setConnectTimeout(config.getConnectTimeoutMs()) diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java index d5d03329bb..c5634eaf8c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -48,42 +48,43 @@ public class HttpConnectionMngFactory { private static final String P12_KEYSTORE_EXTENTION = ".p12"; private static final String PFX_KEYSTORE_EXTENTION = ".pfx"; private static final String JKS_KEYSTORE_EXTENTION = ".jks"; - + private static final String P12_KEYSTORE_TYPE = "pkcs12"; private static final String JKS_KEYSTORE_TYPE = "jks"; - - private static final Logger LOGGER = Logger.getLogger(HttpConnectionMngFactory.class.getName()); + + private static final Logger logger = Logger.getLogger(HttpConnectionMngFactory.class.getName()); private static final int DEFAULT_CONNECTION_POOL_SIZE = 30; private static final int DEFAULT_MAX_CONNECTION_PER_ROUTE = 5; private static final int VALIDATE_CONNECTION_AFTER_INACTIVITY_MS = 10000; - + private Map<ClientCertificate, HttpClientConnectionManager> sslClientConnectionManagers = new ConcurrentHashMap<>(); private HttpClientConnectionManager plainClientConnectionManager; - + HttpConnectionMngFactory() { plainClientConnectionManager = createConnectionMng(null); } HttpClientConnectionManager getOrCreate(ClientCertificate clientCertificate) { - if (clientCertificate == null) { + if(clientCertificate == null) { return plainClientConnectionManager; } return sslClientConnectionManagers.computeIfAbsent(clientCertificate, k -> createConnectionMng(clientCertificate)); } - + private HttpClientConnectionManager createConnectionMng(ClientCertificate clientCertificate) { SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); SSLConnectionSocketFactory sslsf = null; try { sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy()); - - if (clientCertificate != null) { + + if(clientCertificate != null) { setClientSsl(clientCertificate, sslContextBuilder); } sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE); - } catch (GeneralSecurityException e) { - LOGGER.debug("Create SSL connection socket factory failed with exception, use default SSL factory ", e); + } + catch (GeneralSecurityException e) { + logger.debug("Create SSL connection socket factory failed with exception, use default SSL factory ", e); sslsf = SSLConnectionSocketFactory.getSocketFactory(); } @@ -105,12 +106,13 @@ public class HttpConnectionMngFactory { char[] keyStorePassword = clientCertificate.getKeyStorePassword().toCharArray(); KeyStore clientKeyStore = createClientKeyStore(clientCertificate.getKeyStore(), keyStorePassword); sslContextBuilder.loadKeyMaterial(clientKeyStore, keyStorePassword); - LOGGER.debug("#setClientSsl - Set Client Certificate authentication"); - } catch (IOException | GeneralSecurityException e) { - LOGGER.debug("#setClientSsl - Set Client Certificate authentication failed with exception, diasable client SSL authentication ", e); + logger.debug("#setClientSsl - Set Client Certificate authentication"); + } + catch (IOException | GeneralSecurityException e) { + logger.debug("#setClientSsl - Set Client Certificate authentication failed with exception, diasable client SSL authentication ", e); } } - + private KeyStore createClientKeyStore(String keyStorePath, char[] keyStorePassword) throws IOException, GeneralSecurityException { KeyStore keyStore = null; try (InputStream stream = new FileInputStream(keyStorePath)) { @@ -119,14 +121,15 @@ public class HttpConnectionMngFactory { } return keyStore; } - + private String getKeyStoreType(String keyStore) { - if (!StringUtils.isEmpty(keyStore)) { - if (keyStore.endsWith(P12_KEYSTORE_EXTENTION) || keyStore.endsWith(PFX_KEYSTORE_EXTENTION)) { + if(!StringUtils.isEmpty(keyStore)) { + if(keyStore.endsWith(P12_KEYSTORE_EXTENTION) || keyStore.endsWith(PFX_KEYSTORE_EXTENTION)) { return P12_KEYSTORE_TYPE; - } else if (keyStore.endsWith(JKS_KEYSTORE_EXTENTION)) { - return JKS_KEYSTORE_TYPE; } + else if(keyStore.endsWith(JKS_KEYSTORE_EXTENTION)) { + return JKS_KEYSTORE_TYPE; + } } return KeyStore.getDefaultType(); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java index 2b2e7a4f12..8487e1ff72 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,17 +25,17 @@ public class HttpExecuteException extends Exception { private static final long serialVersionUID = 1L; public HttpExecuteException(String message) { - super(message); + super (message); } public HttpExecuteException(String message, Throwable cause) { - super(message, cause); + super (message, cause); } public HttpExecuteException(Throwable cause) { super(cause); } - + @Override public Throwable getCause() { Throwable cause = super.getCause(); diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java index b418ce744e..57e5cb2bed 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,34 +28,27 @@ import java.util.Properties; //TODO- remove all static and use instance methods for better testing public abstract class HttpRequest { - private static final Properties DEFAULT_HEADERS = null; - private static final HttpClientConfig DEFAULT_CONFIG = new HttpClientConfig(); + static final Properties defaultHeaders = null; + static final HttpClientConfig defaultConfig = new HttpClientConfig(); - private HttpRequest() { - } - - public static Properties getDefaultHeaders() { - return DEFAULT_HEADERS; - } - public static HttpClientConfig getDefaultConfig() { - return DEFAULT_CONFIG; + private HttpRequest() { } /* * GET response as string */ public static HttpResponse<String> get(String url) throws HttpExecuteException { - return get(url, DEFAULT_HEADERS, DEFAULT_CONFIG); + return get(url, defaultHeaders, defaultConfig); } public static HttpResponse<String> get(String url, Properties headers) throws HttpExecuteException { - return get(url, headers, DEFAULT_CONFIG); + return get(url, headers, defaultConfig); } - + public static HttpResponse<String> get(String url, HttpClientConfig config) throws HttpExecuteException { - return get(url, DEFAULT_HEADERS, config); + return get(url, defaultHeaders, config); } public static HttpResponse<String> get(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { @@ -66,15 +59,15 @@ public abstract class HttpRequest { * GET response as byte array */ public static HttpResponse<byte[]> getAsByteArray(String url) throws HttpExecuteException { - return getAsByteArray(url, DEFAULT_HEADERS, DEFAULT_CONFIG); + return getAsByteArray(url, defaultHeaders, defaultConfig); } public static HttpResponse<byte[]> getAsByteArray(String url, Properties headers) throws HttpExecuteException { - return getAsByteArray(url, headers, DEFAULT_CONFIG); + return getAsByteArray(url, headers, defaultConfig); } public static HttpResponse<byte[]> getAsByteArray(String url, HttpClientConfig config) throws HttpExecuteException { - return getAsByteArray(url, DEFAULT_HEADERS, config); + return getAsByteArray(url, defaultHeaders, config); } public static HttpResponse<byte[]> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { @@ -85,15 +78,15 @@ public abstract class HttpRequest { * PUT */ public static HttpResponse<String> put(String url, HttpEntity entity) throws HttpExecuteException { - return put(url, DEFAULT_HEADERS, entity, DEFAULT_CONFIG); + return put(url, defaultHeaders, entity, defaultConfig); } public static HttpResponse<String> put(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { - return put(url, headers, entity, DEFAULT_CONFIG); + return put(url, headers, entity, defaultConfig); } - + public static HttpResponse<String> put(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { - return put(url, DEFAULT_HEADERS, entity, config); + return put(url, defaultHeaders, entity, config); } public static HttpResponse<String> put(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { @@ -104,59 +97,59 @@ public abstract class HttpRequest { * POST */ public static HttpResponse<String> post(String url, HttpEntity entity) throws HttpExecuteException { - return post(url, DEFAULT_HEADERS, entity, DEFAULT_CONFIG); + return post(url, defaultHeaders, entity, defaultConfig); } public static HttpResponse<String> post(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { - return post(url, headers, entity, DEFAULT_CONFIG); + return post(url, headers, entity, defaultConfig); } - + public static HttpResponse<String> post(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { - return post(url, DEFAULT_HEADERS, entity, config); + return post(url, defaultHeaders, entity, config); } public static HttpResponse<String> post(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().post(url, headers, entity, config); } - + /* * PATCH */ public static HttpResponse<String> patch(String url, HttpEntity entity) throws HttpExecuteException { - return patch(url, DEFAULT_HEADERS, entity, DEFAULT_CONFIG); + return patch(url, defaultHeaders, entity, defaultConfig); } public static HttpResponse<String> patch(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { - return patch(url, headers, entity, DEFAULT_CONFIG); + return patch(url, headers, entity, defaultConfig); } - + public static HttpResponse<String> patch(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { - return patch(url, DEFAULT_HEADERS, entity, config); + return patch(url, defaultHeaders, entity, config); } public static HttpResponse<String> patch(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().patch(url, headers, entity, config); } - + /* * DELETE */ public static HttpResponse<String> delete(String url) throws HttpExecuteException { - return delete(url, DEFAULT_HEADERS, DEFAULT_CONFIG); + return delete(url, defaultHeaders, defaultConfig); } public static HttpResponse<String> delete(String url, Properties headers) throws HttpExecuteException { - return delete(url, headers, DEFAULT_CONFIG); + return delete(url, headers, defaultConfig); } - + public static HttpResponse<String> delete(String url, HttpClientConfig config) throws HttpExecuteException { - return delete(url, DEFAULT_HEADERS, config); + return delete(url, defaultHeaders, config); } public static HttpResponse<String> delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().delete(url, headers, config); } - + public static void destroy() { HttpRequestHandler.get().destroy(); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java index e4747f4308..73f0f15354 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,10 +38,10 @@ public class HttpRequestHandler { private static HttpRequestHandler handlerInstance = new HttpRequestHandler(); private static final String HTTPS_PREFIX = "https://"; private static final String HTTP_PREFIX = "http://"; - + private Map<HttpClientConfigImmutable, HttpClient> clients = new ConcurrentHashMap<>(); private HttpClientFactory clientFactory; - + private FunctionThrows<CloseableHttpResponse, HttpResponse<byte[]>, Exception> byteResponseBuilder = (CloseableHttpResponse httpResponse) -> { HttpEntity entity = httpResponse.getEntity(); byte[] response = null; @@ -51,8 +51,8 @@ public class HttpRequestHandler { response = IOUtils.toByteArray(content); } } - return new HttpResponse<>(response, - httpResponse.getStatusLine().getStatusCode(), + return new HttpResponse<>(response, + httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); }; @@ -62,7 +62,7 @@ public class HttpRequestHandler { if (entity != null) { response = EntityUtils.toString(entity); } - return new HttpResponse<>(response, + return new HttpResponse<>(response, httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); }; @@ -71,7 +71,7 @@ public class HttpRequestHandler { HttpConnectionMngFactory connectionMngFactory = new HttpConnectionMngFactory(); clientFactory = new HttpClientFactory(connectionMngFactory); } - + public static HttpRequestHandler get() { return handlerInstance; } @@ -81,7 +81,7 @@ public class HttpRequestHandler { return client.<String>get(url, headers, stringResponseBuilder); } - public HttpResponse<byte[]> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { + public HttpResponse<byte []> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { HttpClient client = getOrCreateClient(url, config); return client.<byte[]>get(url, headers, byteResponseBuilder); } @@ -102,15 +102,15 @@ public class HttpRequestHandler { } public HttpResponse<String> delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { - HttpClient client = getOrCreateClient(url, config != null ? config : HttpRequest.getDefaultConfig()); + HttpClient client = getOrCreateClient(url, config != null ? config : HttpRequest.defaultConfig); return client.<String>delete(url, headers, stringResponseBuilder); } - + public void destroy() { clients.forEach((k, v) -> v.close()); clients.clear(); } - + private HttpClient getOrCreateClient(String url, HttpClientConfig config) throws HttpExecuteException { String protocol = getProtocol(url); HttpClientConfigImmutable httpClientConfigImmutable = HttpClientConfigImmutable.getOrCreate(config); @@ -129,10 +129,12 @@ public class HttpRequestHandler { private String getProtocol(String url) throws HttpExecuteException { if (url.startsWith(HTTPS_PREFIX)) { return Constants.HTTPS; - } else if (url.startsWith(HTTP_PREFIX)) { + } + else if (url.startsWith(HTTP_PREFIX)) { return Constants.HTTP; - } else { - throw new HttpExecuteException(String.format("Failed to create http client. Requested protocol is not supported \"%s\"", url)); } + else { + throw new HttpExecuteException(String.format("Failed to create http client. Requested protocol is not supported \"%s\"", url)); + } } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java index b3a4a96b2f..c6061cf1c2 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ public class HttpResponse<T> { this.statusCode = statusCode; this.description = StringUtils.EMPTY; } - + public HttpResponse(T response, int statusCode, String description) { this.response = response; this.statusCode = statusCode; @@ -63,6 +63,6 @@ public class HttpResponse<T> { builder.append("]"); return builder.toString(); } - - + + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java index 88c4a4fe87..71f9ac2629 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,7 +24,7 @@ import org.apache.http.HttpStatus; public final class Responses { public static final HttpResponse<String> INTERNAL_SERVER_ERROR = new HttpResponse<>("Internal server error", HttpStatus.SC_INTERNAL_SERVER_ERROR); - + private Responses() { } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java index efac5c18ef..7b39e3f8c9 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java index f611ad6eba..bbcd815e75 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,15 +27,14 @@ import java.io.IOException; public class RetryHandlers { - private static final Logger LOGGER = Logger.getLogger(RetryHandlers.class.getName()); + private static final Logger logger = Logger.getLogger(RetryHandlers.class.getName()); - private RetryHandlers() { - } + private RetryHandlers(){} public static ComparableHttpRequestRetryHandler getDefault(int numOfRetries) { return (IOException exception, int executionCount, HttpContext context) -> { - LOGGER.debug("failed sending request with exception", exception); - LOGGER.debug("try request number: {}", executionCount); + logger.debug("failed sending request with exception", exception); + logger.debug("try request number: {}", executionCount); return executionCount <= numOfRetries; }; } |