2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2019 European Software Marketing Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.aai.modelloader.restclient;
24 import com.google.gson.Gson;
25 import com.google.gson.reflect.TypeToken;
26 import com.google.json.JsonSanitizer;
27 import com.sun.jersey.api.client.Client; // NOSONAR
28 import com.sun.jersey.api.client.ClientResponse;
29 import com.sun.jersey.api.client.WebResource;
30 import com.sun.jersey.api.client.config.DefaultClientConfig;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.security.KeyManagementException;
36 import java.security.KeyStore;
37 import java.security.KeyStoreException;
38 import java.security.NoSuchAlgorithmException;
39 import java.security.UnrecoverableKeyException;
40 import java.security.cert.CertificateException;
41 import java.security.cert.X509Certificate;
42 import java.time.ZonedDateTime;
43 import java.time.format.DateTimeFormatter;
44 import java.util.Base64;
45 import java.util.Collections;
46 import java.util.List;
47 import java.util.Objects;
48 import javax.net.ssl.HttpsURLConnection;
49 import javax.net.ssl.KeyManagerFactory;
50 import javax.net.ssl.SSLContext;
51 import javax.net.ssl.TrustManager;
52 import javax.net.ssl.TrustManagerFactory;
53 import javax.net.ssl.X509TrustManager;
54 import javax.ws.rs.core.Response;
55 import org.json.JSONException;
56 import org.json.JSONObject;
57 import org.onap.aai.babel.service.data.BabelArtifact;
58 import org.onap.aai.cl.api.LogFields;
59 import org.onap.aai.cl.api.LogLine;
60 import org.onap.aai.cl.api.Logger;
61 import org.onap.aai.cl.eelf.LoggerFactory;
62 import org.onap.aai.cl.mdc.MdcContext;
63 import org.onap.aai.cl.mdc.MdcOverride;
64 import org.onap.aai.modelloader.config.ModelLoaderConfig;
65 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
68 * HTTPS Client for interfacing with Babel.
71 public class HttpsBabelServiceClient implements BabelServiceClient {
73 private static final Logger logger = LoggerFactory.getInstance().getLogger(HttpsBabelServiceClient.class);
74 private static final Logger metricsLogger =
75 LoggerFactory.getInstance().getMetricsLogger(HttpsBabelServiceClient.class);
76 private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
78 private static final String SSL_PROTOCOL = "TLS";
79 private static final String KEYSTORE_ALGORITHM = "SunX509";
80 private static final String KEYSTORE_TYPE = "PKCS12";
82 private final ModelLoaderConfig config;
83 private final Client client;
87 * @throws NoSuchAlgorithmException
88 * @throws KeyStoreException
89 * @throws CertificateException
91 * @throws UnrecoverableKeyException
92 * @throws KeyManagementException
93 * @throws BabelServiceClientException
95 public HttpsBabelServiceClient(ModelLoaderConfig config)
96 throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
97 UnrecoverableKeyException, KeyManagementException, BabelServiceClientException {
100 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel Service client");
102 SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
103 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
104 KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
106 String clientCertPassword = config.getBabelKeyStorePassword();
109 if (clientCertPassword != null) {
110 pwd = clientCertPassword.toCharArray();
113 TrustManager[] trustManagers = getTrustManagers();
115 String clientCertFileName = config.getBabelKeyStorePath();
116 if (clientCertFileName == null) {
117 ctx.init(null, trustManagers, null);
119 InputStream fin = Files.newInputStream(Paths.get(clientCertFileName));
120 keyStore.load(fin, pwd);
121 kmf.init(keyStore, pwd);
122 ctx.init(kmf.getKeyManagers(), trustManagers, null);
125 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Initialised context");
127 HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
128 HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true);
130 client = Client.create(new DefaultClientConfig());
132 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Jersey client created");
135 private TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
136 IOException, BabelServiceClientException {
137 TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
138 // Using null here initializes the TMF with the default trust store.
139 tmf.init((KeyStore) null);
141 // Create a new Trust Manager from the local trust store.
142 String trustStoreFile = config.getBabelTrustStorePath();
143 if (trustStoreFile == null) {
144 throw new BabelServiceClientException("No Babel trust store defined");
146 try (InputStream myKeys = Files.newInputStream(Paths.get(trustStoreFile))) {
147 KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
148 myTrustStore.load(myKeys, config.getBabelTrustStorePassword().toCharArray());
149 tmf.init(myTrustStore);
151 X509TrustManager localTm = findX509TrustManager(tmf);
153 // Create a custom trust manager that wraps both our trust store and the default.
154 final X509TrustManager finalLocalTm = localTm;
156 // Find the default trust manager.
157 final X509TrustManager defaultTrustManager = findX509TrustManager(tmf);
159 return new TrustManager[] {new X509TrustManager() {
161 public X509Certificate[] getAcceptedIssuers() {
162 return defaultTrustManager.getAcceptedIssuers();
166 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
168 finalLocalTm.checkServerTrusted(chain, authType);
169 } catch (CertificateException e) { // NOSONAR
170 defaultTrustManager.checkServerTrusted(chain, authType);
175 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
176 defaultTrustManager.checkClientTrusted(chain, authType);
181 private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
182 X509TrustManager trustManager = null;
183 for (TrustManager tm : tmf.getTrustManagers()) {
184 if (tm instanceof X509TrustManager) {
185 trustManager = (X509TrustManager) tm;
193 * @param artifactPayload
194 * @param artifactName
195 * @param artifactVersion
196 * @param transactionId
198 * @throws BabelServiceClientException
199 * @throws JSONException
202 public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
203 String transactionId) throws BabelServiceClientException {
204 Objects.requireNonNull(artifactPayload);
206 String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload);
208 JSONObject obj = new JSONObject();
210 obj.put("csar", encodedPayload);
211 obj.put("artifactVersion", artifactVersion);
212 obj.put("artifactName", artifactName);
213 } catch (JSONException ex) {
214 throw new BabelServiceClientException(ex);
217 if (logger.isInfoEnabled()) {
218 logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName
219 + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload);
222 MdcOverride override = new MdcOverride();
223 override.addAttribute(MdcContext.MDC_START_TIME, ZonedDateTime.now().format(formatter));
225 WebResource webResource = client.resource(config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl());
226 ClientResponse response = webResource.type("application/json")
227 .header(AaiRestClient.HEADER_TRANS_ID, Collections.singletonList(transactionId))
228 .header(AaiRestClient.HEADER_FROM_APP_ID, Collections.singletonList(AaiRestClient.ML_APP_NAME))
229 .post(ClientResponse.class, obj.toString());
230 String sanitizedJson = JsonSanitizer.sanitize(response.getEntity(String.class));
232 if (logger.isDebugEnabled()) {
233 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
234 "Babel response " + response.getStatus() + " " + sanitizedJson);
237 metricsLogger.info(ModelLoaderMsgs.BABEL_REST_REQUEST, new LogFields() //
238 .setField(LogLine.DefinedFields.TARGET_ENTITY, "Babel")
239 .setField(LogLine.DefinedFields.STATUS_CODE,
240 Response.Status.fromStatusCode(response.getStatus()).getFamily()
241 .equals(Response.Status.Family.SUCCESSFUL) ? "COMPLETE" : "ERROR")
242 .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
243 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusInfo().toString()), //
244 override, response.toString());
246 if (response.getStatus() != Response.Status.OK.getStatusCode()) {
247 throw new BabelServiceClientException(sanitizedJson);
250 return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());