2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.openecomp.appc.mdsal.operation;
27 import org.openecomp.appc.exceptions.APPCException;
28 import org.openecomp.appc.mdsal.impl.Constants;
29 import com.att.eelf.configuration.EELFLogger;
30 import com.att.eelf.configuration.EELFManager;
31 import com.fasterxml.jackson.databind.JsonNode;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import org.apache.commons.codec.binary.Base64;
34 import org.apache.http.HttpHeaders;
35 import org.apache.http.HttpResponse;
36 import org.apache.http.HttpVersion;
37 import org.apache.http.client.HttpClient;
38 import org.apache.http.client.methods.HttpPut;
39 import org.apache.http.conn.ClientConnectionManager;
40 import org.apache.http.conn.scheme.PlainSocketFactory;
41 import org.apache.http.conn.scheme.Scheme;
42 import org.apache.http.conn.scheme.SchemeRegistry;
43 import org.apache.http.conn.ssl.SSLSocketFactory;
44 import org.apache.http.entity.StringEntity;
45 import org.apache.http.impl.client.DefaultHttpClient;
46 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
47 import org.apache.http.params.BasicHttpParams;
48 import org.apache.http.params.HttpParams;
49 import org.apache.http.params.HttpProtocolParams;
50 import org.apache.http.protocol.HTTP;
52 import javax.net.ssl.SSLContext;
53 import javax.net.ssl.TrustManager;
54 import javax.net.ssl.X509TrustManager;
55 import java.io.IOException;
56 import java.io.UnsupportedEncodingException;
57 import java.net.MalformedURLException;
58 import java.net.Socket;
60 import java.security.*;
61 import java.security.cert.CertificateException;
62 import java.security.cert.X509Certificate;
63 import java.util.ArrayList;
64 import java.util.Iterator;
66 import org.apache.commons.io.IOUtils;
69 * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation.
71 public class ConfigOperation {
72 private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class);
74 private static URL url;
75 private static String basicAuth;
79 private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter();
81 private static ObjectMapper mapper = new ObjectMapper();
84 * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input
85 * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store
86 * @param module - Module name that contains yang Schema
87 * @param containerName - yang container name which will be used as base container.
88 * @param subModules - Sub modules list if any. Order of sub module is top to bottom.
89 * @throws APPCException
91 public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException {
92 if (configJson == null) {
93 throw new APPCException("Provided message was null");
95 LOG.debug("Config JSON: " + configJson +"\n"
96 +"module" + module +"\n"
97 +"containerName" + containerName +"\n"
98 +"subModules length : " + subModules.length );
103 String path = requestFormatter.buildPath(url, module, containerName, subModules);
104 LOG.debug("Configuration Path : " + path);
105 URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
106 HttpResponse response = doPut(serviceUrl , configJson);
107 httpCode = response.getStatusLine().getStatusCode();
108 respBody = IOUtils.toString(response.getEntity().getContent());
109 } catch (IOException e) {
110 LOG.error("Error while storing configuration json "+e.getMessage(), e);
111 throw new APPCException(e);
114 if (httpCode != 200 ) {
116 ArrayList<String> errorMessage = new ArrayList<>();
117 JsonNode responseJson = toJsonNodeFromJsonString(respBody);
118 if(responseJson!=null && responseJson.get("errors")!=null) {
119 JsonNode errors = responseJson.get("errors").get("error");
120 for (Iterator<JsonNode> i = errors.elements();i.hasNext();){
121 JsonNode error = i.next();
122 errorMessage.add(error.get("error-message").textValue());
125 throw new APPCException("Failed to load config JSON to MD SAL store. Error Message:" + errorMessage.toString());
126 } catch (Exception e) {
127 LOG.error("Error while loading config JSON to MD SAL store. "+e.getMessage(), e);
128 throw new APPCException("Error while loading config JSON to MD SAL store. "+ e.getMessage(),e);
134 * This is Generic method that can be used to perform REST Put operation
135 * @param url - Destination URL for put
136 * @param body - payload for put action which will be sent as request body.
137 * @return - HttpResponse object which is returned from put REST call.
138 * @throws APPCException
140 public static HttpResponse doPut (URL url, String body) throws APPCException {
143 put = new HttpPut(url.toExternalForm());
144 put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON);
145 put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON);
147 if (basicAuth != null) {
148 put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
151 StringEntity entity = new StringEntity(body);
152 entity.setContentType(Constants.OPERATION_APPLICATION_JSON);
153 put.setEntity(new StringEntity(body));
154 } catch (UnsupportedEncodingException e) {
155 throw new APPCException(e);
158 HttpClient client = getHttpClient();
161 return client.execute(put);
162 } catch (IOException e) {
163 throw new APPCException(e);
169 * Updates the static var URL and returns the value;
171 * @return The new value of URL
173 public static String getUrl() {
174 return url.toExternalForm();
177 public static void setUrl(String newUrl) {
179 url = new URL(newUrl);
180 } catch (MalformedURLException e) {
181 LOG.error("Malformed URL " +newUrl + e.getMessage(), e);
186 * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
189 * @param user The user with optional domain name (for AAF)
190 * @param password The password for the user
191 * @return The new value of the basic auth string that will be used in the request headers
193 public static String setAuthentication(String user, String password) {
194 if (user != null && password != null) {
195 String authStr = user + ":" + password;
196 basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
203 @SuppressWarnings("deprecation")
204 private static HttpClient getHttpClient() throws APPCException {
206 if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) {
208 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
209 trustStore.load(null, null);
210 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
211 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
213 HttpParams params = new BasicHttpParams();
214 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
215 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
217 SchemeRegistry registry = new SchemeRegistry();
218 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
219 registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443));
220 registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443));
221 registry.register(new Scheme("http", sf, 8181));
223 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
224 client = new DefaultHttpClient(ccm, params);
225 } catch (Exception e) {
226 LOG.error("Error creating HTTP Client. Creating default client." , e);
227 client = new DefaultHttpClient();
229 } else if ("http".equals(url.getProtocol())) {
230 client = new DefaultHttpClient();
232 throw new APPCException(
233 "The provider.topology.url property is invalid. The url did not start with http[s]");
238 @SuppressWarnings("deprecation")
239 private static class MySSLSocketFactory extends SSLSocketFactory {
240 private SSLContext sslContext = SSLContext.getInstance("TLS");
242 private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
243 KeyStoreException, UnrecoverableKeyException {
246 TrustManager tm = new X509TrustManager() {
248 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
249 LOG.debug("Inside checkClientTrusted");
253 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
254 LOG.debug("Inside checkServerTrusted");
258 public X509Certificate[] getAcceptedIssuers() {
259 return new X509Certificate[1];
263 sslContext.init(null, new TrustManager[]{
269 public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
271 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
275 public Socket createSocket() throws IOException {
276 return sslContext.getSocketFactory().createSocket();
280 private static JsonNode toJsonNodeFromJsonString(String jsonStr) {
281 JsonNode jsonNode = null;
282 if(jsonStr != null) {
284 jsonNode = mapper.readTree(jsonStr);
285 } catch (IOException e) {
286 LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e);