Updating aai adapter to v19 model
[ccsdk/sli/adaptors.git] / aai-service / provider / src / main / java / org / onap / ccsdk / sli / adaptors / aai / AAIClientRESTExecutor.java
index 85e81b5..446ec4b 100755 (executable)
@@ -5,6 +5,8 @@
  * Copyright (C) 2017 AT&T Intellectual Property. All rights
  *                         reserved.
  * ================================================================================
+ * Modifications Copyright (C) 2018 IBM.
+ * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
@@ -42,13 +44,11 @@ import java.security.NoSuchAlgorithmException;
 import java.text.SimpleDateFormat;
 import java.util.Properties;
 
-import javax.net.ssl.HostnameVerifier;
 import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.KeyManagerFactory;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLSession;
 import javax.net.ssl.SSLSocketFactory;
-import javax.ws.rs.HttpMethod;
 
 import org.apache.commons.codec.binary.Base64;
 import org.onap.ccsdk.sli.adaptors.aai.AAIService.TransactionIdTracker;
@@ -58,20 +58,19 @@ import org.onap.ccsdk.sli.adaptors.aai.data.RequestError;
 import org.onap.ccsdk.sli.adaptors.aai.data.ResourceVersion;
 import org.onap.ccsdk.sli.adaptors.aai.data.ServiceException;
 import org.onap.ccsdk.sli.core.sli.MetricLogger;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.client.urlconnection.HTTPSProperties;
 import org.apache.http.impl.EnglishReasonPhraseCatalog;
 
 /**
  * The AAIClientRESTExecutor class provides CRUD API for AAI Client service.
- * @author  richtabedzki
+ * @author  Rich Tabedzki
  */
