Remove outdated doc for A1 Adaptor
[integration.git] / test / mocks / masspnfsim / pnf-sim-lightweight / src / main / java / org / onap / pnfsimulator / simulator / client / RestTemplateAdapterImpl.java
1 /*
2  * ============LICENSE_START=======================================================
3  * PNF-REGISTRATION-HANDLER
4  * ================================================================================
5  * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.pnfsimulator.simulator.client;
22
23 import static org.onap.pnfsimulator.logging.MDCVariables.REQUEST_ID;
24 import static org.onap.pnfsimulator.logging.MDCVariables.X_INVOCATION_ID;
25 import static org.onap.pnfsimulator.logging.MDCVariables.X_ONAP_REQUEST_ID;
26 import static org.onap.pnfsimulator.logging.MDCVariables.AUTHORIZATION;
27
28 import org.springframework.web.client.ResourceAccessException;
29 import java.security.KeyManagementException;
30 import java.security.KeyStoreException;
31 import java.security.NoSuchAlgorithmException;
32 import java.security.cert.X509Certificate;
33 import javax.net.ssl.SSLContext;
34 import javax.net.ssl.TrustManager;
35 import javax.net.ssl.X509TrustManager;
36 import org.apache.http.conn.ssl.NoopHostnameVerifier;
37 import org.apache.http.impl.client.CloseableHttpClient;
38 import org.apache.http.impl.client.HttpClients;
39 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
40 import org.springframework.web.client.RestTemplate;
41
42 import org.springframework.http.HttpEntity;
43 import org.springframework.http.ResponseEntity;
44 import org.springframework.http.HttpHeaders;
45
46 import java.util.UUID;
47 import org.springframework.web.client.HttpClientErrorException;
48 import org.apache.http.client.config.RequestConfig;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.slf4j.MDC;
52 import org.slf4j.Marker;
53 import org.slf4j.MarkerFactory;
54
55 public class RestTemplateAdapterImpl implements RestTemplateAdapter {
56
57     private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateAdapterImpl.class);
58     private static final String CONTENT_TYPE = "Content-Type";
59     private static final String APPLICATION_JSON = "application/json";
60     private final Marker INVOKE = MarkerFactory.getMarker("INVOKE");
61     private static final RequestConfig CONFIG = RequestConfig.custom()
62         .setConnectTimeout(1000)
63         .setConnectionRequestTimeout(1000)
64         .setSocketTimeout(1000)
65         .build();
66
67     private RestTemplate restTemplate;
68
69     public RestTemplateAdapterImpl() {
70         try {
71         this.restTemplate = createRestTemplate();
72         } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException ex) {
73             LOGGER.warn("Error while creating a RestTemplate object: {}", ex.getMessage());
74         }
75     }
76
77     RestTemplateAdapterImpl(RestTemplate restTemplate) {
78         this.restTemplate = restTemplate;
79     }
80
81     @Override
82     public void send(String content, String url) {
83         try {
84             HttpEntity<String> entity = createPostEntity(content);
85             ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
86             LOGGER.info(INVOKE, "Message sent, ves response code: {}", response.getStatusCode());
87         } catch (HttpClientErrorException codeEx) {
88             LOGGER.warn("Response body: ", codeEx.getResponseBodyAsString());
89             LOGGER.warn("Error sending message to ves: {}", codeEx.getMessage());
90             LOGGER.warn("URL: {}", url);
91         } catch (ResourceAccessException ioEx) {
92             LOGGER.warn("The URL cannot be reached: {}", ioEx.getMessage());
93             LOGGER.warn("URL: {}", url);
94         }
95     }
96
97     private CloseableHttpClient createClient()
98     throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
99
100         TrustManager[] trustAllCerts = new TrustManager[] {
101             new X509TrustManager() {
102
103                 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
104                     return new X509Certificate[0];
105                 }
106
107                 public void checkClientTrusted(
108                     java.security.cert.X509Certificate[] certs,
109                     String authType) {}
110
111                 public void checkServerTrusted(
112                     java.security.cert.X509Certificate[] certs,
113                     String authType) {}
114             }
115         };
116
117         SSLContext sslContext = SSLContext.getInstance("TLS");
118         sslContext.init(
119             null,
120             trustAllCerts,
121             new java.security.SecureRandom()
122         );
123
124         CloseableHttpClient httpClient = HttpClients
125             .custom()
126             .setSSLContext(sslContext)
127             .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
128             .build();
129
130         return httpClient;
131     }
132
133     private RestTemplate createRestTemplate()
134     throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
135
136         CloseableHttpClient client = createClient();
137         HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
138         requestFactory.setHttpClient(client);
139
140         return new RestTemplate(requestFactory);
141
142     }
143
144     private HttpEntity createPostEntity(String content) {
145
146         HttpHeaders headers = new HttpHeaders();
147         headers.set(CONTENT_TYPE, APPLICATION_JSON);
148         headers.set(AUTHORIZATION, MDC.get(AUTHORIZATION));
149         headers.set(X_ONAP_REQUEST_ID, MDC.get(REQUEST_ID));
150         headers.set(X_INVOCATION_ID, UUID.randomUUID().toString());
151
152         return new HttpEntity<>(content, headers);
153
154     }
155 }