b2d0b61d07bdeca68803b5b857c140237c9aa311
[policy/clamp.git] /
1 /*-
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
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.controlloop.participant.dcae.httpclient;
22
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;
58
59 public abstract class AbstractHttpClient implements Closeable {
60
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();
66
67     /**
68      * Constructor.
69      */
70     protected AbstractHttpClient(RestServerParameters restServerParameters) {
71         try {
72             final String scheme = restServerParameters.isHttps() ? "https" : "http";
73             target = new HttpHost(restServerParameters.getHost(), restServerParameters.getPort(), scheme);
74
75             CredentialsProvider credsProvider = new BasicCredentialsProvider();
76             credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
77                     new UsernamePasswordCredentials(restServerParameters.getUserName(),
78                             restServerParameters.getPassword()));
79
80             AuthCache authCache = new BasicAuthCache();
81             BasicScheme basicAuth = new BasicScheme();
82             authCache.put(target, basicAuth);
83             localContext = HttpClientContext.create();
84             localContext.setAuthCache(authCache);
85
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);
92             }
93             httpclient = builder.build();
94
95         } catch (final Exception e) {
96             throw new ControlLoopRuntimeException(Status.INTERNAL_SERVER_ERROR,
97                     restServerParameters.getName() + " Client failed to start", e);
98         }
99     }
100
101     CloseableHttpResponse execute(HttpRequest request) throws IOException {
102         return httpclient.execute(target, request, localContext);
103     }
104
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) {
109             return false;
110         }
111     }
112
113     protected Loop executePost(String path, int statusCode) {
114         try (CloseableHttpResponse response = execute(new HttpPost(path))) {
115             if (response.getStatusLine().getStatusCode() != statusCode) {
116                 return null;
117             }
118             return entityToMap(response.getEntity());
119         } catch (Exception e) {
120             return null;
121         }
122     }
123
124     protected Loop executeGet(String path, int statusCode) {
125         try (CloseableHttpResponse response = execute(new HttpGet(path))) {
126             if (response.getStatusLine().getStatusCode() != statusCode) {
127                 return null;
128             }
129             return entityToMap(response.getEntity());
130         } catch (Exception e) {
131             return null;
132         }
133     }
134
135     private Loop entityToMap(HttpEntity httpEntity) {
136         if (httpEntity == null) {
137             return new Loop();
138         }
139         try {
140             return CODER.convert(EntityUtils.toString(httpEntity), Loop.class);
141         } catch (ParseException | IOException e) {
142             LOGGER.error("error reading Entity", e);
143             return new Loop();
144         } catch (CoderException e) {
145             LOGGER.error("cannot convert to Loop Object", e);
146             return new Loop();
147         }
148     }
149
150     @Override
151     public void close() throws IOException {
152         httpclient.close();
153     }
154 }