2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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.openecomp.appc.mdsal.operation;
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;
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;
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;
63 import org.apache.commons.io.IOUtils;
66 * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation.
68 public class ConfigOperation {
69 private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class);
71 private static URL url;
72 private static String basicAuth;
76 private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter();
78 private static ObjectMapper mapper = new ObjectMapper();
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
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");
92 LOG.debug("Config JSON: " + configJson +"\n"
93 +"module" + module +"\n"
94 +"containerName" + containerName +"\n"
95 +"subModules length : " + subModules.length );
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);
111 if (httpCode != 200 ) {
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());
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);
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
137 public static HttpResponse doPut (URL url, String body) throws APPCException {
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);
144 if (basicAuth != null) {
145 put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
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);
155 HttpClient client = getHttpClient();
158 return client.execute(put);
159 } catch (IOException e) {
160 throw new APPCException(e);
166 * Updates the static var URL and returns the value;
168 * @return The new value of URL
170 public static String getUrl() {
171 return url.toExternalForm();
174 public static void setUrl(String newUrl) {
176 url = new URL(newUrl);
177 } catch (MalformedURLException e) {
178 LOG.error("Malformed URL " +newUrl + e.getMessage(), e);
183 * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
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
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()));
200 @SuppressWarnings("deprecation")
201 private static HttpClient getHttpClient() throws APPCException {
203 if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) {
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);
210 HttpParams params = new BasicHttpParams();
211 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
212 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
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));
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();
226 } else if ("http".equals(url.getProtocol())) {
227 client = new DefaultHttpClient();
229 throw new APPCException(
230 "The provider.topology.url property is invalid. The url did not start with http[s]");
235 @SuppressWarnings("deprecation")
236 private static class MySSLSocketFactory extends SSLSocketFactory {
237 private SSLContext sslContext = SSLContext.getInstance("TLS");
239 private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
240 KeyStoreException, UnrecoverableKeyException {
243 TrustManager tm = new X509TrustManager() {
245 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
246 LOG.debug("Inside checkClientTrusted");
250 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
251 LOG.debug("Inside checkServerTrusted");
255 public X509Certificate[] getAcceptedIssuers() {
256 return new X509Certificate[1];
260 sslContext.init(null, new TrustManager[]{
266 public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
268 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
272 public Socket createSocket() throws IOException {
273 return sslContext.getSocketFactory().createSocket();
277 private static JsonNode toJsonNodeFromJsonString(String jsonStr) {
278 JsonNode jsonNode = null;
279 if(jsonStr != null) {
281 jsonNode = mapper.readTree(jsonStr);
282 } catch (IOException e) {
283 LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e);