Revisions made to the Model Loader to use Babel
[aai/model-loader.git] / src / main / java / org / onap / aai / modelloader / restclient / BabelServiceClient.java
1 /**
2  * ============LICENSE_START==========================================
3  * org.onap.aai
4  * ===================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
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
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
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============================================
20  */
21 package org.onap.aai.modelloader.restclient;
22
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.FileInputStream;
31 import java.io.IOException;
32 import java.security.KeyManagementException;
33 import java.security.KeyStore;
34 import java.security.KeyStoreException;
35 import java.security.NoSuchAlgorithmException;
36 import java.security.UnrecoverableKeyException;
37 import java.security.cert.CertificateException;
38 import java.security.cert.X509Certificate;
39 import java.util.Base64;
40 import java.util.Collections;
41 import java.util.List;
42 import java.util.Objects;
43 import javax.net.ssl.HttpsURLConnection;
44 import javax.net.ssl.KeyManagerFactory;
45 import javax.net.ssl.SSLContext;
46 import javax.net.ssl.TrustManager;
47 import javax.net.ssl.X509TrustManager;
48 import javax.ws.rs.core.Response;
49 import org.json.JSONObject;
50 import org.onap.aai.babel.service.data.BabelArtifact;
51 import org.onap.aai.cl.api.Logger;
52 import org.onap.aai.cl.eelf.LoggerFactory;
53 import org.onap.aai.modelloader.config.ModelLoaderConfig;
54 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
55
56 /**
57  * Initial version for testing End to End scenarios
58  *
59  */
60 public class BabelServiceClient {
61
62     private static Logger logger = LoggerFactory.getInstance().getLogger(BabelServiceClient.class);
63
64     private static final String SSL_PROTOCOL = "TLS";
65     private static final String KEYSTORE_ALGORITHM = "SunX509";
66     private static final String KEYSTORE_TYPE = "PKCS12";
67
68     private ModelLoaderConfig config;
69     private Client client;
70
71     private TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
72         @Override
73         public X509Certificate[] getAcceptedIssuers() {
74             return null; // NOSONAR
75         }
76
77         @Override
78         public void checkClientTrusted(X509Certificate[] certs, String authType) {
79             // Do nothing
80         }
81
82         @Override
83         public void checkServerTrusted(X509Certificate[] certs, String authType) {
84             // Do nothing
85         }
86     }};
87
88     public class BabelServiceException extends Exception {
89
90         /**
91          * Babel Service error response
92          */
93         private static final long serialVersionUID = 1L;
94
95         public BabelServiceException(String message) {
96             super(message);
97         }
98
99     }
100
101     /**
102      * @param config
103      * @throws NoSuchAlgorithmException
104      * @throws KeyStoreException
105      * @throws CertificateException
106      * @throws IOException
107      * @throws UnrecoverableKeyException
108      * @throws KeyManagementException
109      */
110     public BabelServiceClient(ModelLoaderConfig config) throws NoSuchAlgorithmException, KeyStoreException,
111             CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
112         this.config = config;
113
114         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel Service client");
115
116         SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
117         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
118         KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
119
120         String clientCertPassword = config.getBabelKeyStorePassword();
121
122         char[] pwd = null;
123         if (clientCertPassword != null) {
124             pwd = clientCertPassword.toCharArray();
125         }
126
127         String clientCertFileName = config.getBabelKeyStorePath();
128         if (clientCertFileName != null) {
129             FileInputStream fin = new FileInputStream(clientCertFileName);
130             ks.load(fin, pwd);
131             kmf.init(ks, pwd);
132             ctx.init(kmf.getKeyManagers(), trustAllCerts, null);
133         } else {
134             ctx.init(null, trustAllCerts, null);
135         }
136
137         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Initialised context");
138
139         HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
140         HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true);
141
142         client = Client.create(new DefaultClientConfig());
143
144         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Jersey client created");
145     }
146
147     /**
148      * @param artifactPayload
149      * @param artifactName
150      * @param artifactVersion
151      * @param transactionId
152      * @return
153      * @throws BabelServiceException
154      */
155     public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
156             String transactionId) throws BabelServiceException {
157         Objects.requireNonNull(artifactPayload);
158
159         String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload);
160
161         JSONObject obj = new JSONObject();
162         obj.put("csar", encodedPayload);
163         obj.put("artifactVersion", artifactVersion);
164         obj.put("artifactName", artifactName);
165
166         logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName
167                 + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload);
168
169         WebResource webResource = client.resource(config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl());
170         ClientResponse response = webResource.type("application/json")
171                 .header(AaiRestClient.HEADER_TRANS_ID, Collections.singletonList(transactionId))
172                 .header(AaiRestClient.HEADER_FROM_APP_ID, Collections.singletonList(AaiRestClient.ML_APP_NAME))
173                 .post(ClientResponse.class, obj.toString());
174         String sanitizedJson = JsonSanitizer.sanitize(response.getEntity(String.class));
175
176         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Babel response " + response.getStatus() + " " + sanitizedJson);
177
178         if (response.getStatus() != Response.Status.OK.getStatusCode()) {
179             throw new BabelServiceException(sanitizedJson);
180         }
181
182         return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());
183     }
184 }