* ============LICENSE_END=========================================================
*/
-package org.openecomp.appc.listener.CL.impl;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.Socket;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
+package org.openecomp.appc.mdsal.operation;
+import org.openecomp.appc.exceptions.APPCException;
+import org.openecomp.appc.mdsal.impl.Constants;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
-import org.json.JSONObject;
-import org.openecomp.appc.exceptions.APPCException;
-import org.openecomp.appc.listener.CL.model.IncomingMessage;
-import org.openecomp.appc.listener.util.Mapper;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.Socket;
+import java.net.URL;
+import java.security.*;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Iterator;
-public class ProviderOperations {
+import org.apache.commons.io.IOUtils;
- private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
+/**
+ * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation.
+*/
+public class ConfigOperation {
+ private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class);
private static URL url;
+ private static String basicAuth;
+
+ ConfigOperation(){}
- private static String basic_auth;
+ private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter();
- //@formatter:off
- @SuppressWarnings("nls")
- private final static String TEMPLATE = "{\"input\": {\"common-request-header\": {\"service-request-id\": \"%s\"},\"vnf-resource\": {\"vm-id\": \"%s\"%s}}}";
- //@formatter:on
+ private static ObjectMapper mapper = new ObjectMapper();
/**
- * Calls the AppcProvider to run a topology directed graph
- *
- * @param msg
- * The incoming message to be run
- * @return True if the result is success. Never returns false and throws an exception instead.
- * @throws UnsupportedEncodingException
- * @throws Exception
- * if there was a failure processing the request. The exception message is the failure reason.
+ * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input
+ * @param configJson - configuration JSON as String. This value will be stored in MD-SAL store
+ * @param module - Module name that contains yang Schema
+ * @param containerName - yang container name which will be used as base container.
+ * @param subModules - Sub modules list if any. Order of sub module is top to bottom.
+ * @throws APPCException
*/
- @SuppressWarnings("nls")
- public static boolean topologyDG(IncomingMessage msg) throws APPCException {
- if (msg == null) {
+ public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException {
+ if (configJson == null) {
throw new APPCException("Provided message was null");
}
+ LOG.debug("Config JSON: " + configJson +"\n"
+ +"module" + module +"\n"
+ +"containerName" + containerName +"\n"
+ +"subModules length : " + subModules.length );
- HttpPost post = null;
+ int httpCode;
+ String respBody ;
try {
- // Concatenate the "action" on the end of the URL
- String path = url.getPath() + ":" + msg.getAction().getValue().toLowerCase();
+ String path = requestFormatter.buildPath(url, module, containerName, subModules);
+ LOG.debug("Configuration Path : " + path);
URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
+ HttpResponse response = doPut(serviceUrl , configJson);
+ httpCode = response.getStatusLine().getStatusCode();
+ respBody = IOUtils.toString(response.getEntity().getContent());
+ } catch (IOException e) {
+ LOG.error("Error while storing configuration json "+e.getMessage(), e);
+ throw new APPCException(e);
+ }
- post = new HttpPost(serviceUrl.toExternalForm());
- post.setHeader("Content-Type", "application/json");
- post.setHeader("Accept", "application/json");
-
- // Set Auth
- if (basic_auth != null) {
- post.setHeader("Authorization", "Basic " + basic_auth);
+ if (httpCode != 200 ) {
+ try {
+ ArrayList<String> errorMessage = new ArrayList<>();
+ JsonNode responseJson = toJsonNodeFromJsonString(respBody);
+ if(responseJson!=null && responseJson.get("errors")!=null) {
+ JsonNode errors = responseJson.get("errors").get("error");
+ for (Iterator<JsonNode> i = errors.elements();i.hasNext();){
+ JsonNode error = i.next();
+ errorMessage.add(error.get("error-message").textValue());
+ }
+ }
+ throw new APPCException("Failed to load config JSON to MD SAL store. Error Message:" + errorMessage.toString());
+ } catch (Exception e) {
+ LOG.error("Error while loading config JSON to MD SAL store. "+e.getMessage(), e);
+ throw new APPCException("Error while loading config JSON to MD SAL store. "+ e.getMessage(),e);
}
+ }
+ }
- String body = buildReqest(msg.getId(), msg.getUrl(), msg.getIdentityUrl());
-
+ /**
+ * This is Generic method that can be used to perform REST Put operation
+ * @param url - Destination URL for put
+ * @param body - payload for put action which will be sent as request body.
+ * @return - HttpResponse object which is returned from put REST call.
+ * @throws APPCException
+ */
+ public static HttpResponse doPut (URL url, String body) throws APPCException {
+ HttpPut put;
+ try {
+ put = new HttpPut(url.toExternalForm());
+ put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON);
+ put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON);
- LOG.info(String.format("DMaaP ACTION PATH : %s", path));
- LOG.info(String.format("DMaaP ACTION BODY : %s", body));
+ if (basicAuth != null) {
+ put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
+ }
StringEntity entity = new StringEntity(body);
- entity.setContentType("application/json");
- post.setEntity(new StringEntity(body));
- } catch (UnsupportedEncodingException | MalformedURLException e) {
+ entity.setContentType(Constants.OPERATION_APPLICATION_JSON);
+ put.setEntity(new StringEntity(body));
+ } catch (UnsupportedEncodingException e) {
throw new APPCException(e);
}
HttpClient client = getHttpClient();
- int httpCode = 0;
- String respBody = null;
try {
- HttpResponse response = client.execute(post);
- httpCode = response.getStatusLine().getStatusCode();
- respBody = IOUtils.toString(response.getEntity().getContent());
+ return client.execute(put);
} catch (IOException e) {
throw new APPCException(e);
}
- if (httpCode >= 200 && httpCode < 300 && respBody != null) {
- JSONObject json;
- try {
- json = Mapper.toJsonObject(respBody);
- } catch (Exception e) {
- LOG.error("Error processing response from provider. Could not map response to json", e);
- throw new APPCException("APPC has an unknown RPC error");
- }
- boolean success;
- String reason;
- try {
- JSONObject header = json.getJSONObject("output").getJSONObject("common-response-header");
- success = header.getBoolean("success");
- reason = header.getString("reason");
- } catch (Exception e) {
- LOG.error("Unknown error prcoessing failed response from provider. Json not in expected format", e);
- throw new APPCException("APPC has an unknown RPC error");
- }
- if (success) {
- return true;
- }
- String reasonStr = reason == null ? "Unknown" : reason;
- LOG.warn(String.format("Topology Operation [%s] failed. Reason: %s", msg.getId(), reasonStr));
- throw new APPCException(reasonStr);
-
- }
- throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
}
/**
* Updates the static var URL and returns the value;
- *
+ *
* @return The new value of URL
*/
public static String getUrl() {
try {
url = new URL(newUrl);
} catch (MalformedURLException e) {
- e.printStackTrace();
+ LOG.error("Malformed URL " +newUrl + e.getMessage(), e);
}
}
* Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
* to null
*
- * @param user
- * The user with optional domain name
- * @param password
- * The password for the user
+ * @param user The user with optional domain name (for AAF)
+ * @param password The password for the user
* @return The new value of the basic auth string that will be used in the request headers
*/
public static String setAuthentication(String user, String password) {
if (user != null && password != null) {
String authStr = user + ":" + password;
- basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
+ basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
} else {
- basic_auth = null;
+ basicAuth = null;
}
- return basic_auth;
- }
-
- /**
- * Builds the request body for a topology operation
- *
- * @param id
- * The request id
- * @param action
- * The action in lowercase
- * @param url
- * The vm's url
- * @return A String containing the request body
- */
- private static String buildReqest(String id, String url, String ident) {
- String extraVmResource = "";
- if (ident != null) {
- extraVmResource = String.format(", \"identity-url\": \"%s\"", ident);
- }
- return String.format(TEMPLATE, id, url, extraVmResource);
+ return basicAuth;
}
@SuppressWarnings("deprecation")
private static HttpClient getHttpClient() throws APPCException {
HttpClient client;
- if (url.getProtocol().equals("https")) {
+ if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
- registry.register(new Scheme("https", sf, 443));
- registry.register(new Scheme("https", sf, 8443));
+ registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443));
+ registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443));
registry.register(new Scheme("http", sf, 8181));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
client = new DefaultHttpClient(ccm, params);
} catch (Exception e) {
+ LOG.error("Error creating HTTP Client. Creating default client." , e);
client = new DefaultHttpClient();
}
- } else if (url.getProtocol().equals("http")) {
+ } else if ("http".equals(url.getProtocol())) {
client = new DefaultHttpClient();
} else {
throw new APPCException(
- "The provider.topology.url property is invalid. The url did not start with http[s]");
+ "The provider.topology.url property is invalid. The url did not start with http[s]");
}
return client;
}
@SuppressWarnings("deprecation")
- public static class MySSLSocketFactory extends SSLSocketFactory {
+ private static class MySSLSocketFactory extends SSLSocketFactory {
private SSLContext sslContext = SSLContext.getInstance("TLS");
- public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
- KeyStoreException, UnrecoverableKeyException {
+ private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
+ KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+ LOG.debug("Inside checkClientTrusted");
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+ LOG.debug("Inside checkServerTrusted");
}
@Override
public X509Certificate[] getAcceptedIssuers() {
- return null;
+ return new X509Certificate[1];
}
};
- sslContext.init(null, new TrustManager[] {
- tm
+ sslContext.init(null, new TrustManager[]{
+ tm
}, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
- throws IOException, UnknownHostException {
+ throws IOException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
}
}
+ private static JsonNode toJsonNodeFromJsonString(String jsonStr) {
+ JsonNode jsonNode = null;
+ if(jsonStr != null) {
+ try {
+ jsonNode = mapper.readTree(jsonStr);
+ } catch (IOException e) {
+ LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e);
+ }
+ }
+ return jsonNode;
+ }
+
}