CHeckstyle and JUnit for base package in ONAP-REST
[policy/engine.git] / ONAP-PDP-REST / src / main / java / org / onap / policy / pdp / rest / XACMLPdpServlet.java
index 87cafc4..cae73ce 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP-PDP-REST
  * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * 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
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -53,13 +53,14 @@ import org.onap.policy.common.im.IntegrityMonitor;
 import org.onap.policy.common.im.IntegrityMonitorException;
 import org.onap.policy.common.im.IntegrityMonitorProperties;
 import org.onap.policy.common.im.StandbyStatusException;
-import org.onap.policy.common.logging.ONAPLoggingContext;
-import org.onap.policy.common.logging.ONAPLoggingUtils;
+import org.onap.policy.common.logging.OnapLoggingContext;
+import org.onap.policy.common.logging.OnapLoggingUtils;
 import org.onap.policy.common.logging.eelf.MessageCodes;
 import org.onap.policy.common.logging.eelf.PolicyLogger;
 import org.onap.policy.pdp.rest.jmx.PdpRestMonitor;
-import org.onap.policy.rest.XACMLRest;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRest;
+import org.onap.policy.rest.XacmlRestProperties;
+import org.onap.policy.utils.PeCryptoUtils;
 import org.onap.policy.xacml.api.XACMLErrorConstants;
 import org.onap.policy.xacml.pdp.std.functions.PolicyList;
 import org.onap.policy.xacml.std.pap.StdPDPStatus;
