Remove commented methods/fields in APPC
[appc.git] / appc-dg / appc-dg-shared / appc-dg-mdsal-store / src / main / java / org / openecomp / appc / mdsal / operation / ConfigOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
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
22 package org.openecomp.appc.mdsal.operation;
23
24 import org.openecomp.appc.exceptions.APPCException;
25 import org.openecomp.appc.mdsal.impl.Constants;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.databind.JsonNode;
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import org.apache.commons.codec.binary.Base64;
31 import org.apache.http.HttpHeaders;
32 import org.apache.http.HttpResponse;
33 import org.apache.http.HttpVersion;
34 import org.apache.http.client.HttpClient;
35 import org.apache.http.client.methods.HttpPut;
36 import org.apache.http.conn.ClientConnectionManager;
37 import org.apache.http.conn.scheme.PlainSocketFactory;
38 import org.apache.http.conn.scheme.Scheme;
39 import org.apache.http.conn.scheme.SchemeRegistry;
40 import org.apache.http.conn.ssl.SSLSocketFactory;
41 import org.apache.http.entity.StringEntity;
42 import org.apache.http.impl.client.DefaultHttpClient;
43 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
44 import org.apache.http.params.BasicHttpParams;
45 import org.apache.http.params.HttpParams;
46 import org.apache.http.params.HttpProtocolParams;
47 import org.apache.http.protocol.HTTP;
48
49 import javax.net.ssl.SSLContext;
50 import javax.net.ssl.TrustManager;
51 import javax.net.ssl.X509TrustManager;
52 import java.io.IOException;
53 import java.io.UnsupportedEncodingException;
54 import java.net.MalformedURLException;
55 import java.net.Socket;
56 import java.net.URL;
57 import java.security.*;
58 import java.security.cert.CertificateException;
59 import java.security.cert.X509Certificate;
60 import java.util.ArrayList;
61 import java.util.Iterator;
62
63 import org.apache.commons.io.IOUtils;
64
65 /**
66  * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation.
67 */
68 public class ConfigOperation {
69     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class);
70
71     private static URL url;
72     private static String basicAuth;
73
74     ConfigOperation(){}
75
76     private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter();
77
78     private static ObjectMapper mapper = new ObjectMapper();
79
80     /**
81      * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input
82      * @param configJson - configuration JSON as String. This value will be stored in  MD-SAL store
83      * @param module - Module name that contains yang Schema
84      * @param containerName - yang container name which will be used as base container.
85      * @param subModules - Sub modules list if any. Order of sub module is top to bottom.
86      * @throws APPCException
87      */
88     public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException {
89         if (configJson == null) {
90             throw new APPCException("Provided message was null");
91         }
92         LOG.debug("Config JSON: " + configJson +"\n"
93                 +"module" + module +"\n"
94                 +"containerName" + containerName +"\n"
95                 +"subModules length : " + subModules.length );
96
97         int httpCode;
98         String respBody ;
99         try {
100             String path = requestFormatter.buildPath(url, module, containerName, subModules);
101             LOG.debug("Configuration Path : " + path);
102             URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
103             HttpResponse response = doPut(serviceUrl , configJson);
104             httpCode = response.getStatusLine().getStatusCode();
105             respBody = IOUtils.toString(response.getEntity().getContent());
106         } catch (IOException e) {
107             LOG.error("Error while storing configuration json "+e.getMessage(), e);
108             throw new APPCException(e);
109         }
110
111         if (httpCode != 200 ) {
112             try {
113                 ArrayList<String> errorMessage = new ArrayList<>();
114                 JsonNode responseJson = toJsonNodeFromJsonString(respBody);
115                 if(responseJson!=null && responseJson.get("errors")!=null) {
116                     JsonNode errors = responseJson.get("errors").get("error");
117                 for (Iterator<JsonNode> i = errors.elements();i.hasNext();){
118                     JsonNode error = i.next();
119                     errorMessage.add(error.get("error-message").textValue());
120                 }
121                 }
122                 throw new APPCException("Failed to load config JSON to MD SAL store. Error Message:" + errorMessage.toString());
123             } catch (Exception e) {
124                 LOG.error("Error while loading config JSON to MD SAL store. "+e.getMessage(), e);
125                 throw new APPCException("Error while loading config JSON to MD SAL store. "+ e.getMessage(),e);
126             }
127         }
128     }
129
130     /**
131      * This is Generic method that can be used to perform REST Put operation
132      * @param url - Destination URL for put
133      * @param body - payload for put action which will be sent as request body.
134      * @return - HttpResponse object which is returned from put REST call.
135      * @throws APPCException
136      */
137     public static HttpResponse doPut (URL url, String body) throws APPCException {
138         HttpPut put;
139         try {
140             put = new HttpPut(url.toExternalForm());
141             put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON);
142             put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON);
143
144             if (basicAuth != null) {
145                 put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
146             }
147
148             StringEntity entity = new StringEntity(body);
149             entity.setContentType(Constants.OPERATION_APPLICATION_JSON);
150             put.setEntity(new StringEntity(body));
151         } catch (UnsupportedEncodingException e) {
152             throw new APPCException(e);
153         }
154
155         HttpClient client = getHttpClient();
156
157         try {
158             return client.execute(put);
159         } catch (IOException e) {
160             throw new APPCException(e);
161         }
162
163     }
164
165     /**
166      * Updates the static var URL and returns the value;
167      *
168      * @return The new value of URL
169      */
170     public static String getUrl() {
171         return url.toExternalForm();
172     }
173
174     public static void setUrl(String newUrl) {
175         try {
176             url = new URL(newUrl);
177         } catch (MalformedURLException e) {
178             LOG.error("Malformed URL " +newUrl + e.getMessage(), e);
179         }
180     }
181
182     /**
183      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
184      * to null
185      *
186      * @param user     The user with optional domain name (for AAF)
187      * @param password The password for the user
188      * @return The new value of the basic auth string that will be used in the request headers
189      */
190     public static String setAuthentication(String user, String password) {
191         if (user != null && password != null) {
192             String authStr = user + ":" + password;
193             basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
194         } else {
195             basicAuth = null;
196         }
197         return basicAuth;
198     }
199
200     @SuppressWarnings("deprecation")
201     private static HttpClient getHttpClient() throws APPCException {
202         HttpClient client;
203         if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) {
204             try {
205                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
206                 trustStore.load(null, null);
207                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
208                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
209
210                 HttpParams params = new BasicHttpParams();
211                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
212                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
213
214                 SchemeRegistry registry = new SchemeRegistry();
215                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
216                 registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443));
217                 registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443));
218                 registry.register(new Scheme("http", sf, 8181));
219
220                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
221                 client = new DefaultHttpClient(ccm, params);
222             } catch (Exception e) {
223                 LOG.error("Error creating HTTP Client. Creating default client." ,  e);
224                 client = new DefaultHttpClient();
225             }
226         } else if ("http".equals(url.getProtocol())) {
227             client = new DefaultHttpClient();
228         } else {
229             throw new APPCException(
230                     "The provider.topology.url property is invalid. The url did not start with http[s]");
231         }
232         return client;
233     }
234
235     @SuppressWarnings("deprecation")
236     private static class MySSLSocketFactory extends SSLSocketFactory {
237         private SSLContext sslContext = SSLContext.getInstance("TLS");
238
239         private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
240                 KeyStoreException, UnrecoverableKeyException {
241             super(truststore);
242
243             TrustManager tm = new X509TrustManager() {
244                 @Override
245                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
246                     LOG.debug("Inside checkClientTrusted");
247                 }
248
249                 @Override
250                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
251                     LOG.debug("Inside checkServerTrusted");
252                 }
253
254                 @Override
255                 public X509Certificate[] getAcceptedIssuers() {
256                     return new X509Certificate[1];
257                 }
258             };
259
260             sslContext.init(null, new TrustManager[]{
261                     tm
262             }, null);
263         }
264
265         @Override
266         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
267                 throws IOException  {
268             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
269         }
270
271         @Override
272         public Socket createSocket() throws IOException {
273             return sslContext.getSocketFactory().createSocket();
274         }
275     }
276
277     private static JsonNode toJsonNodeFromJsonString(String jsonStr) {
278         JsonNode jsonNode = null;
279         if(jsonStr != null) {
280             try {
281                 jsonNode = mapper.readTree(jsonStr);
282             } catch (IOException e) {
283                 LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e);
284             }
285         }
286         return jsonNode;
287     }
288
289 }