2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 Nordix Foundation.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.clamp.controlloop.participant.dcae.httpclient;
23 import java.io.Closeable;
24 import java.io.IOException;
25 import javax.ws.rs.core.Response.Status;
26 import org.apache.http.HttpEntity;
27 import org.apache.http.HttpHost;
28 import org.apache.http.HttpRequest;
29 import org.apache.http.ParseException;
30 import org.apache.http.auth.AuthScope;
31 import org.apache.http.auth.UsernamePasswordCredentials;
32 import org.apache.http.client.AuthCache;
33 import org.apache.http.client.CredentialsProvider;
34 import org.apache.http.client.methods.CloseableHttpResponse;
35 import org.apache.http.client.methods.HttpGet;
36 import org.apache.http.client.methods.HttpPost;
37 import org.apache.http.client.methods.HttpPut;
38 import org.apache.http.client.protocol.HttpClientContext;
39 import org.apache.http.conn.ssl.NoopHostnameVerifier;
40 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
41 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
42 import org.apache.http.impl.auth.BasicScheme;
43 import org.apache.http.impl.client.BasicAuthCache;
44 import org.apache.http.impl.client.BasicCredentialsProvider;
45 import org.apache.http.impl.client.CloseableHttpClient;
46 import org.apache.http.impl.client.HttpClientBuilder;
47 import org.apache.http.impl.client.HttpClients;
48 import org.apache.http.ssl.SSLContextBuilder;
49 import org.apache.http.util.EntityUtils;
50 import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException;
51 import org.onap.policy.clamp.controlloop.participant.dcae.model.Loop;
52 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
53 import org.onap.policy.common.utils.coder.Coder;
54 import org.onap.policy.common.utils.coder.CoderException;
55 import org.onap.policy.common.utils.coder.StandardCoder;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 public abstract class AbstractHttpClient implements Closeable {
61 private static final Logger LOGGER = LoggerFactory.getLogger(AbstractHttpClient.class);
62 private final HttpClientContext localContext;
63 private final CloseableHttpClient httpclient;
64 private final HttpHost target;
65 public static final Coder CODER = new StandardCoder();
70 protected AbstractHttpClient(RestServerParameters restServerParameters) {
72 final String scheme = restServerParameters.isHttps() ? "https" : "http";
73 target = new HttpHost(restServerParameters.getHost(), restServerParameters.getPort(), scheme);
75 CredentialsProvider credsProvider = new BasicCredentialsProvider();
76 credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
77 new UsernamePasswordCredentials(restServerParameters.getUserName(),
78 restServerParameters.getPassword()));
80 AuthCache authCache = new BasicAuthCache();
81 BasicScheme basicAuth = new BasicScheme();
82 authCache.put(target, basicAuth);
83 localContext = HttpClientContext.create();
84 localContext.setAuthCache(authCache);
86 HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
87 if (restServerParameters.isHttps()) {
88 final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(new SSLContextBuilder()
89 .loadTrustMaterial(null, new TrustSelfSignedStrategy()).setProtocol("TLSv1.2").build(),
90 new NoopHostnameVerifier());
91 builder.setSSLSocketFactory(sslsf);
93 httpclient = builder.build();
95 } catch (final Exception e) {
96 throw new ControlLoopRuntimeException(Status.INTERNAL_SERVER_ERROR,
97 restServerParameters.getName() + " Client failed to start", e);
101 CloseableHttpResponse execute(HttpRequest request) throws IOException {
102 return httpclient.execute(target, request, localContext);
105 protected boolean executePut(String path, int statusCode) {
106 try (CloseableHttpResponse response = execute(new HttpPut(path))) {
107 return response.getStatusLine().getStatusCode() == statusCode;
108 } catch (Exception e) {
113 protected Loop executePost(String path, int statusCode) {
114 try (CloseableHttpResponse response = execute(new HttpPost(path))) {
115 if (response.getStatusLine().getStatusCode() != statusCode) {
118 return entityToMap(response.getEntity());
119 } catch (Exception e) {
124 protected Loop executeGet(String path, int statusCode) {
125 try (CloseableHttpResponse response = execute(new HttpGet(path))) {
126 if (response.getStatusLine().getStatusCode() != statusCode) {
129 return entityToMap(response.getEntity());
130 } catch (Exception e) {
135 private Loop entityToMap(HttpEntity httpEntity) {
136 if (httpEntity == null) {
140 return CODER.convert(EntityUtils.toString(httpEntity), Loop.class);
141 } catch (ParseException | IOException e) {
142 LOGGER.error("error reading Entity", e);
144 } catch (CoderException e) {
145 LOGGER.error("cannot convert to Loop Object", e);
151 public void close() throws IOException {