@@ -77,23 +78,23 @@ import com.fasterxml.jackson.databind.ObjectMapper;
 
 /**
  * Servlet implementation class XacmlPdpServlet
- * 
+ *
  * This is an implementation of the XACML 3.0 RESTful Interface with added features to support simple PAP RESTful API
  * for policy publishing and PIP configuration changes.
- * 
+ *
  * If you are running this the first time, then we recommend you look at the xacml.pdp.properties file. This properties
  * file has all the default parameter settings. If you are running the servlet as is, then we recommend setting up
  * you're container to run it on port 8080 with context "/pdp". Wherever the default working directory is set to, a
  * "config" directory will be created that holds the policy and pip cache. This setting is located in the
  * xacml.pdp.properties file.
- * 
+ *
  * When you are ready to customize, you can create a separate xacml.pdp.properties on you're local file system and setup
  * the parameters as you wish. Just set the Java VM System variable to point to that file:
- * 
+ *
  * -Dxacml.properties=/opt/app/xacml/etc/xacml.pdp.properties
- * 
+ *
  * Or if you only want to change one or two properties, simply set the Java VM System variable for that property.
- * 
+ *
  * -Dxacml.rest.pdp.register=false
  *
  *
@@ -176,7 +177,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
     //
     private static transient Thread configThread = null;
     private static volatile boolean configThreadTerminate = false;
-    private transient ONAPLoggingContext baseLoggingContext = null;
+    private transient OnapLoggingContext baseLoggingContext = null;
     private transient IntegrityMonitor im;
 
     public IntegrityMonitor getIm() {
@@ -204,7 +205,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
         //
         // Initialize
         //
-        XACMLRest.xacmlInit(config);
+        XacmlRest.xacmlInit(config);
         // Load the Notification Delay.
         setNotificationDelay();
         // Load Queue size. Not sure if we really need to have the queue bounded, we should look further into this
@@ -225,7 +226,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
         //
         // Logging stuff....
         //
-        baseLoggingContext = new ONAPLoggingContext();
+        baseLoggingContext = new OnapLoggingContext();
         // fixed data that will be the same in all logging output goes here
         try {
             String hostname = InetAddress.getLocalHost().getCanonicalHostName();
@@ -242,7 +243,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
                     "Error loading properties with: XACMLProperties.getProperties()");
             throw new ServletException(e.getMessage(), e.getCause());
         }
-        if (properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME) == null) {
+        if (properties.getProperty(XacmlRestProperties.PDP_RESOURCE_NAME) == null) {
             XACMLProperties.reloadProperties();
             try {
                 properties = XACMLProperties.getProperties();
@@ -268,23 +269,34 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
                 properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE);
         setCreateUpdatePolicyConstructor(createUpdateResourceName);
 
+        PeCryptoUtils.initAesKey(properties.getProperty(XacmlRestProperties.PROP_AES_KEY));
+
         // Create an IntegrityMonitor
         try {
             logger.info("Creating IntegrityMonitor");
+            properties.setProperty("javax.persistence.jdbc.password",
+                    PeCryptoUtils.decrypt(properties.getProperty("javax.persistence.jdbc.password", "")));
             im = IntegrityMonitor.getInstance(pdpResourceName, properties);
         } catch (Exception e) {
             PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" + e);
             throw new ServletException(e);
         }
+
+        try {
+            System.setProperty("msToscaModel.home", properties.getProperty("msToscaModel.home"));
+        } catch (Exception e) {
+           logger.error("ERROR: Unable to set msToscaModel.home- Please check the configuration");
+        }
+
         startThreads(baseLoggingContext, new Thread(this));
     }
 
-    private static void startThreads(ONAPLoggingContext baseLoggingContext, Thread thread) {
+    private static void startThreads(OnapLoggingContext baseLoggingContext, Thread thread) {
         environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
         //
         // Kick off our thread to register with the PAP servlet.
         //
-        if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER))) {
+        if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_REGISTER))) {
             XACMLPdpServlet.registerRunnable = new XACMLPdpRegisterThread(baseLoggingContext);
             XACMLPdpServlet.registerThread = new Thread(XACMLPdpServlet.registerRunnable);
             XACMLPdpServlet.registerThread.start();
@@ -309,9 +321,9 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
     }
 
     private static void setPDPResourceName(Properties properties) throws ServletException {
-        pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME);
+        pdpResourceName = properties.getProperty(XacmlRestProperties.PDP_RESOURCE_NAME);
         if (pdpResourceName == null) {
-            PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp");
+            PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XacmlRestProperties.PDP_RESOURCE_NAME, "xacml.pdp");
             throw new ServletException("pdpResourceName is null");
         }
     }
@@ -323,7 +335,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
     private static void setNotificationDelay() {
         try {
             XACMLPdpServlet.notificationDelay =
-                    Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY));
+                    Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_DELAY));
         } catch (NumberFormatException e) {
             logger.error("Error in notification delay format, Taking the default value.", e);
         }
@@ -373,52 +385,52 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
 
     /**
      * PUT - The PAP engine sends configuration information using HTTP PUT request.
-     * 
+     *
      * One parameter is expected:
-     * 
+     *
      * config=[policy|pip|all]
-     * 
+     *
      * policy - Expect a properties file that contains updated lists of the root and referenced policies that the PDP
      * should be using for PEP requests.
-     * 
+     *
      * Specifically should AT LEAST contain the following properties: xacml.rootPolicies xacml.referencedPolicies
-     * 
+     *
      * In addition, any relevant information needed by the PDP to load or retrieve the policies to store in its cache.
      *
      * EXAMPLE: xacml.rootPolicies=PolicyA.1, PolicyB.1
      *
      * PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1
      * PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1
-     * 
+     *
      * xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1
      *
      * RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1
      * RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1
-     * 
+     *
      * pip - Expect a properties file that contain PIP engine configuration properties.
-     * 
+     *
      * Specifically should AT LEAST the following property: xacml.pip.engines
-     * 
+     *
      * In addition, any relevant information needed by the PDP to load and configure the PIPs.
-     * 
+     *
      * EXAMPLE: xacml.pip.engines=foo,bar
-     * 
+     *
      * foo.classname=com.foo foo.sample=abc foo.example=xyz ......
-     * 
+     *
      * bar.classname=com.bar ......
-     * 
+     *
      * all - Expect ALL new configuration properties for the PDP
-     * 
+     *
      * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
      */
     @Override
     protected void doPut(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
-        ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+        OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
         loggingContext.transactionStarted();
-        if ((loggingContext.getRequestID() == null) || "".equals(loggingContext.getRequestID())) {
+        if ((loggingContext.getRequestId() == null) || "".equals(loggingContext.getRequestId())) {
             UUID requestID = UUID.randomUUID();
-            loggingContext.setRequestID(requestID.toString());
+            loggingContext.setRequestId(requestID.toString());
             PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPut) so we generated one");
         } else {
             PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPut)");
@@ -433,7 +445,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
         // Dump our request out
         //
         if (logger.isDebugEnabled()) {
-            XACMLRest.dumpRequest(request);
+            XacmlRest.dumpRequest(request);
         }
 
         try {
@@ -497,7 +509,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
     }
 
     protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response,
-            ONAPLoggingContext loggingContext) throws ServletException, IOException {
+            OnapLoggingContext loggingContext) throws IOException {
         try {
             // prevent multiple configuration changes from stacking up
             logger.info("XACMLPdpServlet: checking remainingCapacity of Queue.");
@@ -618,23 +630,23 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
 
     /**
      * Parameters: type=hb|config|Status
-     * 
+     *
      * 1. HeartBeat Status HeartBeat OK - All Policies are Loaded, All PIPs are Loaded LOADING_IN_PROGRESS - Currently
      * loading a new policy set/pip configuration LAST_UPDATE_FAILED - Need to track the items that failed during last
      * update LOAD_FAILURE - ??? Need to determine what information is sent and how 2. Configuration 3. Status return
      * the StdPDPStatus object in the Response content
-     * 
-     * 
+     *
+     *
      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
      */
     @Override
     protected void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
-        ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+        OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
         loggingContext.transactionStarted();
-        if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")) {
+        if ((loggingContext.getRequestId() == null) || (loggingContext.getRequestId() == "")) {
             UUID requestID = UUID.randomUUID();
-            loggingContext.setRequestID(requestID.toString());
+            loggingContext.setRequestId(requestID.toString());
             PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doGet) so we generated one");
         } else {
             PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doGet)");
@@ -646,95 +658,66 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
         loggingContext.metricEnded();
         PolicyLogger.metrics("Metric example posted here - 2 of 2");
 
-        XACMLRest.dumpRequest(request);
+        XacmlRest.dumpRequest(request);
 
         String pathInfo = request.getRequestURI();
-        if (pathInfo != null) {
+        if (pathInfo != null && "/pdp/test".equals(pathInfo)) {
             // health check from Global Site Selector (iDNS).
             // DO NOT do a im.startTransaction for the test request
-            if (pathInfo.equals("/pdp/test")) {
-                loggingContext.setServiceName("iDNS:PDP.test");
+            loggingContext.setServiceName("iDNS:PDP.test");
+            try {
+                im.evaluateSanity();
+                // If we make it this far, all is well
+                String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK";
+                PolicyLogger.debug(message);
+                PolicyLogger.audit("Success");
+                response.setStatus(HttpServletResponse.SC_OK);
+                return;
+            } catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException fpe) {
+                // No forward progress is being made
+                String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is not making forward progress."
+                        + " Exception Message: " + fpe.getMessage();
+                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + fpe);
+                PolicyLogger.audit("Transaction Failed - See Error.log");
                 try {
-                    im.evaluateSanity();
-                    // If we make it this far, all is well
-                    String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK";
-                    PolicyLogger.debug(message);
-                    loggingContext.transactionEnded();
-                    PolicyLogger.audit("Success");
-                    response.setStatus(HttpServletResponse.SC_OK);
-                    return;
-                } catch (ForwardProgressException fpe) {
-                    // No forward progress is being made
-                    String message = "GET:/pdp/test called and PDP " + pdpResourceName
-                            + " is not making forward progress." + " Exception Message: " + fpe.getMessage();
-                    PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + fpe);
-                    loggingContext.transactionEnded();
-                    PolicyLogger.audit("Transaction Failed - See Error.log");
-                    try {
-                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                    } catch (Exception e1) {
-                        logger.error("Exception occured while sending error in response" + e1);
-                    }
-                    return;
-                } catch (AdministrativeStateException ase) {
-                    // Administrative State is locked
-                    String message = "GET:/pdp/test called and PDP " + pdpResourceName
-                            + " Administrative State is LOCKED " + " Exception Message: " + ase.getMessage();
-                    PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + ase);
-                    loggingContext.transactionEnded();
-                    PolicyLogger.audit("Transaction Failed - See Error.log");
-                    try {
-                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                    } catch (Exception e1) {
-                        logger.error("Exception occured while sending error in response" + e1);
-                    }
-                    return;
-                } catch (StandbyStatusException sse) {
-                    // Administrative State is locked
-                    String message = "GET:/pdp/test called and PDP " + pdpResourceName
-                            + " Standby Status is NOT PROVIDING SERVICE " + " Exception Message: " + sse.getMessage();
-                    PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + sse);
-                    loggingContext.transactionEnded();
-                    PolicyLogger.audit("Transaction Failed - See Error.log");
-                    try {
-                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                    } catch (Exception e1) {
-                        logger.error("Exception occured while sending error in response" + e1);
-                    }
-                    return;
-                } catch (Exception e) {
-                    // A subsystem is not making progress or is not responding
-                    String eMsg = e.getMessage();
-                    if (eMsg == null) {
-                        eMsg = "No Exception Message";
-                    }
-                    String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure."
-                            + " Exception Message: " + eMsg;
-                    PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
-                    // Get the specific list of subsystems that failed
-                    String failedNodeList = null;
-                    for (String node : dependencyNodes) {
-                        if (eMsg.contains(node)) {
-                            if (failedNodeList == null) {
-                                failedNodeList = node;
-                            } else {
-                                failedNodeList = failedNodeList.concat("," + node);
-                            }
+                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                } catch (Exception e1) {
+                    logger.error("Exception occured while sending error in response" + e1);
+                }
+                return;
+            } catch (Exception e) {
+                // A subsystem is not making progress or is not responding
+                String eMsg = e.getMessage();
+                if (eMsg == null) {
+                    eMsg = "No Exception Message";
+                }
+                String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure."
+                        + " Exception Message: " + eMsg;
+                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
+                // Get the specific list of subsystems that failed
+                String failedNodeList = null;
+                for (String node : dependencyNodes) {
+                    if (eMsg.contains(node)) {
+                        if (failedNodeList == null) {
+                            failedNodeList = node;
+                        } else {
+                            failedNodeList = failedNodeList.concat("," + node);
                         }
                     }
-                    if (failedNodeList == null) {
-                        failedNodeList = "UnknownSubSystem";
-                    }
-                    response.addHeader("X-ONAP-SubsystemFailure", failedNodeList);
-                    try {
-                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                    } catch (Exception e1) {
-                        logger.error("Exception occured while sending error in response" + e1);
-                    }
-                    loggingContext.transactionEnded();
-                    PolicyLogger.audit("Transaction Failed - See Error.log" + e);
-                    return;
                 }
+                if (failedNodeList == null) {
+                    failedNodeList = "UnknownSubSystem";
+                }
+                response.addHeader("X-ONAP-SubsystemFailure", failedNodeList);
+                try {
+                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                } catch (Exception e1) {
+                    logger.error("Exception occured while sending error in response" + e1);
+                }
+                PolicyLogger.audit("Transaction Failed - See Error.log" + e);
+                return;
+            } finally {
+                loggingContext.transactionEnded();
             }
         }
 