-public     class AAIClientRESTExecutor implements AAIExecutorInterface {
+public class AAIClientRESTExecutor implements AAIExecutorInterface {
 
     private final String truststorePath;
     private final String truststorePassword;
@@ -82,6 +81,8 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
     private String userName;
     private String userPassword;
     private final String applicationId;
+    private static final String HTTP_URL_CONNECTION_RESULT="HttpURLConnection result: {} : {}";
+    private static final String ENTRY_DOESNT_EXIST="Entry does not exist.";
 
     /**
      * class Constructor
@@ -119,10 +120,9 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
 
         ignoreCertificateHostError = host_error;
 
-        HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
-            public boolean verify(String string,SSLSession ssls) {
-                return ignoreCertificateHostError;
-            }
+        HttpsURLConnection.setDefaultHostnameVerifier( (String string,SSLSession ssls)  -> {
+             return ignoreCertificateHostError;
+            
         });
 
         if(truststorePath != null && truststorePassword != null && (new File(truststorePath)).exists()) {
@@ -132,7 +132,6 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
 
         if(keystorePath != null && keystorePassword != null && (new File(keystorePath)).exists())
         {
-            DefaultClientConfig config = new DefaultClientConfig();
             //both jersey and HttpURLConnection can use this
             SSLContext ctx = null;
             try {
@@ -146,7 +145,7 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
 
                     String extension = keystorePath.substring(keystorePath.lastIndexOf(".") + 1);
 
-                    if(extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) {
+                    if(extension != null && !extension.isEmpty() && "JKS".equalsIgnoreCase(extension)) {
                         storeType = "JKS";
                     }
                     KeyStore ks = KeyStore.getInstance(storeType);
@@ -159,12 +158,6 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
                 }
 
                 ctx.init(kmf.getKeyManagers(), null, null);
-                config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() {
-                        @Override
-                        public boolean verify( String s, SSLSession sslSession ) {
-                            return ignoreCertificateHostError;
-                        }
-                }, ctx));
 
                 CTX = ctx;
                 LOG.debug("SSLContext created");
@@ -261,12 +254,13 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
                responseMessage = con.getResponseMessage();
             } catch(Exception exc) {
                responseMessage = EnglishReasonPhraseCatalog.INSTANCE.getReason(responseCode,null);
+            } finally {
                if(responseMessage == null)
                        responseMessage = NOT_PROVIDED;
             }
 
             // Process the response
-            LOG.info("HttpURLConnection result: {} : {}", responseCode, responseMessage);
+            LOG.info(HTTP_URL_CONNECTION_RESULT, responseCode, responseMessage);
             logMetricResponse(responseCode, responseMessage);
 
             if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
@@ -288,7 +282,7 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
                     LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
                 }
             } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
-                LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
+                LOGwriteEndingTrace(responseCode, responseMessage, ENTRY_DOESNT_EXIST);
                 ErrorResponse errorresponse = null;
                 try {
                     errorresponse = mapper.readValue(reader, ErrorResponse.class);
@@ -296,7 +290,7 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
                     errorresponse = new ErrorResponse();
                     RequestError requestError = new RequestError();
                     ServiceException serviceException = new ServiceException();
-                    serviceException.setText("Entry does not exist.");
+                    serviceException.setText(ENTRY_DOESNT_EXIST);
                     requestError.setServiceException(serviceException);
                     errorresponse.setRequestError(requestError );
                 }
@@ -402,11 +396,12 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
                responseMessage = con.getResponseMessage();
             } catch(Exception exc) {
                responseMessage = EnglishReasonPhraseCatalog.INSTANCE.getReason(responseCode,null);
+            } finally {
                if(responseMessage == null)
                        responseMessage = NOT_PROVIDED;
             }
 
-            LOG.info("HttpURLConnection result: {} : {}", responseCode, responseMessage);
+            LOG.info(HTTP_URL_CONNECTION_RESULT, responseCode, responseMessage);
             logMetricResponse(responseCode, responseMessage);
 
             // Process the response
@@ -483,12 +478,13 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
                responseMessage = conn.getResponseMessage();
             } catch(Exception exc) {
                responseMessage = EnglishReasonPhraseCatalog.INSTANCE.getReason(responseCode,null);
+            } finally {
                if(responseMessage == null)
                        responseMessage = NOT_PROVIDED;
             }
 
             // Process the response
-            LOG.info("HttpURLConnection result: {} : {}", responseCode, responseMessage);
+            LOG.info(HTTP_URL_CONNECTION_RESULT, responseCode, responseMessage);
             logMetricResponse(responseCode, responseMessage);
 
             if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
@@ -506,7 +502,7 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
                 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
                 response = true;
             } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
-                LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
+                LOGwriteEndingTrace(responseCode, responseMessage, ENTRY_DOESNT_EXIST);
                 response = false;
             } else {
                 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
@@ -564,11 +560,12 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
                responseMessage = con.getResponseMessage();
             } catch(Exception exc) {
                responseMessage = EnglishReasonPhraseCatalog.INSTANCE.getReason(responseCode,null);
+            } finally {
                if(responseMessage == null)
                        responseMessage = NOT_PROVIDED;
             }
 
-            LOG.info("HttpURLConnection result: {} : {}", responseCode, responseMessage);
+            LOG.info(HTTP_URL_CONNECTION_RESULT, responseCode, responseMessage);
             logMetricResponse(responseCode, responseMessage);
             ObjectMapper mapper = AAIService.getObjectMapper();
 
@@ -578,7 +575,7 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
                 response = mapper.readValue(reader, clas);
                 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
             } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
-                LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
+                LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", ENTRY_DOESNT_EXIST);
                 return response;
             } else {
                 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
@@ -615,7 +612,8 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
             }
 
             URL requestUrl = null;
-            HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
+            requestUrl = request.getRequestUrl("PATCH", resourceVersion);
+            HttpURLConnection con = getConfiguredConnection(requestUrl, "PATCH");
             ObjectMapper mapper = AAIService.getObjectMapper();
             String jsonText = request.toJSONString();
 
@@ -637,12 +635,14 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
             try {
                responseMessage = con.getResponseMessage();
             } catch(Exception exc) {
+                LOG.info("Exception occured", exc.getMessage());
                responseMessage = EnglishReasonPhraseCatalog.INSTANCE.getReason(responseCode,null);
+            } finally {
                if(responseMessage == null)
                        responseMessage = NOT_PROVIDED;
             }
 
-            LOG.info("HttpURLConnection result: {} : {}", responseCode, responseMessage);
+            LOG.info(HTTP_URL_CONNECTION_RESULT, responseCode, responseMessage);
             logMetricResponse(responseCode, responseMessage);
 
             // Process the response
@@ -715,7 +715,7 @@ public     class AAIClientRESTExecutor implements AAIExecutorInterface {
         String mlId = ml.getRequestID();
         if (mlId != null && !mlId.isEmpty()) {
             LOG.debug(String.format("MetricLogger requestId = %s", mlId));
-            con.setRequestProperty(MetricLogger.REQUEST_ID, mlId);
+            con.setRequestProperty(ONAPLogConstants.MDCs.REQUEST_ID, mlId);
         } else {
             LOG.debug("MetricLogger requestId is null");
         }