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 || httpCode >= 300 ) {
116 LOG.debug("Config operation Error response code: " + httpCode);
117 ArrayList<String> errorMessage = new ArrayList<>();
118 JsonNode responseJson = toJsonNodeFromJsonString(respBody);
119 if(responseJson!=null && responseJson.get("errors")!=null) {
120 JsonNode errors = responseJson.get("errors").get("error");
121 for (Iterator<JsonNode> i = errors.elements();i.hasNext();){
122 JsonNode error = i.next();
123 errorMessage.add(error.get("error-message").textValue());
126 throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString());
127 } catch (Exception e) {
128 LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e);
129 throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e);
132 LOG.debug("Config operation successful. Response code: " + httpCode);
137 * This is Generic method that can be used to perform REST Put operation
138 * @param url - Destination URL for put
139 * @param body - payload for put action which will be sent as request body.
140 * @return - HttpResponse object which is returned from put REST call.
141 * @throws APPCException
143 public static HttpResponse doPut (URL url, String body) throws APPCException {
146 put = new HttpPut(url.toExternalForm());
147 put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON);
148 put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON);
150 if (basicAuth != null) {
151 put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
154 StringEntity entity = new StringEntity(body);
155 entity.setContentType(Constants.OPERATION_APPLICATION_JSON);
156 put.setEntity(new StringEntity(body));
157 } catch (UnsupportedEncodingException e) {
158 throw new APPCException(e);
161 HttpClient client = getHttpClient();
164 return client.execute(put);
165 } catch (IOException e) {
166 throw new APPCException(e);
172 * Updates the static var URL and returns the value;
174 * @return The new value of URL
176 public static String getUrl() {
177 return url.toExternalForm();
180 public static void setUrl(String newUrl) {
182 url = new URL(newUrl);
183 } catch (MalformedURLException e) {
184 LOG.error("Malformed URL " +newUrl + e.getMessage(), e);
189 * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
192 * @param user The user with optional domain name (for AAF)
193 * @param password The password for the user
194 * @return The new value of the basic auth string that will be used in the request headers
196 public static String setAuthentication(String user, String password) {
197 if (user != null && password != null) {
198 String authStr = user + ":" + password;
199 basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
206 @SuppressWarnings("deprecation")
207 private static HttpClient getHttpClient() throws APPCException {
209 if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) {
211 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
212 trustStore.load(null, null);
213 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
214 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
216 HttpParams params = new BasicHttpParams();
217 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
218 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
220 SchemeRegistry registry = new SchemeRegistry();
221 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
222 registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443));
223 registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443));
224 registry.register(new Scheme("http", sf, 8181));
226 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
227 client = new DefaultHttpClient(ccm, params);
228 } catch (Exception e) {
229 LOG.error("Error creating HTTP Client. Creating default client." , e);
230 client = new DefaultHttpClient();
232 } else if ("http".equals(url.getProtocol())) {
233 client = new DefaultHttpClient();
235 throw new APPCException(
236 "The provider.topology.url property is invalid. The url did not start with http[s]");
241 @SuppressWarnings("deprecation")
242 private static class MySSLSocketFactory extends SSLSocketFactory {
243 private SSLContext sslContext = SSLContext.getInstance("TLS");
245 private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
246 KeyStoreException, UnrecoverableKeyException {
249 TrustManager tm = new X509TrustManager() {
251 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
252 LOG.debug("Inside checkClientTrusted");
256 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
257 LOG.debug("Inside checkServerTrusted");
261 public X509Certificate[] getAcceptedIssuers() {
262 return new X509Certificate[1];
266 sslContext.init(null, new TrustManager[]{
272 public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
274 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
278 public Socket createSocket() throws IOException {
279 return sslContext.getSocketFactory().createSocket();
283 private static JsonNode toJsonNodeFromJsonString(String jsonStr) {
284 JsonNode jsonNode = null;
285 if(jsonStr != null) {
287 jsonNode = mapper.readTree(jsonStr);
288 } catch (IOException e) {
289 LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e);