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