2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 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=========================================================
21 package org.onap.aai.modelloader.restclient;
23 import com.google.gson.Gson;
24 import com.google.gson.reflect.TypeToken;
25 import com.google.json.JsonSanitizer;
26 import com.sun.jersey.api.client.Client; // NOSONAR
27 import com.sun.jersey.api.client.ClientResponse;
28 import com.sun.jersey.api.client.WebResource;
29 import com.sun.jersey.api.client.config.DefaultClientConfig;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.nio.file.Files;
33 import java.nio.file.Paths;
34 import java.security.KeyManagementException;
35 import java.security.KeyStore;
36 import java.security.KeyStoreException;
37 import java.security.NoSuchAlgorithmException;
38 import java.security.UnrecoverableKeyException;
39 import java.security.cert.CertificateException;
40 import java.security.cert.X509Certificate;
41 import java.util.Base64;
42 import java.util.Collections;
43 import java.util.List;
44 import java.util.Objects;
45 import javax.net.ssl.HttpsURLConnection;
46 import javax.net.ssl.KeyManagerFactory;
47 import javax.net.ssl.SSLContext;
48 import javax.net.ssl.TrustManager;
49 import javax.net.ssl.TrustManagerFactory;
50 import javax.net.ssl.X509TrustManager;
51 import javax.ws.rs.core.Response;
52 import org.json.JSONException;
53 import org.json.JSONObject;
54 import org.onap.aai.babel.service.data.BabelArtifact;
55 import org.onap.aai.cl.api.Logger;
56 import org.onap.aai.cl.eelf.LoggerFactory;
57 import org.onap.aai.modelloader.config.ModelLoaderConfig;
58 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
61 * HTTPS Client for interfacing with Babel.
64 public class HttpsBabelServiceClient implements BabelServiceClient {
66 private static final Logger logger = LoggerFactory.getInstance().getLogger(HttpsBabelServiceClient.class);
68 private static final String SSL_PROTOCOL = "TLS";
69 private static final String KEYSTORE_ALGORITHM = "SunX509";
70 private static final String KEYSTORE_TYPE = "PKCS12";
72 private final ModelLoaderConfig config;
73 private final Client client;
77 * @throws NoSuchAlgorithmException
78 * @throws KeyStoreException
79 * @throws CertificateException
81 * @throws UnrecoverableKeyException
82 * @throws KeyManagementException
83 * @throws BabelServiceClientException
85 public HttpsBabelServiceClient(ModelLoaderConfig config)
86 throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
87 UnrecoverableKeyException, KeyManagementException, BabelServiceClientException {
90 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel Service client");
92 SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
93 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
94 KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
96 String clientCertPassword = config.getBabelKeyStorePassword();
99 if (clientCertPassword != null) {
100 pwd = clientCertPassword.toCharArray();
103 TrustManager[] trustManagers = getTrustManagers();
105 String clientCertFileName = config.getBabelKeyStorePath();
106 if (clientCertFileName == null) {
107 ctx.init(null, trustManagers, null);
109 InputStream fin = Files.newInputStream(Paths.get(clientCertFileName));
110 keyStore.load(fin, pwd);
111 kmf.init(keyStore, pwd);
112 ctx.init(kmf.getKeyManagers(), trustManagers, null);
115 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Initialised context");
117 HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
118 HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true);
120 client = Client.create(new DefaultClientConfig());
122 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Jersey client created");
125 private TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
126 IOException, BabelServiceClientException {
127 TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
128 // Using null here initializes the TMF with the default trust store.
129 tmf.init((KeyStore) null);
131 // Create a new Trust Manager from the local trust store.
132 String trustStoreFile = config.getBabelTrustStorePath();
133 if (trustStoreFile == null) {
134 throw new BabelServiceClientException("No Babel trust store defined");
136 try (InputStream myKeys = Files.newInputStream(Paths.get(trustStoreFile))) {
137 KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
138 myTrustStore.load(myKeys, config.getBabelTrustStorePassword().toCharArray());
139 tmf.init(myTrustStore);
141 X509TrustManager localTm = findX509TrustManager(tmf);
143 // Create a custom trust manager that wraps both our trust store and the default.
144 final X509TrustManager finalLocalTm = localTm;
146 // Find the default trust manager.
147 final X509TrustManager defaultTrustManager = findX509TrustManager(tmf);
149 return new TrustManager[] {new X509TrustManager() {
151 public X509Certificate[] getAcceptedIssuers() {
152 return defaultTrustManager.getAcceptedIssuers();
156 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
158 finalLocalTm.checkServerTrusted(chain, authType);
159 } catch (CertificateException e) {
160 defaultTrustManager.checkServerTrusted(chain, authType);
165 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
166 defaultTrustManager.checkClientTrusted(chain, authType);
171 private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
172 X509TrustManager trustManager = null;
173 for (TrustManager tm : tmf.getTrustManagers()) {
174 if (tm instanceof X509TrustManager) {
175 trustManager = (X509TrustManager) tm;
183 * @param artifactPayload
184 * @param artifactName
185 * @param artifactVersion
186 * @param transactionId
188 * @throws BabelServiceClientException
189 * @throws JSONException
192 public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
193 String transactionId) throws BabelServiceClientException {
194 Objects.requireNonNull(artifactPayload);
196 String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload);
198 JSONObject obj = new JSONObject();
200 obj.put("csar", encodedPayload);
201 obj.put("artifactVersion", artifactVersion);
202 obj.put("artifactName", artifactName);
203 } catch (JSONException ex) {
204 throw new BabelServiceClientException(ex);
207 if (logger.isInfoEnabled()) {
208 logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName
209 + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload);
212 WebResource webResource = client.resource(config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl());
213 ClientResponse response = webResource.type("application/json")
214 .header(AaiRestClient.HEADER_TRANS_ID, Collections.singletonList(transactionId))
215 .header(AaiRestClient.HEADER_FROM_APP_ID, Collections.singletonList(AaiRestClient.ML_APP_NAME))
216 .post(ClientResponse.class, obj.toString());
217 String sanitizedJson = JsonSanitizer.sanitize(response.getEntity(String.class));
219 if (logger.isDebugEnabled()) {
220 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
221 "Babel response " + response.getStatus() + " " + sanitizedJson);
224 if (response.getStatus() != Response.Status.OK.getStatusCode()) {
225 throw new BabelServiceClientException(sanitizedJson);
228 return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());