@@ -822,7 +805,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
         }
         if (returnHB) {
             synchronized (pdpStatusLock) {
-                response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
+                response.addHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
             }
         }
         loggingContext.transactionEnded();
@@ -834,20 +817,20 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
     /**
      * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or JSON
      * according to the XACML 3.0 Specifications for both.
-     * 
-     * 
+     *
+     *
      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
      */
     @Override
     protected void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
 
-        ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+        OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
         loggingContext.transactionStarted();
         loggingContext.setServiceName("PDP.decide");
-        if ((loggingContext.getRequestID() == null) || ("".equals(loggingContext.getRequestID()))) {
+        if ((loggingContext.getRequestId() == null) || ("".equals(loggingContext.getRequestId()))) {
             UUID requestID = UUID.randomUUID();
-            loggingContext.setRequestID(requestID.toString());
+            loggingContext.setRequestId(requestID.toString());
             PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPost) so we generated one");
         } else {
             PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPost)");
@@ -893,7 +876,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
             return;
         }
 
-        XACMLRest.dumpRequest(request);
+        XacmlRest.dumpRequest(request);
         //
         // Set our no-cache header
         //
@@ -1001,7 +984,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
                 if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
                     pdpRequest = JSONRequest.load(incomingRequestString);
                 } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
-                        || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
+                        || "application/xacml+xml".equalsIgnoreCase(contentType.getMimeType())) {
                     pdpRequest = DOMRequest.load(incomingRequestString);
                 }
             } catch (Exception e) {
@@ -1035,7 +1018,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
         // Did we successfully get and parse a request?
         //
         if (pdpRequest == null || pdpRequest.getRequestAttributes() == null
-                || pdpRequest.getRequestAttributes().size() <= 0) {
+                || pdpRequest.getRequestAttributes().isEmpty()) {
             String message = "Zero Attributes found in the request";
             logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);