Merge "Adding simple, missing junit"
authorJorge Hernandez <jorge.hernandez-herrero@att.com>
Thu, 17 Oct 2019 00:09:11 +0000 (00:09 +0000)
committerGerrit Code Review <gerrit@onap.org>
Thu, 17 Oct 2019 00:09:11 +0000 (00:09 +0000)
35 files changed:
POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPdpProperties.java
POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java
POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java
POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java
POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java
POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ActionPolicyControllerTest.java [new file with mode: 0644]
POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java
POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java
POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java [new file with mode: 0644]
POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java

index 81d3fb5..16b6d09 100644 (file)
@@ -53,7 +53,7 @@ import org.onap.policy.xacml.api.XACMLErrorConstants;
  *
  * <p>The reset() method has been added to assist with the above problem in order to acquire >80% JUnit code coverage.
  *
- * <p>This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure 
+ * <p>This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure
  * that a valid URL exists for a PDP along with user/password.
  */
 public class CheckPdpProperties {
@@ -209,8 +209,7 @@ public class CheckPdpProperties {
                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
             }
             return encoding;
-        } else {
-            return null;
         }
+        return null;
     }
 }
index cff9dd5..343a19f 100644 (file)
@@ -69,28 +69,25 @@ public class PolicyAdapter {
     }
 
     private String getConfigPolicyName(PolicyRestAdapter policyAdapter) {
-        String configPolicyName = null;
         if (policyAdapter.getPolicyName().startsWith("Config_PM")) {
-            configPolicyName = "ClosedLoop_PM";
+            return "ClosedLoop_PM";
         } else if (policyAdapter.getPolicyName().startsWith("Config_Fault")) {
-            configPolicyName = "ClosedLoop_Fault";
+            return "ClosedLoop_Fault";
         } else if (policyAdapter.getPolicyName().startsWith("Config_FW")) {
-            configPolicyName = "Firewall Config";
+            return "Firewall Config";
         } else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")) {
-            configPolicyName = "BRMS_Raw";
+            return "BRMS_Raw";
         } else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")) {
-            configPolicyName = "BRMS_Param";
+            return "BRMS_Param";
         } else if (policyAdapter.getPolicyName().startsWith("Config_MS")) {
-            configPolicyName = "Micro Service";
+            return "Micro Service";
         } else if (policyAdapter.getPolicyName().startsWith("Config_OOF")) {
-            configPolicyName = "Optimization";
+            return "Optimization";
         } else if (policyAdapter.getPolicyName().startsWith("Action")
                 || policyAdapter.getPolicyName().startsWith("Decision")) {
-            // No configPolicyName is applicable
-        } else {
-            configPolicyName = "Base";
+            return null;
         }
-        return configPolicyName;
+        return "Base";
     }
 
     private void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
index d4378f4..ed1266c 100644 (file)
@@ -390,7 +390,6 @@ public class PolicyManagerServlet extends HttpServlet {
     }
 
     private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
-        List<Object> policyData = new ArrayList<>();
         JSONArray policyList = null;
         if (params.has("policyList")) {
             policyList = (JSONArray) params.get("policyList");
@@ -398,7 +397,7 @@ public class PolicyManagerServlet extends HttpServlet {
         PolicyController controller = getPolicyControllerInstance();
         List<JSONObject> resultList = new ArrayList<>();
         try {
-            if (!lookupPolicyData(request, policyData, policyList, controller, resultList)) {
+            if (!lookupPolicyData(request, new ArrayList<>(), policyList, controller, resultList)) {
                 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
             }
         } catch (Exception e) {
@@ -411,13 +410,11 @@ public class PolicyManagerServlet extends HttpServlet {
 
     private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList,
             PolicyController controller, List<JSONObject> resultList) {
-        List<String> roles;
-        Set<String> scopes;// Get the Login Id of the User from Request
         String userId = UserUtils.getUserSession(request).getOrgUserId();
         List<Object> userRoles = controller.getRoles(userId);
         Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
-        roles = pair.u;
-        scopes = pair.t;
+        List<String> roles = pair.second;
+        Set<String> scopes = pair.first;
         if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
             if (scopes.isEmpty()) {
                 return false;
@@ -601,13 +598,12 @@ public class PolicyManagerServlet extends HttpServlet {
         } else if (path.contains(DECISION2)) {
             path = path.replace(DECISION, DECISION1);
         }
-        PolicyController controller = getPolicyControllerInstance();
         String[] split = path.split(":");
         String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
         SimpleBindings peParams = new SimpleBindings();
         peParams.put(SPLIT_1, split[1]);
         peParams.put(SPLIT_0, split[0]);
-        List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
+        List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams);
         if (queryData.isEmpty()) {
             return error("Error Occured while Describing the Policy - query is empty");
         }
@@ -645,14 +641,13 @@ public class PolicyManagerServlet extends HttpServlet {
     }
 
     private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
-        PolicyController controller = getPolicyControllerInstance();
         // Get the Login Id of the User from Request
         String testUserID = getTestUserId();
         String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
-        List<Object> userRoles = controller.getRoles(userId);
+        List<Object> userRoles = getPolicyControllerInstance().getRoles(userId);
         Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
-        List<String> roles = pair.u;
-        Set<String> scopes = pair.t;
+        List<String> roles = pair.second;
+        Set<String> scopes = pair.first;
         Map<String, String> roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles);
 
         List<JSONObject> resultList = new ArrayList<>();
@@ -741,7 +736,6 @@ public class PolicyManagerServlet extends HttpServlet {
     // Get Active Policy List based on Scope Selection from Policy Version table
     private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles,
             Set<String> scopes, Map<String, String> roleByScope) {
-        final PolicyController controller = getPolicyControllerInstance();
         String scopeName = inScopeName;
         if (scopeName.contains(FORWARD_SLASH)) {
             scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
@@ -754,8 +748,8 @@ public class PolicyManagerServlet extends HttpServlet {
         SimpleBindings params = new SimpleBindings();
         params.put(SCOPE_NAME, scopeName + "%");
 
-        List<Object> activePolicies = getDataByQueryFromController(controller, query, params);
-        List<Object> scopesList = getDataByQueryFromController(controller,
+        List<Object> activePolicies = getDataByQueryFromController(getPolicyControllerInstance(), query, params);
+        List<Object> scopesList = getDataByQueryFromController(getPolicyControllerInstance(),
                 FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params);
         for (Object list : scopesList) {
             scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope);
@@ -845,8 +839,8 @@ public class PolicyManagerServlet extends HttpServlet {
     }
 
     private String getUserName(String loginId) {
-        PolicyController controller = getPolicyControllerInstance();
-        UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
+        UserInfo userInfo = (UserInfo) getPolicyControllerInstance().getEntityItem(UserInfo.class, "userLoginId",
+                loginId);
         if (userInfo == null) {
             return SUPERADMIN;
         }
@@ -1543,7 +1537,6 @@ public class PolicyManagerServlet extends HttpServlet {
     private JSONObject editFile(JSONObject params) throws ServletException {
         // get content
         try {
-            final PolicyController controller = getPolicyControllerInstance();
             final String mode = params.getString("mode");
             String path = params.getString("path");
             LOGGER.debug("editFile path: {}" + path);
@@ -1560,7 +1553,7 @@ public class PolicyManagerServlet extends HttpServlet {
             SimpleBindings peParams = new SimpleBindings();
             peParams.put(SPLIT_1, split[1]);
             peParams.put(SPLIT_0, split[0]);
-            List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
+            List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams);
             PolicyEntity entity = (PolicyEntity) queryData.get(0);
             InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
 
@@ -1599,7 +1592,6 @@ public class PolicyManagerServlet extends HttpServlet {
 
     // Add Scopes
     private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
-        PolicyController controller = getPolicyControllerInstance();
         try {
             String name = getNameFromParams(params);
             String validateName =
@@ -1614,7 +1606,8 @@ public class PolicyManagerServlet extends HttpServlet {
                     name = name.substring(1);
                 }
                 PolicyEditorScopes entity =
-                        (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, SCOPE_NAME, name);
+                        (PolicyEditorScopes) getPolicyControllerInstance().getEntityItem(
+                                PolicyEditorScopes.class, SCOPE_NAME, name);
                 if (entity != null) {
                     return error("Scope Already Exists");
                 }
@@ -1625,7 +1618,7 @@ public class PolicyManagerServlet extends HttpServlet {
                 newScope.setScopeName(name);
                 newScope.setUserCreatedBy(userInfo);
                 newScope.setUserModifiedBy(userInfo);
-                controller.saveData(newScope);
+                getPolicyControllerInstance().saveData(newScope);
             }
             return success();
         } catch (Exception e) {
index 79b08d2..12d3fc3 100644 (file)
@@ -132,11 +132,10 @@ public class PolicyRestController extends RestrictedBaseController {
      */
     @RequestMapping(value = {"/policycreation/save_policy"}, method = {RequestMethod.POST})
     public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
-        String userId = UserUtils.getUserSession(request).getOrgUserId();
         ObjectMapper mapper = new ObjectMapper();
         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
         try {
-            updateAndSendToPap(request, response, userId, mapper);
+            updateAndSendToPap(request, response, UserUtils.getUserSession(request).getOrgUserId(), mapper);
         } catch (Exception e) {
             policyLogger.error("Exception Occured while saving policy", e);
         }
@@ -171,9 +170,8 @@ public class PolicyRestController extends RestrictedBaseController {
         policyData.setUserId(userId);
 
         String result;
-        String body = PolicyUtils.objectToJsonString(policyData);
-        String uri = request.getRequestURI();
-        ResponseEntity<?> responseEntity = sendToPap(body, uri, HttpMethod.POST);
+        ResponseEntity<?> responseEntity = sendToPap(PolicyUtils.objectToJsonString(policyData),
+                request.getRequestURI(), HttpMethod.POST);
         if (responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)) {
             result = "PolicyExists";
         } else if (responseEntity != null) {
@@ -236,10 +234,10 @@ public class PolicyRestController extends RestrictedBaseController {
 
     private ResponseEntity<?> sendToPap(String body, String requestUri, HttpMethod method) {
         String papUrl = PolicyController.getPapUrl();
-        String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
         String papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
-        Base64.Encoder encoder = Base64.getEncoder();
-        String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
+        String encoding = Base64.getEncoder().encodeToString(
+                (XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)
+                + ":" + papPass).getBytes(StandardCharsets.UTF_8));
         HttpHeaders headers = new HttpHeaders();
         headers.set(AUTHORIZATION, BASIC + encoding);
         headers.set(CONTENT_TYPE, PolicyController.getContenttype());
@@ -286,25 +284,23 @@ public class PolicyRestController extends RestrictedBaseController {
     }
 
     private String callPap(HttpServletRequest request, String method, String uriValue) {
-        String papUrl = PolicyController.getPapUrl();
-        String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
         PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
         String papPass = PeCryptoUtils.decrypt((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
 
         Base64.Encoder encoder = Base64.getEncoder();
-        String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
+        String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)
+                + ":" + papPass).getBytes(StandardCharsets.UTF_8));
         HttpHeaders headers = new HttpHeaders();
         headers.set(AUTHORIZATION, BASIC + encoding);
         headers.set(CONTENT_TYPE, PolicyController.getContenttype());
 
         HttpURLConnection connection = null;
-        List<FileItem> items;
         FileItem item = null;
         File file = null;
         String uri = uriValue;
         if (uri.contains(IMPORT_DICTIONARY)) {
             try {
-                items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
+                List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                 item = items.get(0);
                 file = new File(item.getName());
                 String newFile = file.toString();
@@ -315,7 +311,7 @@ public class PolicyRestController extends RestrictedBaseController {
         }
 
         try {
-            URL url = new URL(papUrl + uri);
+            URL url = new URL(PolicyController.getPapUrl() + uri);
             connection = (HttpURLConnection) url.openConnection();
             connection.setRequestMethod(method);
             connection.setUseCaches(false);
@@ -358,7 +354,6 @@ public class PolicyRestController extends RestrictedBaseController {
 
     private void checkUri(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item)
             throws IOException {
-        String boundary;
         if (!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))) {
             connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype());
             ObjectMapper mapper = new ObjectMapper();
@@ -385,7 +380,7 @@ public class PolicyRestController extends RestrictedBaseController {
                 IOUtils.copy(request.getInputStream(), os);
             }
         } else {
-            boundary = "===" + System.currentTimeMillis() + "===";
+            String boundary = "===" + System.currentTimeMillis() + "===";
             connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
             try (OutputStream os = connection.getOutputStream()) {
                 if (item != null) {
@@ -407,8 +402,7 @@ public class PolicyRestController extends RestrictedBaseController {
 
     private String doConnect(final HttpURLConnection connection) throws IOException {
         connection.connect();
-        int responseCode = connection.getResponseCode();
-        if (responseCode == 200) {
+        if (connection.getResponseCode() == 200) {
             // get the response content into a String
             String responseJson = null;
             // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
@@ -438,9 +432,9 @@ public class PolicyRestController extends RestrictedBaseController {
      */
     @RequestMapping(value = {"/getDictionary/*"}, method = {RequestMethod.GET})
     public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) {
-        String uri = request.getRequestURI().replace("/getDictionary", "");
         String body;
-        ResponseEntity<?> responseEntity = sendToPap(null, uri, HttpMethod.GET);
+        ResponseEntity<?> responseEntity = sendToPap(null, request.getRequestURI().replace("/getDictionary", ""),
+                HttpMethod.GET);
         if (responseEntity != null) {
             body = responseEntity.getBody().toString();
         } else {
@@ -542,8 +536,7 @@ public class PolicyRestController extends RestrictedBaseController {
                 data.add("Elastic Search Server is down");
                 resultList = data;
             } else {
-                JSONObject json = new JSONObject(body);
-                resultList = json.get("policyresult");
+                resultList = new JSONObject(body).get("policyresult");
             }
         } catch (Exception e) {
             policyLogger.error(
@@ -555,9 +548,7 @@ public class PolicyRestController extends RestrictedBaseController {
 
         response.setCharacterEncoding(PolicyController.getCharacterencoding());
         response.setContentType(PolicyController.getContenttype());
-        PrintWriter out = response.getWriter();
-        JSONObject json = new JSONObject("{result: " + resultList + "}");
-        out.write(json.toString());
+        response.getWriter().write(new JSONObject("{result: " + resultList + "}").toString());
         return null;
     }
 
@@ -595,9 +586,7 @@ public class PolicyRestController extends RestrictedBaseController {
         response.setContentType("application / json");
         request.setCharacterEncoding(UTF_8);
 
-        PrintWriter out = response.getWriter();
-        JSONObject json2 = new JSONObject("{result: " + resultList + "}");
-        out.write(json2.toString());
+        response.getWriter().write(new JSONObject("{result: " + resultList + "}").toString());
         return null;
     }
 
index 4163188..9cf6479 100644 (file)
@@ -53,15 +53,12 @@ public class PolicyUserInfoController extends RestrictedBaseController {
      */
     @RequestMapping(value = "/get_PolicyUserInfo", method = RequestMethod.GET)
     public void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response) {
-        JsonMessage msg;
         try {
             String userId = UserUtils.getUserSession(request).getOrgUserId();
             Map<String, Object> model = new HashMap<>();
-            ObjectMapper mapper = new ObjectMapper();
             model.put("userid", userId);
-            msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject json = new JSONObject(msg);
-            response.getWriter().write(json.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(
+                    new ObjectMapper().writeValueAsString(model))).toString());
         } catch (Exception e) {
             LOGGER.error("Exception Occurred" + e);
         }
index 60029f8..f2c3a5d 100644 (file)
@@ -8,9 +8,9 @@
  * 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.
@@ -106,9 +106,16 @@ public class HumanPolicyComponent {
         // Default Constructor
     }
 
+    /**
+     * DescribePolicy.
+     *
+     * @param policyFile File
+     * @return JSONObject
+     */
     public static JSONObject DescribePolicy(final File policyFile) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace(ENTER);
+        }
 
         HumanPolicyComponent.policyFile = policyFile;
         return humanPolicyLayout();
@@ -116,8 +123,9 @@ public class HumanPolicyComponent {
     }
 
     private static JSONObject humanPolicyLayout() {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace(ENTER);
+        }
 
         try {
             String html = processPolicy();
@@ -137,8 +145,9 @@ public class HumanPolicyComponent {
         }
         try (FileInputStream pIS = new FileInputStream(policyFile)) {
             Object policy = XACMLPolicyScanner.readPolicy(pIS);
-            if (policy == null)
+            if (policy == null) {
                 throw new IllegalArgumentException("Policy File " + policyFile.getName() + " cannot be unmarshalled");
+            }
 
             HumanPolicyComponent.htmlProcessor = new HtmlProcessor(HumanPolicyComponent.policyFile, policy);
 
@@ -146,8 +155,9 @@ public class HumanPolicyComponent {
             XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor);
             xacmlScanner.scan();
             String html = htmlProcessor.html();
-            if (LOGGER.isDebugEnabled())
+            if (LOGGER.isDebugEnabled()) {
                 LOGGER.debug(policyPath + System.lineSeparator() + html);
+            }
 
             return html;
 
@@ -167,6 +177,7 @@ class HtmlProcessor extends SimpleCallback {
 
     private static final String ENTER = "ENTER";
     private static Map<String, String> function2human;
+
     static {
         function2human = new HashMap<>();
         function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal");
@@ -177,6 +188,7 @@ class HtmlProcessor extends SimpleCallback {
     }
 
     private static Map<String, String> combiningAlgo2human;
+
     static {
         combiningAlgo2human = new HashMap<>();
         combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to <i>deny</i>");
@@ -205,8 +217,9 @@ class HtmlProcessor extends SimpleCallback {
     private final Object rootPolicyObject;
 
     public HtmlProcessor(File policyFile, Object policyObject) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace(ENTER);
+        }
 
         if (policyFile == null) {
             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File");
@@ -261,6 +274,8 @@ class HtmlProcessor extends SimpleCallback {
     }
 
     /**
+     * getAttributeIdentifiersMap.
+     *
      * @return the attributeIdentifiersMap
      */
     public Map<String, AttributeIdentifiers> getAttributeIdentifiersMap() {
@@ -269,8 +284,9 @@ class HtmlProcessor extends SimpleCallback {
 
     @Override
     public void onFinishScan(Object root) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace(ENTER);
+        }
 
         if (rootPolicyObject instanceof PolicySetType) {
             htmlOut.println("</dl>");
@@ -308,43 +324,52 @@ class HtmlProcessor extends SimpleCallback {
 
     @Override
     public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion());
+        }
 
-        if (parent != null && LOGGER.isTraceEnabled())
+        if (parent != null && LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + "Parent PolicySet: " + parent.getPolicySetId()
                     + " Version: " + parent.getVersion());
+        }
 
         String description = policySet.getDescription();
-        if (description != null && LOGGER.isTraceEnabled())
+        if (description != null && LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Description: " + policySet.getDescription());
+        }
 
-        if (parent == null) // root
+        if (parent == null) // root
             policySet(policySet, "dl");
-        else
+        } else {
             policySet(policySet, "li");
+        }
 
-        if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty())
+        if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) {
             htmlOut.println("<ol>");
+        }
 
         return super.onPreVisitPolicySet(parent, policySet);
     }
 
     @Override
     public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion());
+        }
 
-        if (parent != null && LOGGER.isTraceEnabled())
+        if (parent != null && LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + "Parent PolicySet: " + parent.getPolicySetId()
                     + " Version: " + parent.getVersion());
+        }
 
         String description = policySet.getDescription();
-        if (description != null && LOGGER.isTraceEnabled())
+        if (description != null && LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Description: " + policySet.getDescription());
+        }
 
-        if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty())
+        if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) {
             htmlOut.println("</ol>");
+        }
 
         htmlOut.println("<p></p>");
 
@@ -352,21 +377,25 @@ class HtmlProcessor extends SimpleCallback {
     }
 
     public void policySet(PolicySetType policySet, String htmlListElement) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policySet.getPolicySetId());
+        }
 
         String combiningAlgorithm = "-";
         String id = "-";
         String version = "-";
 
-        if (policySet.getPolicyCombiningAlgId() != null)
+        if (policySet.getPolicyCombiningAlgId() != null) {
             combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":");
+        }
 
-        if (policySet.getPolicySetId() != null)
+        if (policySet.getPolicySetId() != null) {
             id = extractLastIdentifier(policySet.getPolicySetId(), ":");
+        }
 
-        if (policySet.getVersion() != null)
+        if (policySet.getVersion() != null) {
             version = policySet.getVersion();
+        }
 
         htmlOut.println("<" + htmlListElement + "><b>Policy Set ID</b>: <i>" + id + "</i>  (v" + version + ") " + "</"
                 + htmlListElement + ">");
@@ -378,8 +407,7 @@ class HtmlProcessor extends SimpleCallback {
             htmlOut.print("<p>");
             htmlOut.print("This policy set applies to requests with attributes ");
 
-            List<AnyOfType> anyOf_s = policySet.getTarget().getAnyOf();
-            target(anyOf_s);
+            target(policySet.getTarget().getAnyOf());
             htmlOut.println(".</p>");
         }
 
@@ -398,57 +426,68 @@ class HtmlProcessor extends SimpleCallback {
 
     @Override
     public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion());
+        }
 
-        if (parent != null && LOGGER.isTraceEnabled())
+        if (parent != null && LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policy.getPolicyId() + "Parent PolicySet: " + parent.getPolicySetId()
                     + " Version: " + parent.getVersion());
+        }
 
         String description = policy.getDescription();
-        if (description != null && LOGGER.isTraceEnabled())
+        if (description != null && LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Description: " + policy.getDescription());
+        }
 
         policy(policy);
 
-        if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty())
+        if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) {
             htmlOut.println("<ol type=\"i\">");
+        }
 
         return super.onPreVisitPolicy(parent, policy);
     }
 
     @Override
     public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion());
+        }
 
-        if (parent != null && LOGGER.isTraceEnabled())
+        if (parent != null && LOGGER.isTraceEnabled()) {
             LOGGER.trace("PolicySet: " + policy.getPolicyId() + "Parent PolicySet: " + parent.getPolicySetId()
                     + " Version: " + parent.getVersion());
+        }
 
-        if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty())
+        if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) {
             htmlOut.println("</ol>");
+        }
 
         htmlOut.println("<p></p>");
         return super.onPostVisitPolicy(parent, policy);
     }
 
     public void policy(PolicyType policy) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace("Policy: " + policy.getPolicyId());
+        }
 
         String combiningAlgorithm = "-";
         String id = "-";
         String version = "-";
 
-        if (policy.getRuleCombiningAlgId() != null)
+        if (policy.getRuleCombiningAlgId() != null) {
             combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":");
+        }
 
-        if (policy.getPolicyId() != null)
+        if (policy.getPolicyId() != null) {
             id = extractLastIdentifier(policy.getPolicyId(), ":");
+        }
 
-        if (policy.getVersion() != null)
+        if (policy.getVersion() != null) {
             version = policy.getVersion();
+        }
 
         htmlOut.println("<li><b>Policy ID</b>: <i>" + id + "</i>  (v" + version + ") " + "</li>");
 
@@ -459,8 +498,7 @@ class HtmlProcessor extends SimpleCallback {
             htmlOut.print("<p>");
             htmlOut.print("This policy applies to requests with attributes ");
 
-            List<AnyOfType> anyOf_s = policy.getTarget().getAnyOf();
-            target(anyOf_s);
+            target(policy.getTarget().getAnyOf());
             htmlOut.println(".</p>");
         }
 
@@ -478,11 +516,13 @@ class HtmlProcessor extends SimpleCallback {
 
     @Override
     public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace("Rule: " + rule.getRuleId());
+        }
 
-        if (parent != null && LOGGER.isTraceEnabled())
+        if (parent != null && LOGGER.isTraceEnabled()) {
             LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion());
+        }
 
         String description = rule.getDescription();
         if (description != null && LOGGER.isTraceEnabled()) {
@@ -496,23 +536,21 @@ class HtmlProcessor extends SimpleCallback {
 
     @Override
     public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) {
-        if (LOGGER.isTraceEnabled())
-            LOGGER.trace("Rule: " + rule.getRuleId());
 
-        if (parent != null && LOGGER.isTraceEnabled())
+        if (parent != null && LOGGER.isTraceEnabled()) {
             LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion());
+        }
 
         return super.onPostVisitRule(parent, rule);
     }
 
     public void rule(RuleType rule) {
-        if (LOGGER.isTraceEnabled())
-            LOGGER.trace("Rule: " + rule.getRuleId());
 
         String id = "-";
 
-        if (rule.getRuleId() != null)
+        if (rule.getRuleId() != null) {
             id = extractLastIdentifier(rule.getRuleId(), ":");
+        }
 
         htmlOut.println("<li><b>Rule ID</b>: <i>" + id + "</i></li>");
 
@@ -524,9 +562,8 @@ class HtmlProcessor extends SimpleCallback {
         if (rule.getTarget() == null || rule.getTarget().getAnyOf() == null || rule.getTarget().getAnyOf().isEmpty()) {
             htmlOut.print(" for all requests");
         } else {
-            List<AnyOfType> anyOf_s = rule.getTarget().getAnyOf();
             htmlOut.print(" for requests with attributes ");
-            target(anyOf_s);
+            target(rule.getTarget().getAnyOf());
         }
 
         if (rule.getCondition() != null) {
@@ -538,8 +575,9 @@ class HtmlProcessor extends SimpleCallback {
 
         if (rule.getAdviceExpressions() != null) {
             advice(rule.getAdviceExpressions());
-            if (rule.getObligationExpressions() != null)
+            if (rule.getObligationExpressions() != null) {
                 htmlOut.println(" and ");
+            }
         }
 
         if (rule.getObligationExpressions() != null) {
@@ -550,8 +588,9 @@ class HtmlProcessor extends SimpleCallback {
     }
 
     private void advice(AdviceExpressionsType adviceExpressions) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace(ENTER);
+        }
 
         List<AdviceExpressionType> ae = adviceExpressions.getAdviceExpression();
         for (AdviceExpressionType expression : ae) {
@@ -567,8 +606,9 @@ class HtmlProcessor extends SimpleCallback {
     }
 
     private void obligation(ObligationExpressionsType obligationExpressions) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace(ENTER);
+        }
 
         List<ObligationExpressionType> oe = obligationExpressions.getObligationExpression();
         for (ObligationExpressionType expression : oe) {
@@ -584,11 +624,14 @@ class HtmlProcessor extends SimpleCallback {
     }
 
     /**
-     * @param assignments
+     * processAttributeAssignments.
+     *
+     * @param assignments List of AttributeAssignmentExpressionType
      */
     private void processAttributeAssignments(List<AttributeAssignmentExpressionType> assignments) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace(ENTER);
+        }
 
         for (AttributeAssignmentExpressionType assignment : assignments) {
             String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") + ":"
@@ -618,8 +661,9 @@ class HtmlProcessor extends SimpleCallback {
                 for (Object c : avt.getContent()) {
                     countContent++;
                     htmlOut.print("<i>" + c + "</i>");
-                    if (countContent < numContent)
+                    if (countContent < numContent) {
                         htmlOut.print(" or ");
+                    }
                 }
                 htmlOut.println("</li>");
             } else if (assignmentObject instanceof AttributeDesignatorType
@@ -632,118 +676,118 @@ class HtmlProcessor extends SimpleCallback {
     }
 
     /**
-     * 
-     * @param anyOfList
+     * target.
+     *
+     * @param anyOfList List of AnyOfType's
      */
     public void target(List<AnyOfType> anyOfList) {
-        if (LOGGER.isTraceEnabled())
+        if (LOGGER.isTraceEnabled()) {
             LOGGER.trace(ENTER);
+        }
 
-        if (anyOfList != null) {
-            Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
-            StringBuilder targetInHuman = new StringBuilder();
-            while (iterAnyOf.hasNext()) {
-                AnyOfType anyOf = iterAnyOf.next();
-                List<AllOfType> allOfList = anyOf.getAllOf();
-                if (allOfList != null) {
-                    Iterator<AllOfType> iterAllOf = allOfList.iterator();
-                    while (iterAllOf.hasNext()) {
-                        AllOfType allOf = iterAllOf.next();
-                        List<MatchType> matchList = allOf.getMatch();
-                        if (matchList != null) {
-                            Iterator<MatchType> iterMatch = matchList.iterator();
-                            if (matchList.size() > 1)
-                                targetInHuman.append("(");
-                            while (iterMatch.hasNext()) {
-                                MatchType match = iterMatch.next();
-                                //
-                                // Finally down to the actual attribute
-                                //
-                                StdAttribute attribute = null;
-                                AttributeValueType value = match.getAttributeValue();
-                                String attributeDataType;
-                                if (match.getAttributeDesignator() != null && value != null) {
-                                    AttributeDesignatorType designator = match.getAttributeDesignator();
-                                    attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()),
-                                            new IdentifierImpl(designator.getAttributeId()),
-                                            new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()),
-                                                    value.getContent()),
-                                            designator.getIssuer(), false);
-                                    attributeDataType = designator.getDataType();
-                                } else if (match.getAttributeSelector() != null && value != null) {
-                                    AttributeSelectorType selector = match.getAttributeSelector();
-                                    attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()),
-                                            new IdentifierImpl(selector.getContextSelectorId()),
-                                            new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()),
-                                                    value.getContent()),
-                                            null, false);
-                                    attributeDataType = selector.getDataType();
-                                } else {
-                                    LOGGER.warn("NULL designator/selector or value for match.");
-                                    attributeDataType = "NA";
-                                }
+        if (anyOfList == null) {
+            return;
+        }
+        Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+        StringBuilder targetInHuman = new StringBuilder();
+        while (iterAnyOf.hasNext()) {
+            AnyOfType anyOf = iterAnyOf.next();
+            List<AllOfType> allOfList = anyOf.getAllOf();
+            Iterator<AllOfType> iterAllOf = allOfList.iterator();
+            while (iterAllOf.hasNext()) {
+                AllOfType allOf = iterAllOf.next();
+                List<MatchType> matchList = allOf.getMatch();
+                Iterator<MatchType> iterMatch = matchList.iterator();
+                if (matchList.size() > 1) {
+                    targetInHuman.append("(");
+                }
+                while (iterMatch.hasNext()) {
+                    MatchType match = iterMatch.next();
+                    //
+                    // Finally down to the actual attribute
+                    //
+                    StdAttribute attribute = null;
+                    AttributeValueType value = match.getAttributeValue();
+                    String attributeDataType;
+                    if (match.getAttributeDesignator() != null && value != null) {
+                        AttributeDesignatorType designator = match.getAttributeDesignator();
+                        attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()),
+                                new IdentifierImpl(designator.getAttributeId()),
+                                new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()),
+                                        value.getContent()),
+                                designator.getIssuer(), false);
+                        attributeDataType = designator.getDataType();
+                    } else if (match.getAttributeSelector() != null && value != null) {
+                        AttributeSelectorType selector = match.getAttributeSelector();
+                        attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()),
+                                new IdentifierImpl(selector.getContextSelectorId()),
+                                new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()),
+                                        value.getContent()),
+                                null, false);
+                        attributeDataType = selector.getDataType();
+                    } else {
+                        LOGGER.warn("NULL designator/selector or value for match.");
+                        attributeDataType = "NA";
+                    }
 
-                                String functionName = getHumanFunction(match.getMatchId());
-                                if (attribute != null) {
-                                    String succintIdentifier = extractLastIdentifier(
-                                            attribute.getCategory().stringValue(), ":") + ":"
-                                            + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":");
-                                    AttributeIdentifiers ai =
-                                            new AttributeIdentifiers(attribute.getCategory().stringValue(),
-                                                    attributeDataType, attribute.getAttributeId().stringValue());
-                                    this.attributeIdentifiersMap.put(succintIdentifier, ai);
-
-                                    targetInHuman.append("<i><a href=\"#" + succintIdentifier + "\">"
-                                            + succintIdentifier + "</a></i> " + functionName + " ");
-
-                                    int numAttributes = attribute.getValues().size();
-                                    int count = 0;
-                                    for (AttributeValue<?> v : attribute.getValues()) {
-                                        count++;
-                                        if (v.getValue() instanceof Collection<?>) {
-                                            Collection<?> value_s = (Collection<?>) v.getValue();
-                                            int numValues = value_s.size();
-                                            int countValues = 0;
-                                            for (Object o : value_s) {
-                                                countValues++;
-                                                targetInHuman.append(" <I>" + o + "</I>");
-                                                if (countValues < numValues) {
-                                                    targetInHuman.append(", or");
-                                                }
-                                            }
-                                        } else {
-                                            targetInHuman.append(" <I>" + v.getValue() + "</I>");
-                                            if (count < numAttributes) {
-                                                targetInHuman.append(", or ");
-                                            }
-                                        }
+                    String functionName = getHumanFunction(match.getMatchId());
+                    if (attribute != null) {
+                        String succintIdentifier = extractLastIdentifier(
+                                attribute.getCategory().stringValue(), ":") + ":"
+                                + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":");
+                        AttributeIdentifiers ai =
+                                new AttributeIdentifiers(attribute.getCategory().stringValue(),
+                                        attributeDataType, attribute.getAttributeId().stringValue());
+                        this.attributeIdentifiersMap.put(succintIdentifier, ai);
+
+                        targetInHuman.append("<i><a href=\"#" + succintIdentifier + "\">"
+                                + succintIdentifier + "</a></i> " + functionName + " ");
+
+                        int numAttributes = attribute.getValues().size();
+                        int count = 0;
+                        for (AttributeValue<?> v : attribute.getValues()) {
+                            count++;
+                            if (v.getValue() instanceof Collection<?>) {
+                                Collection<?> collectionValues = (Collection<?>) v.getValue();
+                                int numValues = collectionValues.size();
+                                int countValues = 0;
+                                for (Object o : collectionValues) {
+                                    countValues++;
+                                    targetInHuman.append(" <I>" + o + "</I>");
+                                    if (countValues < numValues) {
+                                        targetInHuman.append(", or");
                                     }
                                 }
-
-                                if (iterMatch.hasNext()) {
-                                    targetInHuman.append(" and ");
+                            } else {
+                                targetInHuman.append(" <I>" + v.getValue() + "</I>");
+                                if (count < numAttributes) {
+                                    targetInHuman.append(", or ");
                                 }
-                            } // end iterMatch
-                            if (matchList.size() > 1) {
-                                targetInHuman.append(")");
                             }
                         }
-                        if (iterAllOf.hasNext()) {
-                            targetInHuman.append(" or ");
-                        }
-                    } // end iterAllOf
-                }
-                if (iterAnyOf.hasNext()) {
-                    targetInHuman = new StringBuilder();
-                    targetInHuman.append("(" + targetInHuman + ")" + " or ");
-                } else {
-                    if (anyOfList.size() > 1) {
-                        targetInHuman.append(")");
                     }
+
+                    if (iterMatch.hasNext()) {
+                        targetInHuman.append(" and ");
+                    }
+                } // end iterMatch
+                if (matchList.size() > 1) {
+                    targetInHuman.append(")");
                 }
-            } // end iterAnyOf
-            htmlOut.println(targetInHuman);
+            }
+            if (iterAllOf.hasNext()) {
+                targetInHuman.append(" or ");
+            }
+        } // end iterAllOf
+        if (iterAnyOf.hasNext()) {
+            targetInHuman = new StringBuilder();
+            targetInHuman.append("(" + targetInHuman + ")" + " or ");
+        } else {
+            if (anyOfList.size() > 1) {
+                targetInHuman.append(")");
+            }
         }
+        htmlOut.println(targetInHuman);
     }
 
     private String getHumanFunction(String matchId) {
@@ -813,12 +857,12 @@ class HtmlProcessor extends SimpleCallback {
                 } else {
                     StringBuilder forResult = new StringBuilder();
                     for (JAXBElement<?> e : exps) {
-                        Object v = e.getValue();
+                        Object theValue = e.getValue();
                         if (LOGGER.isDebugEnabled()) {
-                            LOGGER.debug("one-and-only children: " + v);
+                            LOGGER.debug("one-and-only children: " + theValue);
                         }
-                        if (v != null) {
-                            forResult.append(stringifyExpression(v));
+                        if (theValue != null) {
+                            forResult.append(stringifyExpression(theValue));
                         }
                     }
                     return forResult.toString();
@@ -838,8 +882,8 @@ class HtmlProcessor extends SimpleCallback {
                 }
                 StringBuilder applySubresult = new StringBuilder();
                 for (JAXBElement<?> e : apply.getExpression()) {
-                    Object v = e.getValue();
-                    if (v != null) {
+                    Object theValue = e.getValue();
+                    if (theValue != null) {
                         applySubresult.append(this.stringifyExpression(e.getValue()));
                     }
                 }
@@ -904,11 +948,12 @@ class HtmlProcessor extends SimpleCallback {
         if (expression instanceof AttributeValueType) {
             AttributeValueType avt = (AttributeValueType) expression;
             List<Object> content = avt.getContent();
-            StringBuilder value_s = new StringBuilder();
+            StringBuilder stringValue = new StringBuilder(" ");
             for (Object o : content) {
-                value_s.append(" " + o.toString());
+                stringValue.append(" ");
+                stringValue.append(o.toString());
             }
-            return " " + value_s.toString();
+            return stringValue.toString();
         }
         if (expression instanceof VariableReferenceType) {
             //
index 9f89ea0..666923b 100644 (file)
@@ -8,9 +8,9 @@
  * 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.
@@ -27,23 +27,19 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
-
 import javax.xml.bind.JAXBElement;
-
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-
 import org.onap.policy.common.logging.flexlogger.FlexLogger;
 import org.onap.policy.common.logging.flexlogger.Logger;
 import org.onap.policy.rest.adapter.PolicyRestAdapter;
@@ -66,41 +62,47 @@ public class ActionPolicyController extends RestrictedBaseController {
         // Default Constructor
     }
 
+    /**
+     * prePopulateActionPolicyData.
+     *
+     * @param policyAdapter PolicyRestAdapter
+     */
     public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter) {
         ruleAlgorithmList = new ArrayList<>();
         performer.put("PDP", "PDPAction");
         performer.put("PEP", "PEPAction");
 
-        if (policyAdapter.getPolicyData() instanceof PolicyType) {
-            PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+        if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+            return;
+        }
+        PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
 
-            // 1. Set policy-name, policy-filename and description to Policy Adapter
-            setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy);
+        // 1. Set policy-name, policy-filename and description to Policy Adapter
+        setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy);
 
-            // 2a. Get the target data under policy for Action.
-            TargetType target = policy.getTarget();
-            if (target == null) {
-                return;
-            }
+        // 2a. Get the target data under policy for Action.
+        TargetType target = policy.getTarget();
+        if (target == null) {
+            return;
+        }
 
-            // 2b. Set attributes to Policy Adapter
-            setPolicyAdapterAttributes(policyAdapter, target.getAnyOf());
+        // 2b. Set attributes to Policy Adapter
+        setPolicyAdapterAttributes(policyAdapter, target.getAnyOf());
 
-            List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
-            // Under rule we have Condition and obligation.
-            for (Object o : ruleList) {
-                if (!(o instanceof RuleType)) {
-                    continue;
-                }
-                // 3. Set rule-algorithm choices to Policy Adapter
-                setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o);
+        List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+        // Under rule we have Condition and obligation.
+        for (Object o : ruleList) {
+            if (!(o instanceof RuleType)) {
+                continue;
+            }
+            // 3. Set rule-algorithm choices to Policy Adapter
+            setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o);
 
-                // 4a. Get the Obligation data under the rule for Form elements.
-                ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions();
+            // 4a. Get the Obligation data under the rule for Form elements.
+            ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions();
 
-                // 4b. Set action attribute-value and action-performer to Policy Adapter
-                setPolicyAdapterActionData(policyAdapter, obligations);
-            }
+            // 4b. Set action attribute-value and action-performer to Policy Adapter
+            setPolicyAdapterActionData(policyAdapter, obligations);
         }
     }
 
@@ -109,19 +111,20 @@ public class ActionPolicyController extends RestrictedBaseController {
             return;
         }
         // Under the obligationExpressions we have obligationExpression.
-        List<ObligationExpressionType> obligationList = obligations.getObligationExpression();
-        if (obligationList == null) {
-            return;
-        }
-        for (ObligationExpressionType obligation : obligationList) {
+        // NOTE: getObligationExpression() will never return NULL.
+        //
+        for (ObligationExpressionType obligation : obligations.getObligationExpression()) {
             policyAdapter.setActionAttributeValue(obligation.getObligationId());
             // Under the obligationExpression we have attributeAssignmentExpression.
-            List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList =
-                    obligation.getAttributeAssignmentExpression();
-            if (attributeAssignmentExpressionList == null) {
-                continue;
-            }
-            for (AttributeAssignmentExpressionType attributeAssignmentExpression : attributeAssignmentExpressionList) {
+            //
+            // NOTE: obligation.getAttributeAssignmentExpression() will NEVER be null
+            // It will always return a list.
+            //
+            for (AttributeAssignmentExpressionType attributeAssignmentExpression :
+                obligation.getAttributeAssignmentExpression()) {
+                //
+                //
+                //
                 String attributeID = attributeAssignmentExpression.getAttributeId();
                 AttributeValueType attributeValue =
                         (AttributeValueType) attributeAssignmentExpression.getExpression().getValue();
@@ -152,11 +155,10 @@ public class ActionPolicyController extends RestrictedBaseController {
         policyAdapter.setPolicyDescription(description);
     }
 
-    private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType o) {
-        ConditionType condition = o.getCondition();
-        if (condition != null) {
+    private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType ruleType) {
+        if (ruleType.getCondition() != null) {
             int index = 0;
-            ApplyType actionApply = (ApplyType) condition.getExpression().getValue();
+            ApplyType actionApply = (ApplyType) ruleType.getCondition().getExpression().getValue();
             ruleAlgorithmTracker = new LinkedList<>();
             // Populating Rule Algorithms starting from compound.
             prePopulateCompoundRuleAlgorithm(index, actionApply);
@@ -166,36 +168,43 @@ public class ActionPolicyController extends RestrictedBaseController {
 
     private void setPolicyAdapterAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
         List<Object> attributeList = new ArrayList<>();
-        if (anyOfList == null) {
-            return;
-        }
+        //
+        // NOTE: If using xacml3 code and doing a getAnyOf(), the anyOfList will
+        // NEVER be null as that code will create it if it is null.
+        //
+        // Remove the null check as its impossible to cover it.
+        //
         // under target we have AnyOFType
         for (AnyOfType anyOf : anyOfList) {
             // Under AntOfType we have AllOfType
+            //
+            // NOTE: This will NEVER be null as the method call in the
+            // previous line getAllOf() will never return a null. It
+            // always creates it if its empty.
+            //
             List<AllOfType> allOfList = anyOf.getAllOf();
-            if (allOfList == null) {
-                continue;
-            }
             // Under AllOfType we have Match.
             for (AllOfType allOfType : allOfList) {
-                List<MatchType> matchList = allOfType.getMatch();
-                if (matchList != null) {
-                    //
-                    // Under the match we have attributeValue and
-                    // attributeDesignator. So,finally down to the actual attribute.
-                    //
-                    // Component attributes are saved under Target here we are fetching them back.
-                    // One row is default so we are not adding dynamic component at index 0.
-                    matchList.forEach(match -> {
-                        AttributeValueType attributeValue = match.getAttributeValue();
-                        String value = (String) attributeValue.getContent().get(0);
-                        AttributeDesignatorType designator = match.getAttributeDesignator();
-                        String attributeId = designator.getAttributeId();
-                        Map<String, String> attribute = new HashMap<>();
-                        attribute.put("key", attributeId);
-                        attribute.put("value", value);
-                        attributeList.add(attribute);
-                    });
+                //
+                // NOTE: allOfType.getMatch() will NEVER be null as the method
+                // call getMatch will always return something. If its
+                // not there it will create it.
+                //
+                //
+                // Under the match we have attributeValue and
+                // attributeDesignator. So,finally down to the actual attribute.
+                //
+                // Component attributes are saved under Target here we are fetching them back.
+                // One row is default so we are not adding dynamic component at index 0.
+                for (MatchType match : allOfType.getMatch()) {
+                    AttributeValueType attributeValue = match.getAttributeValue();
+                    String value = (String) attributeValue.getContent().get(0);
+                    AttributeDesignatorType designator = match.getAttributeDesignator();
+                    String attributeId = designator.getAttributeId();
+                    Map<String, String> attribute = new HashMap<>();
+                    attribute.put("key", attributeId);
+                    attribute.put("value", value);
+                    attributeList.add(attribute);
                 }
                 policyAdapter.setAttributes(attributeList);
             }
@@ -211,41 +220,41 @@ public class ActionPolicyController extends RestrictedBaseController {
                 LOGGER.debug("Prepopulating rule algoirthm: " + index);
             }
             // Check to see if Attribute Value exists, if yes then it is not a compound rule
-            if (jaxbElement.getValue() instanceof AttributeValueType) {
+            if (jaxbElement.getValue() instanceof AttributeValueType
+                    || jaxbElement.getValue() instanceof AttributeDesignatorType) {
                 prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes);
                 ruleAlgorithmTracker.addLast(index);
                 isCompoundRule = false;
                 index++;
             }
         }
-        if (isCompoundRule) {
-            // As it's compound rule, Get the Apply types
-            for (JAXBElement<?> jaxbElement : jaxbActionTypes) {
-                ApplyType innerActionApply = (ApplyType) jaxbElement.getValue();
-                index = prePopulateCompoundRuleAlgorithm(index, innerActionApply);
-            }
-            // Populate combo box
-            if (LOGGER.isDebugEnabled()) {
-                LOGGER.debug("Prepopulating Compound rule algorithm: " + index);
-            }
-            Map<String, String> rule = new HashMap<>();
-            for (String key : PolicyController.getDropDownMap().keySet()) {
-                String keyValue = PolicyController.getDropDownMap().get(key);
-                if (keyValue.equals(actionApply.getFunctionId())) {
-                    rule.put("dynamicRuleAlgorithmCombo", key);
-                }
+        if (!isCompoundRule) {
+            return index;
+        }
+        // As it's compound rule, Get the Apply types
+        for (JAXBElement<?> jaxbElement : jaxbActionTypes) {
+            ApplyType innerActionApply = (ApplyType) jaxbElement.getValue();
+            index = prePopulateCompoundRuleAlgorithm(index, innerActionApply);
+        }
+        // Populate combo box
+        if (LOGGER.isDebugEnabled()) {
+            LOGGER.debug("Prepopulating Compound rule algorithm: " + index);
+        }
+        Map<String, String> rule = new HashMap<>();
+        for ( Entry<String, String> entrySet : PolicyController.getDropDownMap().entrySet()) {
+            if (entrySet.getValue().equals(actionApply.getFunctionId())) {
+                rule.put("dynamicRuleAlgorithmCombo", entrySet.getKey());
             }
-            rule.put("id", "A" + (index + 1));
-            // Populate Key and values for Compound Rule
-            rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1));
-            ruleAlgorithmTracker.removeLast();
-            rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1));
-            ruleAlgorithmTracker.removeLast();
-            ruleAlgorithmTracker.addLast(index);
-            ruleAlgorithmList.add(rule);
-            index++;
         }
-        return index;
+        rule.put("id", "A" + (index + 1));
+        // Populate Key and values for Compound Rule
+        rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1));
+        ruleAlgorithmTracker.removeLast();
+        rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1));
+        ruleAlgorithmTracker.removeLast();
+        ruleAlgorithmTracker.addLast(index);
+        ruleAlgorithmList.add(rule);
+        return ++index;
     }
 
     private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List<JAXBElement<?>> jaxbActionTypes) {
@@ -279,11 +288,20 @@ public class ActionPolicyController extends RestrictedBaseController {
             String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
             ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue);
 
-            ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue();
-            List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
-            AttributeDesignatorType attributeDesignator =
-                    (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
-            ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId());
+            //
+            // This is making a BIG assumption here that there exists an innerApply. This IF
+            // statement was added to support JUnit code coverage. For lack of any example of what
+            // this policy should actually look like.
+            //
+            if (jaxbActionTypes.size() > 1) {
+                ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue();
+                List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
+                if (! jaxbInnerActionTypes.isEmpty()) {
+                    AttributeDesignatorType attributeDesignator =
+                        (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
+                    ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId());
+                }
+            }
         }
         ruleAlgorithmList.add(ruleMap);
     }
index 92f125a..e919096 100644 (file)
@@ -26,7 +26,6 @@ import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 
 import java.io.IOException;
-import java.io.PrintWriter;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -74,6 +73,12 @@ public class AdminTabController extends RestrictedBaseController {
         AdminTabController.commonClassDao = commonClassDao;
     }
 
+    /**
+     * getAdminTabEntityData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/get_LockDownData"},
             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
@@ -83,51 +88,51 @@ public class AdminTabController extends RestrictedBaseController {
             Map<String, Object> model = new HashMap<>();
             ObjectMapper mapper = new ObjectMapper();
             model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             LOGGER.error("Exception Occured" + e);
         }
     }
 
+    /**
+     * saveAdminTabLockdownValue.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @return ModelAndView object
+     * @throws IOException IOException
+     */
     @RequestMapping(
             value = {"/adminTabController/save_LockDownValue.htm"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
     public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response)
             throws IOException {
+        response.setCharacterEncoding(CHARACTER_ENCODING);
+        request.setCharacterEncoding(CHARACTER_ENCODING);
         try {
             ObjectMapper mapper = new ObjectMapper();
             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
             String userId = UserUtils.getUserSession(request).getOrgUserId();
             LOGGER.info(
-                    "****************************************Logging UserID for Application Lockdown Function*****************************************");
+                    "********************Logging UserID for Application Lockdown Function**************************");
             LOGGER.info("UserId:  " + userId);
             LOGGER.info(
-                    "*********************************************************************************************************************************");
+                    "**********************************************************************************************");
             JsonNode root = mapper.readTree(request.getReader());
             GlobalRoleSettings globalRole =
                     mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class);
             globalRole.setRole("super-admin");
             commonClassDao.update(globalRole);
 
-            response.setCharacterEncoding(CHARACTER_ENCODING);
             response.setContentType("application / json");
-            request.setCharacterEncoding(CHARACTER_ENCODING);
 
-            PrintWriter out = response.getWriter();
             String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class));
-            JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
 
-            out.write(j.toString());
-
-            return null;
+            response.getWriter().write(new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString
+                    + "}").toString());
         } catch (Exception e) {
             LOGGER.error("Exception Occured" + e);
-            response.setCharacterEncoding(CHARACTER_ENCODING);
-            request.setCharacterEncoding(CHARACTER_ENCODING);
-            PrintWriter out = response.getWriter();
-            out.write(PolicyUtils.CATCH_EXCEPTION);
+            response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
         }
         return null;
     }
index ca62d82..b5e17f2 100644 (file)
@@ -31,8 +31,6 @@ import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
-import java.io.PrintWriter;
-import java.net.URI;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -99,6 +97,9 @@ public class AutoPushController extends RestrictedBaseController {
         this.policyController = policyController;
     }
 
+    /**
+     * refreshGroups.
+     */
     public synchronized void refreshGroups() {
         synchronized (this.groups) {
             this.groups.clear();
@@ -124,6 +125,12 @@ public class AutoPushController extends RestrictedBaseController {
         return scopes;
     }
 
+    /**
+     * getPolicyGroupContainerData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/get_AutoPushPoliciesContainerData"},
             method = {RequestMethod.GET},
@@ -169,18 +176,25 @@ public class AutoPushController extends RestrictedBaseController {
             ObjectMapper mapper = new ObjectMapper();
             model.put("policydatas", mapper.writeValueAsString(data));
             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(msg).toString());
         } catch (Exception e) {
             logger.error("Exception Occurred" + e);
         }
     }
 
+    /**
+     * pushPolicyToPDPGroup.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @return ModelAndView
+     * @throws IOException IOException
+     */
     @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
     public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
             throws IOException {
         try {
-            ArrayList<Object> selectedPDPS = new ArrayList<>();
+            ArrayList<Object> selectedPdps = new ArrayList<>();
             ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
             PolicyController controller = getPolicyControllerInstance();
             this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
@@ -191,17 +205,17 @@ public class AutoPushController extends RestrictedBaseController {
 
             String userId = UserUtils.getUserSession(request).getOrgUserId();
             logger.info(
-                    "****************************************Logging UserID while Pushing  Policy to PDP Group*****************************************");
+                    "**********************Logging UserID while Pushing  Policy to PDP Group***********************");
             logger.info("UserId:  " + userId + "Push Policy Data:  " + root.get("pushTabData").toString());
             logger.info(
-                    "***********************************************************************************************************************************");
+                    "**********************************************************************************************");
 
             AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
             for (Object pdpGroupId : adapter.getPdpDatas()) {
-                LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>) pdpGroupId;
+                LinkedHashMap<?, ?> selectedPdp = (LinkedHashMap<?, ?>) pdpGroupId;
                 for (OnapPDPGroup pdpGroup : this.groups) {
-                    if (pdpGroup.getId().equals(selectedPDP.get("id"))) {
-                        selectedPDPS.add(pdpGroup);
+                    if (pdpGroup.getId().equals(selectedPdp.get("id"))) {
+                        selectedPdps.add(pdpGroup);
                     }
                 }
             }
@@ -213,7 +227,7 @@ public class AutoPushController extends RestrictedBaseController {
                 selectedPoliciesInUI.add(policyName);
             }
 
-            for (Object pdpDestinationGroupId : selectedPDPS) {
+            for (Object pdpDestinationGroupId : selectedPdps) {
                 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
                 Set<PDPPolicy> selectedPolicies = new HashSet<>();
                 for (String policyId : selectedPoliciesInUI) {
@@ -259,10 +273,9 @@ public class AutoPushController extends RestrictedBaseController {
                     BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
                     bw.write(policyEntity.getPolicyData());
                     bw.close();
-                    URI selectedURI = temp.toURI();
                     try {
                         // Create the policy
-                        selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
+                        selectedPolicy = new StdPDPPolicy(name, true, id, temp.toURI());
                     } catch (IOException e) {
                         logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
                     }
@@ -325,27 +338,22 @@ public class AutoPushController extends RestrictedBaseController {
                 response.setContentType("application / json");
                 request.setCharacterEncoding(UTF8);
 
-                PrintWriter out = response.getWriter();
                 refreshGroups();
-                JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
-                JSONObject j = new JSONObject(msg);
-                out.write(j.toString());
-                //
-                // Why is this here? This defeats the purpose of the loop??
-                // Sonar says to remove it or make it conditional
-                //
-                return null;
+                response.getWriter().write(new JSONObject(
+                        new JsonMessage(mapper.writeValueAsString(groups))).toString());
             }
         } catch (Exception e) {
             response.setCharacterEncoding(UTF8);
             request.setCharacterEncoding(UTF8);
-            PrintWriter out = response.getWriter();
             logger.error(e);
-            out.write(PolicyUtils.CATCH_EXCEPTION);
+            response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
         }
         return null;
     }
 
+    /**
+     * removePDPGroup.
+     */
     @SuppressWarnings("unchecked")
     @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
     public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
@@ -355,16 +363,16 @@ public class AutoPushController extends RestrictedBaseController {
             ObjectMapper mapper = new ObjectMapper();
             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
             JsonNode root = mapper.readTree(request.getReader());
-            StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
-            JsonNode removePolicyData = root.get("data");
+            final StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
+            final JsonNode removePolicyData = root.get("data");
 
             String userId = UserUtils.getUserSession(request).getOrgUserId();
             logger.info(
-                    "****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
+                    "**********************Logging UserID while Removing Policy from PDP Group*********************");
             logger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("activePdpGroup").toString()
                     + "Remove Policy Data: " + root.get("data"));
             logger.info(
-                    "***********************************************************************************************************************************");
+                    "**********************************************************************************************");
 
             policyContainer = new PDPPolicyContainer(group);
             if (removePolicyData.size() > 0) {
@@ -386,20 +394,13 @@ public class AutoPushController extends RestrictedBaseController {
             response.setContentType("application / json");
             request.setCharacterEncoding(UTF8);
 
-            PrintWriter out = response.getWriter();
             refreshGroups();
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
-            JSONObject j = new JSONObject(msg);
-
-            out.write(j.toString());
-
-            return null;
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
         } catch (Exception e) {
             response.setCharacterEncoding(UTF8);
             request.setCharacterEncoding(UTF8);
-            PrintWriter out = response.getWriter();
             logger.error(e);
-            out.write(PolicyUtils.CATCH_EXCEPTION);
+            response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
         }
         return null;
     }
index 33b7803..1adeb6d 100644 (file)
@@ -26,7 +26,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 
-import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
@@ -104,6 +103,12 @@ public class CreateBRMSParamController extends RestrictedBaseController {
     private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
     private static String string = "String";
 
+    /**
+     * getBRMSParamPolicyRuleData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(value = {"/policyController/getBRMSTemplateData.htm"}, method = {RequestMethod.POST})
     public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) {
         try {
@@ -117,10 +122,8 @@ public class CreateBRMSParamController extends RestrictedBaseController {
             response.setContentType(PolicyController.getContenttype());
             request.setCharacterEncoding(PolicyController.getCharacterencoding());
 
-            PrintWriter out = response.getWriter();
-            String responseString = mapper.writeValueAsString(dynamicLayoutMap);
-            JSONObject j = new JSONObject("{policyData: " + responseString + "}");
-            out.write(j.toString());
+            response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(dynamicLayoutMap)
+                + "}").toString());
         } catch (Exception e) {
             policyLogger.error("Exception Occured while getting BRMS Rule data", e);
         }
@@ -129,8 +132,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
     private String findRule(String ruleTemplate) {
         List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate);
         if (CollectionUtils.isNotEmpty(datas)) {
-            BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0);
-            return bRMSParamTemplate.getRule();
+            return ((BRMSParamTemplate) datas.get(0)).getRule();
         }
         return null;
     }
@@ -249,48 +251,49 @@ public class CreateBRMSParamController extends RestrictedBaseController {
      */
     public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
         dynamicLayoutMap = new HashMap<>();
-        if (policyAdapter.getPolicyData() instanceof PolicyType) {
-            PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
-            policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-            // policy name value is the policy name without any prefix and
-            // Extensions.
-            String policyNameValue =
-                    policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
-            if (policyLogger.isDebugEnabled()) {
-                policyLogger
-                        .debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
-            }
-            policyAdapter.setPolicyName(policyNameValue);
-            String description;
-            try {
-                description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
-            } catch (Exception e) {
-                policyLogger.info("Error getting description: " + e);
-                description = policy.getDescription();
-            }
-            policyAdapter.setPolicyDescription(description);
-            setDataAdapterFromAdviceExpressions(policy, policyAdapter);
+        if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+            return;
+        }
+        PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+        policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+        // policy name value is the policy name without any prefix and
+        // Extensions.
+        String policyNameValue =
+                policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
+        if (policyLogger.isDebugEnabled()) {
+            policyLogger
+                    .debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
+        }
+        policyAdapter.setPolicyName(policyNameValue);
+        String description;
+        try {
+            description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+        } catch (Exception e) {
+            policyLogger.info("Error getting description: " + e);
+            description = policy.getDescription();
+        }
+        policyAdapter.setPolicyDescription(description);
+        setDataAdapterFromAdviceExpressions(policy, policyAdapter);
 
-            // Generate Param UI
-            try {
-                paramUIGenerate(policyAdapter, entity);
-            } catch (Exception e) {
-                policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
-            }
+        // Generate Param UI
+        try {
+            paramUiGenerate(policyAdapter, entity);
+        } catch (Exception e) {
+            policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
+        }
 
-            // Get the target data under policy.
-            policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
-            if (policyAdapter.getDynamicLayoutMap().size() > 0) {
-                LinkedHashMap<String, String> drlRule = policyAdapter.getDynamicLayoutMap().keySet().stream()
-                        .collect(Collectors.toMap(String::toString,
-                                keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue), (a, b) -> b,
-                                LinkedHashMap::new));
-                policyAdapter.setRuleData(drlRule);
-            }
-            TargetType target = policy.getTarget();
-            if (target != null) {
-                setDataToAdapterFromTarget(target, policyAdapter);
-            }
+        // Get the target data under policy.
+        policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
+        if (policyAdapter.getDynamicLayoutMap().size() > 0) {
+            LinkedHashMap<String, String> drlRule = policyAdapter.getDynamicLayoutMap().keySet().stream()
+                    .collect(Collectors.toMap(String::toString,
+                        keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue), (a, b) -> b,
+                            LinkedHashMap::new));
+            policyAdapter.setRuleData(drlRule);
+        }
+        TargetType target = policy.getTarget();
+        if (target != null) {
+            setDataToAdapterFromTarget(target, policyAdapter);
         }
     }
 
@@ -328,11 +331,10 @@ public class CreateBRMSParamController extends RestrictedBaseController {
 
     private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter) {
         // Under target we have AnyOFType
-        List<AnyOfType> anyOfList = target.getAnyOf();
-        if (anyOfList == null) {
+        if (target.getAnyOf() == null) {
             return;
         }
-        anyOfList.stream().map(AnyOfType::getAllOf).filter(Objects::nonNull).flatMap(Collection::stream)
+        target.getAnyOf().stream().map(AnyOfType::getAllOf).filter(Objects::nonNull).flatMap(Collection::stream)
                 .forEach(allOf -> setDataToAdapterFromMatchList(allOf.getMatch(), policyAdapter));
     }
 
@@ -367,7 +369,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
     }
 
     // This method generates the UI from rule configuration
-    private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+    private void paramUiGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
         String data = entity.getConfigurationData().getConfigBody();
         if (data == null) {
             return;
@@ -473,7 +475,12 @@ public class CreateBRMSParamController extends RestrictedBaseController {
         return line;
     }
 
-    // set View Rule
+    /**
+     * setViewRule.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @SuppressWarnings("unchecked")
     @RequestMapping(value = {"/policyController/ViewBRMSParamPolicyRule.htm"}, method = {RequestMethod.POST})
     public void setViewRule(HttpServletRequest request, HttpServletResponse response) {
@@ -492,7 +499,8 @@ public class CreateBRMSParamController extends RestrictedBaseController {
 
             String body = findRule(policyData.getRuleName()) + "\n";
             StringBuilder generatedMetadata = new StringBuilder().append(
-                    "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t ")
+                    "/* Autogenerated Code Please Don't change/remove this comment section. "
+                            + "This is for the UI purpose. \n\t ")
                     .append(brmsTemplateVlaue).append(policyData.getRuleName()).append("%$> \n */ \n");
 
             if (policyData.getDynamicLayoutMap().size() > 0) {
@@ -517,26 +525,22 @@ public class CreateBRMSParamController extends RestrictedBaseController {
             // Finding all the keys in the Map data-structure.
             Set<String> keySet = copyMap.keySet();
             Iterator<String> iterator = keySet.iterator();
-            Pattern p;
-            Matcher m;
             while (iterator.hasNext()) {
                 // Converting the first character of the key into a lower case.
                 String input = iterator.next();
                 String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : "");
                 // Searching for a pattern in the String using the key.
-                p = Pattern.compile("\\$\\{" + output + "\\}");
-                m = p.matcher(body);
+                Pattern pattern = Pattern.compile("\\$\\{" + output + "\\}");
+                Matcher matcher = pattern.matcher(body);
                 // Replacing the value with the inputs provided by the user in the editor.
-                body = m.replaceAll(copyMap.get(input));
+                body = matcher.replaceAll(copyMap.get(input));
             }
             response.setCharacterEncoding("UTF-8");
             response.setContentType("application / json");
             request.setCharacterEncoding("UTF-8");
 
-            PrintWriter out = response.getWriter();
-            String responseString = mapper.writeValueAsString(body);
-            JSONObject j = new JSONObject("{policyData: " + responseString + "}");
-            out.write(j.toString());
+            response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(body)
+                + "}").toString());
         } catch (Exception e) {
             policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
         }
index 9974292..214cb32 100644 (file)
@@ -53,39 +53,39 @@ public class CreateBRMSRawController {
 
     protected PolicyRestAdapter policyAdapter = null;
 
-    @SuppressWarnings("unchecked")
     public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
 
-        if (policyAdapter.getPolicyData() instanceof PolicyType) {
-            PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
-            policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-
-            // Set PolicyAdapter name value
-            setPolicyAdapterNameValue(policyAdapter);
+        if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+            return;
+        }
+        PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+        policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
 
-            // Set PolicyAdapter description.
-            setPolicyAdapterDescription(policyAdapter, policy);
+        // Set PolicyAdapter name value
+        setPolicyAdapterNameValue(policyAdapter);
 
-            // Set PolicyAdapter attributes.
-            setPolicyAdapterAttributes(policyAdapter, policy);
+        // Set PolicyAdapter description.
+        setPolicyAdapterDescription(policyAdapter, policy);
 
-            // Set PolicyAdapter configBodyData
-            policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
+        // Set PolicyAdapter attributes.
+        setPolicyAdapterAttributes(policyAdapter, policy);
 
-            // Get the target data under policy.
-            TargetType target = policy.getTarget();
-            if (target == null) {
-                return;
-            }
-            // Under target we have AnyOFType
-            List<AnyOfType> anyOfList = target.getAnyOf();
-            if (anyOfList == null) {
-                return;
-            }
+        // Set PolicyAdapter configBodyData
+        policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
 
-            // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes
-            setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf());
+        // Get the target data under policy.
+        TargetType target = policy.getTarget();
+        if (target == null) {
+            return;
+        }
+        // Under target we have AnyOFType
+        List<AnyOfType> anyOfList = target.getAnyOf();
+        if (anyOfList == null) {
+            return;
         }
+
+        // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes
+        setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf());
     }
 
     private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
@@ -136,6 +136,7 @@ public class CreateBRMSRawController {
         policyAdapter.setPolicyDescription(description);
     }
 
+    @SuppressWarnings("unchecked")
     private void setPolicyAdapterAttributes(final PolicyRestAdapter policyAdapter, final PolicyType policy) {
         ArrayList<Object> attributeList = new ArrayList<>();
         AdviceExpressionsType expressionTypes =
index f279418..9f19e4c 100644 (file)
@@ -24,7 +24,6 @@ package org.onap.policy.controller;
 import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.ObjectWriter;
 
 import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;
@@ -91,17 +90,24 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
         // Empty constructor
     }
 
+    /**
+     * setDataToPolicyRestAdapter.
+     *
+     * @param policyData PolicyRestAdapter
+     * @param root JsonNode
+     * @return PolicyRestAdapter
+     */
     public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
         try {
             ObjectMapper mapper = new ObjectMapper();
             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-            ClosedLoopFaultTrapDatas trapDatas =
+            final ClosedLoopFaultTrapDatas trapDatas =
                     mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
-            ClosedLoopFaultTrapDatas faultDatas =
+            final ClosedLoopFaultTrapDatas faultDatas =
                     mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
-            ClosedLoopGridJSONData policyJsonData =
-                    mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class);
-            ClosedLoopFaultBody jsonBody = mapper.readValue(
+            final ClosedLoopGridJsonData policyJsonData =
+                    mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJsonData.class);
+            final ClosedLoopFaultBody jsonBody = mapper.readValue(
                     root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
 
             // Build trapSignatureDatas list from faultData
@@ -118,10 +124,10 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
                 triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge()));
                 ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures();
                 if (!trapSignatureDatas.isEmpty()) {
-                    uiTriggerSignatures.setSignatures(getUITriggerSignature(TRAP, trapSignatureDatas.get(0)));
+                    uiTriggerSignatures.setSignatures(getUiTriggerSignature(TRAP, trapSignatureDatas.get(0)));
                     if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) {
                         uiTriggerSignatures
-                                .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures()));
+                                .setConnectSignatures(getUiConnectTraps(policyJsonData.getConnecttriggerSignatures()));
                     }
                 }
                 jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures);
@@ -144,19 +150,17 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
                 faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut()));
                 ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures();
                 if (!faultSignatureDatas.isEmpty()) {
-                    uifaultSignatures.setSignatures(getUITriggerSignature(FAULT, faultSignatureDatas.get(0)));
+                    uifaultSignatures.setSignatures(getUiTriggerSignature(FAULT, faultSignatureDatas.get(0)));
                     if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) {
                         uifaultSignatures.setConnectSignatures(
-                                getUIConnectTraps(policyJsonData.getConnectVerificationSignatures()));
+                                getUiConnectTraps(policyJsonData.getConnectVerificationSignatures()));
                     }
                 }
                 jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures);
                 jsonBody.setVerificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut()));
             }
             jsonBody.setVerificationSignatures(faultSignatures);
-            ObjectWriter om = new ObjectMapper().writer();
-            String json = om.writeValueAsString(jsonBody);
-            policyData.setJsonBody(json);
+            policyData.setJsonBody(new ObjectMapper().writer().writeValueAsString(jsonBody));
 
         } catch (Exception e) {
             policyLogger.error("Exception Occured while setting data to Adapter", e);
@@ -165,7 +169,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
     }
 
     // TODO: Can getResultBody() and getFaultBody() be merged?
-    private String getResultBody(final ClosedLoopGridJSONData policyJsonData, final List<Object> trapSignatureDatas) {
+    private String getResultBody(final ClosedLoopGridJsonData policyJsonData, final List<Object> trapSignatureDatas) {
         StringBuilder resultBody = new StringBuilder();
         if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) {
             resultBody.append("(");
@@ -182,7 +186,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
         return resultBody.toString();
     }
 
-    private String getFaultBody(final ClosedLoopGridJSONData policyJsonData, final List<Object> faultSignatureDatas) {
+    private String getFaultBody(final ClosedLoopGridJsonData policyJsonData, final List<Object> faultSignatureDatas) {
         StringBuilder faultBody = new StringBuilder();
         if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) {
             faultBody.append("(");
@@ -341,7 +345,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
                 attributesStr = attributesStr + "(" + readAttributes(objectList, iy) + ")";
             } catch (NumberFormatException e) {
                 try {
-                    trap1Attrib = getVarbindOID(trap1Attrib);
+                    trap1Attrib = getVarbindOid(trap1Attrib);
                     attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")";
                 } catch (UnsupportedEncodingException e1) {
                     policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e1);
@@ -349,7 +353,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
             }
         } else {
             try {
-                trap1Attrib = getVarbindOID(trap1Attrib);
+                trap1Attrib = getVarbindOid(trap1Attrib);
                 attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")";
             } catch (UnsupportedEncodingException e) {
                 policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e);
@@ -358,7 +362,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
         return attributesStr;
     }
 
-    private String getVarbindOID(String attrib) {
+    private String getVarbindOid(String attrib) {
         VarbindDictionary varbindId;
         try {
             varbindId =
@@ -372,7 +376,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
 
     // connect traps data set to JSON Body as String
     @SuppressWarnings({"unchecked", "rawtypes"})
-    private String getUIConnectTraps(List<Object> connectTrapSignatures) {
+    private String getUiConnectTraps(List<Object> connectTrapSignatures) {
         StringBuilder resultBody = new StringBuilder();
         String connectMainBody = "";
         for (Object connectTrapSignature : connectTrapSignatures) {
@@ -413,7 +417,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
     }
 
     // get Trigger signature from JSON body
-    private String getUITriggerSignature(String trap, Object object2) {
+    private String getUiTriggerSignature(String trap, Object object2) {
         ClosedLoopFaultTrapDatas trapDatas = (ClosedLoopFaultTrapDatas) object2;
         List<Object> attributeList = new ArrayList<>();
         // Read the Trap
@@ -474,31 +478,32 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
         return triggerBody.toString();
     }
 
+    /**
+     * prePopulateClosedLoopFaultPolicyData.
+     *
+     * @param policyAdapter PolicyRestAdapter
+     * @param entity PolicyEntity
+     */
     public void prePopulateClosedLoopFaultPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
-        if (policyAdapter.getPolicyData() instanceof PolicyType) {
-            PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
-
-            // Set PolicyAdapter policyName, description
-            setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy);
-
-            // Set PolicyAdapter JsonBodyData, timeout settings
-            setClosedLoopJSONFile(policyAdapter, entity);
+        if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+            return;
+        }
+        PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
 
-            // Get the target data under policy.
-            TargetType target = policy.getTarget();
-            if (target == null) {
-                return;
-            }
+        // Set PolicyAdapter policyName, description
+        setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy);
 
-            // Under target we have AnyOFType
-            List<AnyOfType> anyOfList = target.getAnyOf();
-            if (anyOfList == null) {
-                return;
-            }
+        // Set PolicyAdapter JsonBodyData, timeout settings
+        setClosedLoopJsonFile(policyAdapter, entity);
 
-            // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate from match attributes
-            setPolicyAdapterMatchAttributes(policyAdapter, anyOfList);
+        // Get the target data under policy.
+        TargetType target = policy.getTarget();
+        if (target == null) {
+            return;
         }
+
+        // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate from match attributes
+        setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf());
     }
 
     private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
@@ -550,11 +555,11 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
         policyAdapter.setPolicyDescription(description);
     }
 
-    private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
-        ObjectMapper mapper = new ObjectMapper();
+    private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
         try {
             ClosedLoopFaultBody closedLoopBody =
-                    mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class);
+                    new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(),
+                            ClosedLoopFaultBody.class);
             if ("ACTIVE".equalsIgnoreCase(closedLoopBody.getClosedLoopPolicyStatus())) {
                 closedLoopBody.setClosedLoopPolicyStatus("Active");
             } else {
@@ -580,7 +585,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
 
 @Getter
 @Setter
-class ClosedLoopGridJSONData {
+class ClosedLoopGridJsonData {
 
     private String clearTimeOut;
     private String trapMaxAge;
index 4862efd..8d47be7 100644 (file)
@@ -53,32 +53,28 @@ public class CreateClosedLoopPMController {
     protected PolicyRestAdapter policyAdapter = null;
 
     public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
-        if (policyAdapter.getPolicyData() instanceof PolicyType) {
-            Object policyData = policyAdapter.getPolicyData();
-            PolicyType policy = (PolicyType) policyData;
+        if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+            return;
+        }
+        Object policyData = policyAdapter.getPolicyData();
+        PolicyType policy = (PolicyType) policyData;
 
-            // Set oldPolicyFileName to PolicyAdapter
-            policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+        // Set oldPolicyFileName to PolicyAdapter
+        policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
 
-            // Set policyNameValue and description to PolicyAdapter
-            setPolicyAdapterNameValueAndDescription(policyAdapter, policy);
+        // Set policyNameValue and description to PolicyAdapter
+        setPolicyAdapterNameValueAndDescription(policyAdapter, policy);
 
-            // Set PolicyAdapter JsonBodyData
-            setClosedLoopJSONFile(policyAdapter, entity);
+        // Set PolicyAdapter JsonBodyData
+        setClosedLoopJsonFile(policyAdapter, entity);
 
-            // Get the target data under policy.
-            TargetType target = policy.getTarget();
-            if (target == null) {
-                return;
-            }
-            // Under target we have AnyOFType
-            List<AnyOfType> anyOfList = target.getAnyOf();
-            if (anyOfList == null) {
-                return;
-            }
-            // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes
-            setPolicyAdapterMatchAttributes(policyAdapter, anyOfList);
+        // Get the target data under policy.
+        TargetType target = policy.getTarget();
+        if (target == null) {
+            return;
         }
+        // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes
+        setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf());
     }
 
     private void setPolicyAdapterNameValueAndDescription(PolicyRestAdapter policyAdapter, PolicyType policy) {
@@ -95,11 +91,10 @@ public class CreateClosedLoopPMController {
         policyAdapter.setPolicyDescription(description);
     }
 
-    private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
-        ObjectMapper mapper = new ObjectMapper();
+    private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
         try {
             ClosedLoopPMBody closedLoopBody =
-                    mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
+                    new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
             policyAdapter.setJsonBodyData(closedLoopBody);
         } catch (IOException e) {
             LOGGER.error("Exception Occured" + e);
index 2b7974d..2549e21 100644 (file)
@@ -37,7 +37,6 @@ import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
-import java.io.PrintWriter;
 import java.io.StringReader;
 import java.nio.file.Files;
 import java.nio.file.Path;
@@ -162,6 +161,13 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
     private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
     private Map<String, String> jsonStringValues = new HashMap<>();
 
+    /**
+     * setDataToPolicyRestAdapter.
+     *
+     * @param policyData PolicyRestAdapter
+     * @param root JsonNode
+     * @return PolicyRestAdapter
+     */
     public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
 
         String jsonContent = null;
@@ -169,9 +175,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
             LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString());
 
             String tempJson = root.get(POLICYJSON).toString();
-            JSONObject policyJSON = new JSONObject(root.get(POLICYJSON).toString());
-            if (policyJSON != null) {
-                tempJson = saveOriginalJsonObject(policyJSON, jsonStringValues).toString();
+            JSONObject policyJson = new JSONObject(root.get(POLICYJSON).toString());
+            if (policyJson != null) {
+                tempJson = saveOriginalJsonObject(policyJson, jsonStringValues).toString();
             }
             // ---replace empty value with the value below before calling decodeContent method.
             String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
@@ -313,15 +319,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
                 modelName + ":" + versionName);
         MicroServiceModels model = null;
         boolean ruleCheck = false;
-        boolean SymptomRuleCheck = false;
         if (!triggerData.isEmpty()) {
             model = (MicroServiceModels) triggerData.get(0);
             if (model.getRuleFormation() != null) {
                 microServiceObject.setUiContent(jsonContent);
                 ruleCheck = true;
-                if (model.getRuleFormation().contains("@")) {
-                    SymptomRuleCheck = true;
-                }
             }
         }
         try {
@@ -331,7 +333,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         }
         LOGGER.info("input json: " + json);
         LOGGER.info("input jsonContent: " + jsonContent);
-        String cleanJson = cleanUPJson(json);
+        String cleanJson = cleanUpJson(json);
         // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
         String tempJson =
                 StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
@@ -344,40 +346,39 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         // for Triggers
         ObjectMapper mapper = new ObjectMapper();
         JsonNode tempJsonNode = mapper.readTree(cleanJson);
-        if (ruleCheck) {
-            // JsonNode tempJsonNode = mapper.readTree(cleanJson);
-            ObjectNode finalJson = (ObjectNode) tempJsonNode;
-            JsonNode object = tempJsonNode.get("content");
-            String primaryKey1 = model.getRuleFormation();
-            String[] primaryKeyForSignatures = primaryKey1.split("@");
-            for (String primaryKeyForSignature : primaryKeyForSignatures) {
-                String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
-                JsonNode triggerSig = object.get(primarykeyAlarm);
-                sigRules = new HashMap<>();
-                String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
-                StringBuilder sb = null;
-                if (triggerSig instanceof ArrayNode) {
-                    for (int i = 0; i < triggerSig.size(); i++) {
-                        sb = new StringBuilder();
-                        parseData(triggerSig.get(i), parseKey);
-                        sb.append("(");
-                        List<?> keyList = new ArrayList<>(sigRules.keySet());
-                        for (int j = keyList.size() - 1; j >= 0; j--) {
-                            String key = (String) keyList.get(j);
-                            String jsonNode = sigRules.get(key);
-                            constructRule(sb, jsonNode, sigRules);
-                        }
-                        sb.append(")").toString();
-                        putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
-                        sigRules = new HashMap<>();
-                    }
-                } else {
+        if (! ruleCheck) {
+            return policyAdapter;
+        }
+        ObjectNode finalJson = (ObjectNode) tempJsonNode;
+        JsonNode object = tempJsonNode.get("content");
+        String primaryKey1 = model.getRuleFormation();
+        String[] primaryKeyForSignatures = primaryKey1.split("@");
+        for (String primaryKeyForSignature : primaryKeyForSignatures) {
+            String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
+            JsonNode triggerSig = object.get(primarykeyAlarm);
+            sigRules = new HashMap<>();
+            String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
+            StringBuilder sb = null;
+            if (triggerSig instanceof ArrayNode) {
+                for (int i = 0; i < triggerSig.size(); i++) {
                     sb = new StringBuilder();
-                    parseData(triggerSig, parseKey);
+                    parseData(triggerSig.get(i), parseKey);
+                    sb.append("(");
+                    List<?> keyList = new ArrayList<>(sigRules.keySet());
+                    for (int j = keyList.size() - 1; j >= 0; j--) {
+                        String key = (String) keyList.get(j);
+                        String jsonNode = sigRules.get(key);
+                        constructRule(sb, jsonNode, sigRules);
+                    }
+                    sb.append(")").toString();
+                    putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
+                    sigRules = new HashMap<>();
                 }
+            } else {
+                parseData(triggerSig, parseKey);
             }
-            policyAdapter.setJsonBody(finalJson.toString());
         }
+        policyAdapter.setJsonBody(finalJson.toString());
         return policyAdapter;
     }
 
@@ -490,6 +491,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         }
     }
 
+    /**
+     * removeNullAttributes.
+     *
+     * @param cleanJson String
+     * @returnString
+     */
     public String removeNullAttributes(String cleanJson) {
         ObjectMapper mapper = new ObjectMapper();
 
@@ -533,9 +540,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
 
             if (contentChanged) {
                 // set modified content to cleanJson
-                JSONObject jObject = new JSONObject(cleanJson);
-                jObject.put("content", removed.toString());
-                cleanJson = cleanUPJson(jObject.toString());
+                JSONObject jsonObject = new JSONObject(cleanJson);
+                jsonObject.put("content", removed.toString());
+                cleanJson = cleanUpJson(jsonObject.toString());
             }
 
         } catch (IOException e) {
@@ -572,52 +579,69 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         return null;
     }
 
+    /**
+     *  removeNull.
+     *
+     * @param array JsonArray
+     * @return JsonArray
+     */
     public JsonArray removeNull(JsonArray array) {
         JsonArrayBuilder builder = Json.createArrayBuilder();
-        int i = 0;
-        for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
+        int index = 0;
+        for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++index) {
             JsonValue value = it.next();
             switch (value.getValueType()) {
                 case ARRAY:
-                    JsonArray a = removeNull(array.getJsonArray(i));
-                    if (!a.isEmpty())
-                        builder.add(a);
+                    JsonArray tempArray = removeNull(array.getJsonArray(index));
+                    if (!tempArray.isEmpty()) {
+                        builder.add(tempArray);
+                    }
                     break;
                 case OBJECT:
-                    JsonObject object = removeNull(array.getJsonObject(i));
-                    if (!object.isEmpty())
+                    JsonObject object = removeNull(array.getJsonObject(index));
+                    if (!object.isEmpty()) {
                         builder.add(object);
+                    }
                     break;
                 case STRING:
-                    String s = array.getString(i);
-                    if (s != null && !s.isEmpty())
-                        builder.add(s);
+                    String str = array.getString(index);
+                    if (str != null && !str.isEmpty()) {
+                        builder.add(str);
+                    }
                     break;
                 case NUMBER:
-                    builder.add(array.getJsonNumber(i));
+                    builder.add(array.getJsonNumber(index));
                     break;
                 case TRUE:
                 case FALSE:
-                    builder.add(array.getBoolean(i));
+                    builder.add(array.getBoolean(index));
                     break;
                 case NULL:
+                default:
                     break;
             }
         }
         return builder.build();
     }
 
+    /**
+     * removeNull.
+     *
+     * @param obj JsonObject
+     * @return JsonObject
+     */
     public JsonObject removeNull(JsonObject obj) {
         JsonObjectBuilder builder = Json.createObjectBuilder();
         for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
-            Entry<String, JsonValue> e = it.next();
-            String key = e.getKey();
-            JsonValue value = e.getValue();
+            Entry<String, JsonValue> entry = it.next();
+            String key = entry.getKey();
+            JsonValue value = entry.getValue();
             switch (value.getValueType()) {
                 case ARRAY:
                     JsonArray array = removeNull(obj.getJsonArray(key));
-                    if (!array.isEmpty())
+                    if (!array.isEmpty()) {
                         builder.add(key, array);
+                    }
                     break;
                 case OBJECT:
                     JsonObject object = removeNull(obj.getJsonObject(key));
@@ -633,15 +657,15 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
                     }
                     break;
                 case STRING:
-                    String s = obj.getString(key);
-                    if (s != null && !s.isEmpty()) {
+                    String str = obj.getString(key);
+                    if (str != null && !str.isEmpty()) {
                         if (!jsonStringValues.isEmpty()) {
                             String originalValue = getOriginalValue(key);
                             if (originalValue != null) {
-                                s = getOriginalValue(key);
+                                str = getOriginalValue(key);
                             }
                         }
-                        builder.add(key, s);
+                        builder.add(key, str);
                     }
                     break;
                 case NUMBER:
@@ -652,13 +676,20 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
                     builder.add(key, obj.getBoolean(key));
                     break;
                 case NULL:
+                default:
                     break;
             }
         }
         return builder.build();
     }
 
-    public String cleanUPJson(String json) {
+    /**
+     * cleanUpJson.
+     *
+     * @param json String
+     * @return String
+     */
+    public String cleanUpJson(String json) {
         String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
                 new String[] {"\\", "\\", "\\"});
         cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
@@ -679,6 +710,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         return cleanJson;
     }
 
+    /**
+     * decodeContent.
+     *
+     * @param jsonNode JsonNode
+     * @return JsonNode
+     */
     public JSONObject decodeContent(JsonNode jsonNode) {
         Iterator<JsonNode> jsonElements = jsonNode.elements();
         Iterator<String> jsonKeys = jsonNode.fieldNames();
@@ -887,7 +924,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
             allMnyTrueKeys = allkeys.toString();
         }
 
-        String jsonModel = createMicroSeriveJson(returnModel, allkeys);
+        String jsonModel = createMicroSeriveJson(returnModel);
 
         JSONObject jsonObject = new JSONObject(jsonModel);
 
@@ -927,26 +964,25 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         response.setContentType("application / json");
         request.setCharacterEncoding("UTF-8");
         List<Object> list = new ArrayList<>();
-        PrintWriter out = response.getWriter();
         String responseString = mapper.writeValueAsString(returnModel);
 
-        JSONObject j = null;
+        JSONObject json = null;
 
         if ("".equals(allMnyTrueKeys)) {
-            j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
+            json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
                     + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
         } else {
-            j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: "
-                    + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData
-                    + "}");
+            json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel
+                    + ",allManyTrueKeys: " + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
+                    + headDefautlsData + "}");
         }
-        list.add(j);
-        out.write(list.toString());
+        list.add(json);
+        response.getWriter().write(list.toString());
         return null;
     }
 
     @SuppressWarnings({"unchecked", "rawtypes"})
-    private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
+    private String createMicroSeriveJson(MicroServiceModels returnModel) {
         Map<String, String> attributeMap = new HashMap<>();
         Map<String, String> refAttributeMap = new HashMap<>();
         String attribute = returnModel.getAttributes();
@@ -980,10 +1016,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
 
         JSONObject object = new JSONObject();
-        JSONArray array = new JSONArray();
 
         for (Entry<String, String> keySet : attributeMap.entrySet()) {
-            array = new JSONArray();
+            JSONArray array = new JSONArray();
             String value = keySet.getValue();
             if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
                 array.put(value);
@@ -994,7 +1029,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         }
 
         for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
-            array = new JSONArray();
+            JSONArray array = new JSONArray();
             String value = keySet.getValue().split(":")[0];
             if (gsonObject.containsKey(value)) {
                 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
@@ -1081,7 +1116,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         return json;
     }
 
-    // call this method to get all MANY-true properties
+    /**
+     * getManyTrueProperties.
+     *
+     * @param referAttributes String
+     * @return a Set of String
+     */
     public Set<String> getManyTrueProperties(String referAttributes) {
         LOGGER.info("referAttributes : " + referAttributes);
         Set<String> manyTrueProperties = new HashSet<>();
@@ -1112,10 +1152,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
     private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
         for (int i = 0; i < arr.length(); i++) {
             Object obj = arr.get(i);
-            if (obj instanceof JSONObject)
+            if (obj instanceof JSONObject) {
                 keys.addAll(getAllKeys(arr.getJSONObject(i)));
-            if (obj instanceof JSONArray)
+            }
+            if (obj instanceof JSONArray) {
                 keys.addAll(getAllKeys(arr.getJSONArray(i)));
+            }
         }
 
         return keys;
@@ -1130,10 +1172,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
                 LOGGER.info("obj : " + obj);
                 allManyTrueKeys.add(key);
             }
-            if (obj instanceof JSONObject)
+            if (obj instanceof JSONObject) {
                 keys.addAll(getAllKeys(json.getJSONObject(key)));
-            if (obj instanceof JSONArray)
+            }
+            if (obj instanceof JSONArray) {
                 keys.addAll(getAllKeys(json.getJSONArray(key)));
+            }
         }
 
         return keys;
@@ -1146,21 +1190,16 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
             throws IOException {
         ObjectMapper mapper = new ObjectMapper();
         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-        JsonNode root = mapper.readTree(request.getReader());
-
-        String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
-        String servicename = value.split("-v")[0];
-        Set<String> returnList = getVersionList(servicename);
 
         response.setCharacterEncoding("UTF-8");
         response.setContentType("application / json");
         request.setCharacterEncoding("UTF-8");
         List<Object> list = new ArrayList<>();
-        PrintWriter out = response.getWriter();
-        String responseString = mapper.writeValueAsString(returnList);
-        JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString + "}");
-        list.add(j);
-        out.write(list.toString());
+        String value = mapper.readTree(request.getReader()).get("policyData").toString().replaceAll("^\"|\"$", "");
+        String servicename = value.split("-v")[0];
+        Set<String> returnList = getVersionList(servicename);
+        list.add(new JSONObject("{dcaeModelVersionData: " + mapper.writeValueAsString(returnList) + "}"));
+        response.getWriter().write(list.toString());
         return null;
     }
 
@@ -1219,93 +1258,84 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
                 priorityList.add(String.valueOf(i));
             }
             model.put("priorityDatas", mapper.writeValueAsString(priorityList));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             LOGGER.error(e);
         }
     }
 
+    /**
+     * prePopulateDCAEMSPolicyData.
+     *
+     * @param policyAdapter PolicyRestAdapter
+     * @param entity PolicyEntity
+     */
     public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
-        if (policyAdapter.getPolicyData() instanceof PolicyType) {
-            Object policyData = policyAdapter.getPolicyData();
-            PolicyType policy = (PolicyType) policyData;
-            policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-            String policyNameValue =
-                    policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
-            policyAdapter.setPolicyName(policyNameValue);
-            String description = "";
-            try {
-                description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
-            } catch (Exception e) {
-                LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
-                description = policy.getDescription();
-            }
-            policyAdapter.setPolicyDescription(description);
-            // Get the target data under policy.
-            TargetType target = policy.getTarget();
-            if (target != null) {
-                // Under target we have AnyOFType
-                List<AnyOfType> anyOfList = target.getAnyOf();
-                if (anyOfList != null) {
-                    Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
-                    while (iterAnyOf.hasNext()) {
-                        AnyOfType anyOf = iterAnyOf.next();
-                        // Under AnyOFType we have AllOFType
-                        List<AllOfType> allOfList = anyOf.getAllOf();
-                        if (allOfList != null) {
-                            Iterator<AllOfType> iterAllOf = allOfList.iterator();
-                            while (iterAllOf.hasNext()) {
-                                AllOfType allOf = iterAllOf.next();
-                                // Under AllOFType we have Match
-                                List<MatchType> matchList = allOf.getMatch();
-                                if (matchList != null) {
-                                    Iterator<MatchType> iterMatch = matchList.iterator();
-                                    while (matchList.size() > 1 && iterMatch.hasNext()) {
-                                        MatchType match = iterMatch.next();
-                                        //
-                                        // Under the match we have attribute value and
-                                        // attributeDesignator. So,finally down to the actual attribute.
-                                        //
-                                        AttributeValueType attributeValue = match.getAttributeValue();
-                                        String value = (String) attributeValue.getContent().get(0);
-                                        AttributeDesignatorType designator = match.getAttributeDesignator();
-                                        String attributeId = designator.getAttributeId();
-                                        // First match in the target is OnapName, so set that value.
-                                        if ("ONAPName".equals(attributeId)) {
-                                            policyAdapter.setOnapName(value);
-                                        }
-                                        if ("ConfigName".equals(attributeId)) {
-                                            policyAdapter.setConfigName(value);
-                                        }
-                                        if ("uuid".equals(attributeId)) {
-                                            policyAdapter.setUuid(value);
-                                        }
-                                        if ("location".equals(attributeId)) {
-                                            policyAdapter.setLocation(value);
-                                        }
-                                        if ("RiskType".equals(attributeId)) {
-                                            policyAdapter.setRiskType(value);
-                                        }
-                                        if ("RiskLevel".equals(attributeId)) {
-                                            policyAdapter.setRiskLevel(value);
-                                        }
-                                        if ("guard".equals(attributeId)) {
-                                            policyAdapter.setGuard(value);
-                                        }
-                                        if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
-                                            PolicyController controller = new PolicyController();
-                                            String newDate = controller.convertDate(value);
-                                            policyAdapter.setTtlDate(newDate);
-                                        }
-                                    }
-                                    readFile(policyAdapter, entity);
-                                }
-                            }
-                        }
+        if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+            return;
+        }
+        Object policyData = policyAdapter.getPolicyData();
+        PolicyType policy = (PolicyType) policyData;
+        policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+        String policyNameValue =
+                policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
+        policyAdapter.setPolicyName(policyNameValue);
+        String description = "";
+        try {
+            description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+        } catch (Exception e) {
+            LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
+            description = policy.getDescription();
+        }
+        policyAdapter.setPolicyDescription(description);
+        // Get the target data under policy.
+        TargetType target = policy.getTarget();
+        if (target == null) {
+            return;
+        }
+        for (AnyOfType anyOf : target.getAnyOf()) {
+            for (AllOfType allOf : anyOf.getAllOf()) {
+                // Under AllOFType we have Match
+                List<MatchType> matchList = allOf.getMatch();
+                if (matchList == null) {
+                    continue;
+                }
+                Iterator<MatchType> iterMatch = matchList.iterator();
+                //
+                // Can someone please explain why the matchList MUST have
+                // more than 1 matches???
+                //
+                while (matchList.size() > 1 && iterMatch.hasNext()) {
+                    MatchType match = iterMatch.next();
+                    //
+                    // Under the match we have attribute value and
+                    // attributeDesignator. So,finally down to the actual attribute.
+                    //
+                    AttributeValueType attributeValue = match.getAttributeValue();
+                    String value = (String) attributeValue.getContent().get(0);
+                    AttributeDesignatorType designator = match.getAttributeDesignator();
+                    String attributeId = designator.getAttributeId();
+                    // First match in the target is OnapName, so set that value.
+                    if ("ONAPName".equals(attributeId)) {
+                        policyAdapter.setOnapName(value);
+                    } else if ("ConfigName".equals(attributeId)) {
+                        policyAdapter.setConfigName(value);
+                    } else if ("uuid".equals(attributeId)) {
+                        policyAdapter.setUuid(value);
+                    } else if ("location".equals(attributeId)) {
+                        policyAdapter.setLocation(value);
+                    } else if ("RiskType".equals(attributeId)) {
+                        policyAdapter.setRiskType(value);
+                    } else if ("RiskLevel".equals(attributeId)) {
+                        policyAdapter.setRiskLevel(value);
+                    } else if ("guard".equals(attributeId)) {
+                        policyAdapter.setGuard(value);
+                    } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
+                        String newDate = new PolicyController().convertDate(value);
+                        policyAdapter.setTtlDate(newDate);
                     }
                 }
+                readFile(policyAdapter, entity);
             }
         }
     }
@@ -1334,12 +1364,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
      */
     @SuppressWarnings("unchecked")
     public void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
-        String policyScopeName = null;
-        ObjectMapper mapper = new ObjectMapper();
         try {
             DCAEMicroServiceObject msBody =
-                    mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
-            policyScopeName = getPolicyScope(msBody.getPolicyScope());
+                    new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(),
+                            DCAEMicroServiceObject.class);
+            String policyScopeName = getPolicyScope(msBody.getPolicyScope());
             policyAdapter.setPolicyScope(policyScopeName);
 
             policyAdapter.setPriority(msBody.getPriority());
@@ -1405,16 +1434,27 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         }
     }
 
+    /**
+     * getPolicyScope.
+     *
+     * @param value String
+     * @return String
+     */
     public String getPolicyScope(String value) {
         List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
         if (groupList != null && !groupList.isEmpty()) {
-            GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
-            return pScope.getGroupName();
+            return ((GroupPolicyScopeList) groupList.get(0)).getGroupName();
         }
         return null;
     }
 
-    // Convert the map values and set into JSON body
+    /**
+     * Convert the map values and set into JSON body.
+     *
+     * @param attributesMap Map of attributes
+     * @param attributesRefMap Map of attribute references
+     * @return Map
+     */
     public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
         Map<String, String> attribute = new HashMap<>();
         StringBuilder temp;
@@ -1495,35 +1535,31 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         }
 
         if (!errorMsg.isEmpty()) {
-
-            PrintWriter out = response.getWriter();
-
             response.setCharacterEncoding("UTF-8");
             response.setContentType("application / json");
             request.setCharacterEncoding("UTF-8");
 
-            JSONObject j = new JSONObject();
-            j.put("errorMsg", errorMsg);
-            out.write(j.toString());
+            JSONObject json = new JSONObject();
+            json.put("errorMsg", errorMsg);
+            response.getWriter().write(json.toString());
             return;
         }
 
         List<File> fileList = new ArrayList<>();
-        MSModelUtils msMLUtils = new MSModelUtils(commonClassDao);
+        MSModelUtils msModelUtils = new MSModelUtils(commonClassDao);
         this.directory = "model";
         if (zip) {
             extractFolder(this.newFile);
             fileList = listModelFiles(this.directory);
         } else if (yml) {
-            errorMsg = msMLUtils.parseTosca(this.newFile);
+            errorMsg = msModelUtils.parseTosca(this.newFile);
             if (errorMsg != null) {
-                PrintWriter out = response.getWriter();
                 response.setCharacterEncoding("UTF-8");
                 response.setContentType("application / json");
                 request.setCharacterEncoding("UTF-8");
-                JSONObject j = new JSONObject();
-                j.put("errorMsg", errorMsg);
-                out.write(j.toString());
+                JSONObject json = new JSONObject();
+                json.put("errorMsg", errorMsg);
+                response.getWriter().write(json.toString());
                 return;
             }
 
@@ -1538,7 +1574,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
             classMap = new LinkedHashMap<>();
             for (File file : fileList) {
                 if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
-                    retreiveDependency(file.toString(), true);
+                    retrieveDependency(file.toString());
                 }
             }
 
@@ -1554,21 +1590,21 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
             msAttributes.setClassName(className);
 
             LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
-            returnAttributeList.put(className, msMLUtils.getAttributeString());
+            returnAttributeList.put(className, msModelUtils.getAttributeString());
             msAttributes.setAttribute(returnAttributeList);
 
-            msAttributes.setSubClass(msMLUtils.getRetmap());
+            msAttributes.setSubClass(msModelUtils.getRetmap());
 
-            msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
+            msAttributes.setMatchingSet(msModelUtils.getMatchableValues());
 
             LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
 
-            returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
+            returnReferenceList.put(className, msModelUtils.getReferenceAttributes());
             msAttributes.setRefAttribute(returnReferenceList);
 
-            if (msMLUtils.getListConstraints() != "") {
+            if (msModelUtils.getListConstraints() != "") {
                 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
-                String[] listArray = msMLUtils.getListConstraints().split("#");
+                String[] listArray = msModelUtils.getListConstraints().split("#");
                 for (String str : listArray) {
                     String[] strArr = str.split("=");
                     if (strArr.length > 1) {
@@ -1582,22 +1618,19 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
             classMap.put(className, msAttributes);
 
         }
-
-        PrintWriter out = response.getWriter();
-
         response.setCharacterEncoding("UTF-8");
         response.setContentType("application / json");
         request.setCharacterEncoding("UTF-8");
 
         ObjectMapper mapper = new ObjectMapper();
-        JSONObject j = new JSONObject();
-        j.put("classListDatas", modelList);
-        j.put("modelDatas", mapper.writeValueAsString(classMap));
-        j.put("modelType", modelType);
-        j.put("dataOrderInfo", msMLUtils.getDataOrderInfo());
-        j.put("ruleFormation", msMLUtils.getJsonRuleFormation());
-
-        out.write(j.toString());
+        JSONObject json = new JSONObject();
+        json.put("classListDatas", modelList);
+        json.put("modelDatas", mapper.writeValueAsString(classMap));
+        json.put("modelType", modelType);
+        json.put("dataOrderInfo", msModelUtils.getDataOrderInfo());
+        json.put("ruleFormation", msModelUtils.getJsonRuleFormation());
+
+        response.getWriter().write(json.toString());
     }
 
     /*
@@ -1605,7 +1638,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
      */
     @SuppressWarnings("rawtypes")
     private void extractFolder(String zipFile) {
-        int BUFFER = 2048;
+        final int buffer = 2048;
         File file = new File(zipFile);
 
         try (ZipFile zip = new ZipFile(file)) {
@@ -1628,10 +1661,10 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
                 if (!entry.isDirectory()) {
                     BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
                     int currentByte;
-                    byte[] data = new byte[BUFFER];
+                    byte[] data = new byte[buffer];
                     try (FileOutputStream fos = new FileOutputStream(destFile);
-                            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
-                        while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
+                            BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
+                        while ((currentByte = is.read(data, 0, buffer)) != -1) {
                             dest.write(data, 0, currentByte);
                         }
                         dest.flush();
@@ -1653,7 +1686,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         }
     }
 
-    private void retreiveDependency(String workingFile, Boolean modelClass) {
+    private void retrieveDependency(String workingFile) {
 
         MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
         Map<String, MSAttributeObject> tempMap;
@@ -1662,16 +1695,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
 
         classMap.putAll(tempMap);
         LOGGER.info(tempMap);
-
-        return;
-
     }
 
     private List<File> listModelFiles(String directoryName) {
         File fileDirectory = new File(directoryName);
         List<File> resultList = new ArrayList<>();
-        File[] fList = fileDirectory.listFiles();
-        for (File file : fList) {
+        for (File file : fileDirectory.listFiles()) {
             if (file.isFile()) {
                 resultList.add(file);
             } else if (file.isDirectory()) {
@@ -1682,6 +1711,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         return resultList;
     }
 
+    /**
+     * cleanUp.
+     *
+     * @param path String
+     */
     public void cleanUp(String path) {
         if (path != null) {
             try {
@@ -1692,6 +1726,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         }
     }
 
+    /**
+     * checkZipDirectory.
+     *
+     * @param zipDirectory String
+     */
     public void checkZipDirectory(String zipDirectory) {
         Path path = Paths.get(zipDirectory);
 
@@ -1702,9 +1741,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
 
     private List<String> createList() {
         List<String> list = new ArrayList<>();
-        for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
-            if (cMap.getValue().isPolicyTempalate()) {
-                list.add(cMap.getKey());
+        for (Entry<String, MSAttributeObject> entrySet : classMap.entrySet()) {
+            if (entrySet.getValue().isPolicyTempalate()) {
+                list.add(entrySet.getKey());
             }
 
         }
@@ -1737,7 +1776,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
 
 }
 
-
 @Getter
 @Setter
 class DCAEMicroServiceObject {
index 8aad421..0fbc34d 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -25,13 +25,10 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.JsonMappingException;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.ObjectWriter;
 
-import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
@@ -47,7 +44,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-
+import org.apache.commons.lang3.StringUtils;
 import org.hibernate.SessionFactory;
 import org.json.JSONObject;
 import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -91,11 +88,19 @@ public class CreateFirewallController extends RestrictedBaseController {
     private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class);
     private static final String ANY = "ANY";
     private static final String GROUP = "Group_";
+    private static CommonClassDao commonClassDao;
+    private List<String> tagCollectorList;
+    private List<String> termCollectorList;
+
+    List<String> expandablePrefixIpList = new ArrayList<>();
+    List<String> expandableServicesList = new ArrayList<>();
 
     @Autowired
     SessionFactory sessionFactory;
 
-    private static CommonClassDao commonClassDao;
+    public CreateFirewallController() {
+        // Empty constructor
+    }
 
     public static CommonClassDao getCommonClassDao() {
         return commonClassDao;
@@ -105,24 +110,18 @@ public class CreateFirewallController extends RestrictedBaseController {
         CreateFirewallController.commonClassDao = commonClassDao;
     }
 
-    private List<String> tagCollectorList;
-
-    List<String> expandablePrefixIPList = new ArrayList<>();
-    List<String> expandableServicesList = new ArrayList<>();
-
     @Autowired
     private CreateFirewallController(CommonClassDao commonClassDao) {
         CreateFirewallController.commonClassDao = commonClassDao;
     }
 
-    public CreateFirewallController() {
-        // Empty constructor
-    }
-
-    private List<String> termCollectorList;
-
+    /**
+     * setDataToPolicyRestAdapter.
+     *
+     * @param policyData PolicyRestAdapter
+     * @return PolicyRestAdapter
+     */
     public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData) {
-        String jsonBody;
         termCollectorList = new ArrayList<>();
         tagCollectorList = new ArrayList<>();
         if (!policyData.getAttributes().isEmpty()) {
@@ -136,12 +135,15 @@ public class CreateFirewallController extends RestrictedBaseController {
                 }
             }
         }
-        jsonBody = constructJson(policyData);
-        if (jsonBody != null && !"".equalsIgnoreCase(jsonBody)) {
+        String jsonBody = constructJson(policyData);
+        if (StringUtils.isBlank(jsonBody)) {
             policyData.setJsonBody(jsonBody);
         } else {
             policyData.setJsonBody("{}");
         }
+        //
+        // Hmmm - seems to be overriding the previous if statement
+        //
         policyData.setJsonBody(jsonBody);
 
         return policyData;
@@ -206,117 +208,109 @@ public class CreateFirewallController extends RestrictedBaseController {
     public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
         ArrayList<Object> attributeList;
         attributeList = new ArrayList<>();
-        if (policyAdapter.getPolicyData() instanceof PolicyType) {
-            Object policyData = policyAdapter.getPolicyData();
-            PolicyType policy = (PolicyType) policyData;
-            // policy name value is the policy name without any prefix and Extensions.
-            policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-            String policyNameValue =
-                    policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") + 3);
-            if (policyLogger.isDebugEnabled()) {
-                policyLogger
-                        .debug("Prepopulating form data for Config Policy selected:" + policyAdapter.getPolicyName());
-            }
-            policyAdapter.setPolicyName(policyNameValue);
-            String description = "";
-            try {
-                description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
-            } catch (Exception e) {
-                policyLogger.info("General error", e);
-                description = policy.getDescription();
-            }
-            policyAdapter.setPolicyDescription(description);
+        if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+            return;
+        }
+        Object policyData = policyAdapter.getPolicyData();
+        PolicyType policy = (PolicyType) policyData;
+        // policy name value is the policy name without any prefix and Extensions.
+        policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+        String policyNameValue =
+                policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") + 3);
+        if (policyLogger.isDebugEnabled()) {
+            policyLogger
+                    .debug("Prepopulating form data for Config Policy selected:" + policyAdapter.getPolicyName());
+        }
+        policyAdapter.setPolicyName(policyNameValue);
+        String description = "";
+        try {
+            description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+        } catch (Exception e) {
+            policyLogger.info("General error", e);
+            description = policy.getDescription();
+        }
+        policyAdapter.setPolicyDescription(description);
 
-            ObjectMapper mapper = new ObjectMapper();
+        ObjectMapper mapper = new ObjectMapper();
 
-            TermCollector tc1 = null;
-            try {
-                // Json conversion.
-                String data;
-                SecurityZone jpaSecurityZone;
-                data = entity.getConfigurationData().getConfigBody();
-                tc1 = mapper.readValue(data, TermCollector.class);
-                List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
-                for (int i = 0; i < securityZoneData.size(); i++) {
-                    jpaSecurityZone = (SecurityZone) securityZoneData.get(i);
-                    if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())) {
-                        policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName());
-                        break;
-                    }
+        TermCollector tc1 = null;
+        try {
+            // Json conversion.
+            String data;
+            SecurityZone jpaSecurityZone;
+            data = entity.getConfigurationData().getConfigBody();
+            tc1 = mapper.readValue(data, TermCollector.class);
+            List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
+            for (int i = 0; i < securityZoneData.size(); i++) {
+                jpaSecurityZone = (SecurityZone) securityZoneData.get(i);
+                if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())) {
+                    policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName());
+                    break;
                 }
-            } catch (Exception e) {
-                policyLogger.error("Exception Caused while Retriving the JSON body data" + e);
             }
+        } catch (Exception e) {
+            policyLogger.error("Exception Caused while Retriving the JSON body data" + e);
+        }
 
-            Map<String, String> termTagMap;
-            if (tc1 != null) {
-                for (int i = 0; i < tc1.getFirewallRuleList().size(); i++) {
-                    termTagMap = new HashMap<>();
-                    String ruleName = tc1.getFirewallRuleList().get(i).getRuleName();
-                    String tagPickerName = tc1.getRuleToTag().get(i).getTagPickerName();
-                    termTagMap.put("key", ruleName);
-                    termTagMap.put("value", tagPickerName);
-                    attributeList.add(termTagMap);
-                }
+        Map<String, String> termTagMap;
+        if (tc1 != null) {
+            for (int i = 0; i < tc1.getFirewallRuleList().size(); i++) {
+                termTagMap = new HashMap<>();
+                String ruleName = tc1.getFirewallRuleList().get(i).getRuleName();
+                String tagPickerName = tc1.getRuleToTag().get(i).getTagPickerName();
+                termTagMap.put("key", ruleName);
+                termTagMap.put("value", tagPickerName);
+                attributeList.add(termTagMap);
             }
-            policyAdapter.setAttributes(attributeList);
-            // Get the target data under policy.
-            TargetType target = policy.getTarget();
-            if (target != null) {
-                // Under target we have AnyOFType
-                List<AnyOfType> anyOfList = target.getAnyOf();
-                if (anyOfList != null) {
-                    Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
-                    while (iterAnyOf.hasNext()) {
-                        AnyOfType anyOf = iterAnyOf.next();
-                        // Under AnyOFType we have AllOFType
-                        List<AllOfType> allOfList = anyOf.getAllOf();
-                        if (allOfList != null) {
-                            Iterator<AllOfType> iterAllOf = allOfList.iterator();
-                            while (iterAllOf.hasNext()) {
-                                AllOfType allOf = iterAllOf.next();
-                                // Under AllOFType we have Match
-                                List<MatchType> matchList = allOf.getMatch();
-                                if (matchList != null) {
-
-                                    Iterator<MatchType> iterMatch = matchList.iterator();
-                                    while (iterMatch.hasNext()) {
-                                        MatchType match = iterMatch.next();
-                                        //
-                                        // Under the match we have attribute value and
-                                        // attributeDesignator. So,finally down to the actual attribute.
-                                        //
-                                        AttributeValueType attributeValue = match.getAttributeValue();
-                                        String value = (String) attributeValue.getContent().get(0);
-                                        AttributeDesignatorType designator = match.getAttributeDesignator();
-                                        String attributeId = designator.getAttributeId();
-                                        if (("ConfigName").equals(attributeId)) {
-                                            policyAdapter.setConfigName(value);
-                                        }
-                                        if (("RiskType").equals(attributeId)) {
-                                            policyAdapter.setRiskType(value);
-                                        }
-                                        if (("RiskLevel").equals(attributeId)) {
-                                            policyAdapter.setRiskLevel(value);
-                                        }
-                                        if (("guard").equals(attributeId)) {
-                                            policyAdapter.setGuard(value);
-                                        }
-                                        if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
-                                            PolicyController controller = new PolicyController();
-                                            String newDate = controller.convertDate(value);
-                                            policyAdapter.setTtlDate(newDate);
-                                        }
-                                    }
-                                }
-                            }
-                        }
+        }
+        policyAdapter.setAttributes(attributeList);
+        // Get the target data under policy.
+        TargetType target = policy.getTarget();
+        if (target == null) {
+            return;
+        }
+        // Under target we have AnyOFType
+        // NOTE: target.getAnyOf() will never be null
+        for (AnyOfType anyOf : target.getAnyOf()) {
+            for (AllOfType allOf : anyOf.getAllOf()) {
+                for (MatchType match : allOf.getMatch()) {
+                    //
+                    // Under the match we have attribute value and
+                    // attributeDesignator. So,finally down to the actual attribute.
+                    //
+                    AttributeValueType attributeValue = match.getAttributeValue();
+                    String value = (String) attributeValue.getContent().get(0);
+                    AttributeDesignatorType designator = match.getAttributeDesignator();
+                    String attributeId = designator.getAttributeId();
+                    if (("ConfigName").equals(attributeId)) {
+                        policyAdapter.setConfigName(value);
+                    }
+                    if (("RiskType").equals(attributeId)) {
+                        policyAdapter.setRiskType(value);
+                    }
+                    if (("RiskLevel").equals(attributeId)) {
+                        policyAdapter.setRiskLevel(value);
+                    }
+                    if (("guard").equals(attributeId)) {
+                        policyAdapter.setGuard(value);
+                    }
+                    if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
+                        PolicyController controller = new PolicyController();
+                        String newDate = controller.convertDate(value);
+                        policyAdapter.setTtlDate(newDate);
                     }
                 }
             }
         }
     }
 
+    /**
+     * setFWViewRule.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @return ModelAndView
+     */
     @RequestMapping(
             value = {"/policyController/ViewFWPolicyRule.htm"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -467,10 +461,8 @@ public class CreateFirewallController extends RestrictedBaseController {
             response.setContentType("application / json");
             request.setCharacterEncoding("UTF-8");
 
-            PrintWriter out = response.getWriter();
             String responseString = mapper.writeValueAsString(displayString);
-            JSONObject j = new JSONObject("{policyData: " + responseString + "}");
-            out.write(j.toString());
+            response.getWriter().write(new JSONObject("{policyData: " + responseString + "}").toString());
             return null;
         } catch (Exception e) {
             policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
@@ -481,13 +473,13 @@ public class CreateFirewallController extends RestrictedBaseController {
     private String constructJson(PolicyRestAdapter policyData) {
         int ruleCount = 1;
         // Maps to assosciate the values read from the TermList dictionary
-        Map<Integer, String> srcIP_map = null;
-        Map<Integer, String> destIP_map = null;
-        Map<Integer, String> srcPort_map = null;
-        Map<Integer, String> destPort_map = null;
-        Map<Integer, String> action_map = null;
-        Map<Integer, String> fromZone_map = null;
-        Map<Integer, String> toZone_map = null;
+        Map<Integer, String> mapSrcIp = null;
+        Map<Integer, String> mapDestIP = null;
+        Map<Integer, String> mapSrcPort = null;
+        Map<Integer, String> mapDestPort = null;
+        Map<Integer, String> mapAction = null;
+        Map<Integer, String> mapFromZone = null;
+        Map<Integer, String> mapToZone = null;
 
         String ruleDesc = null;
         String ruleFromZone = null;
@@ -513,7 +505,7 @@ public class CreateFirewallController extends RestrictedBaseController {
         List<TagDefines> tagList = null;
         ServiceListJson targetSl = null;
         AddressMembers addressMembersJson = null;
-        int i = 0;
+        int intCounter = 0;
         try {
             String networkRole = "";
             for (String tag : tagCollectorList) {
@@ -542,10 +534,10 @@ public class CreateFirewallController extends RestrictedBaseController {
                 }
                 tags.setTags(tagList);
                 tags.setTagPickerName(tag);
-                tags.setRuleName(termCollectorList.get(i));
+                tags.setRuleName(termCollectorList.get(intCounter));
                 tags.setNetworkRole(networkRole);
                 tagsList.add(tags);
-                i++;
+                intCounter++;
             }
             tc.setRuleToTag(tagsList);
 
@@ -564,47 +556,47 @@ public class CreateFirewallController extends RestrictedBaseController {
                         ruleFromZone = jpaTermList.getFromZone();
 
                         if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())) {
-                            fromZone_map = new HashMap<>();
-                            fromZone_map.put(tl, ruleFromZone);
+                            mapFromZone = new HashMap<>();
+                            mapFromZone.put(tl, ruleFromZone);
                         }
                         ruleToZone = jpaTermList.getToZone();
 
                         if ((ruleToZone != null) && (!ruleToZone.isEmpty())) {
-                            toZone_map = new HashMap<>();
-                            toZone_map.put(tl, ruleToZone);
+                            mapToZone = new HashMap<>();
+                            mapToZone.put(tl, ruleToZone);
                         }
                         ruleSrcPrefixList = jpaTermList.getSrcIPList();
 
                         if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())) {
-                            srcIP_map = new HashMap<>();
-                            srcIP_map.put(tl, ruleSrcPrefixList);
+                            mapSrcIp = new HashMap<>();
+                            mapSrcIp.put(tl, ruleSrcPrefixList);
                         }
 
                         ruleDestPrefixList = jpaTermList.getDestIPList();
                         if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())) {
-                            destIP_map = new HashMap<>();
-                            destIP_map.put(tl, ruleDestPrefixList);
+                            mapDestIP = new HashMap<>();
+                            mapDestIP.put(tl, ruleDestPrefixList);
                         }
 
                         ruleSrcPort = jpaTermList.getSrcPortList();
 
                         if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())) {
-                            srcPort_map = new HashMap<>();
-                            srcPort_map.put(tl, ruleSrcPort);
+                            mapSrcPort = new HashMap<>();
+                            mapSrcPort.put(tl, ruleSrcPort);
                         }
 
                         ruleDestPort = jpaTermList.getDestPortList();
 
                         if (ruleDestPort != null && (!jpaTermList.getDestPortList().isEmpty())) {
-                            destPort_map = new HashMap<>();
-                            destPort_map.put(tl, ruleDestPort);
+                            mapDestPort = new HashMap<>();
+                            mapDestPort.put(tl, ruleDestPort);
                         }
 
                         ruleAction = jpaTermList.getAction();
 
                         if ((ruleAction != null) && (!ruleAction.isEmpty())) {
-                            action_map = new HashMap<>();
-                            action_map.put(tl, ruleAction);
+                            mapAction = new HashMap<>();
+                            mapAction.put(tl, ruleAction);
                         }
                     }
                 }
@@ -613,32 +605,32 @@ public class CreateFirewallController extends RestrictedBaseController {
                 targetTerm.setNegateSource(false);
                 targetTerm.setNegateDestination(false);
 
-                if (action_map != null) {
-                    targetTerm.setAction(action_map.get(tl));
+                if (mapAction != null) {
+                    targetTerm.setAction(mapAction.get(tl));
                 }
 
                 // FromZone arrays
-                if (fromZone_map != null) {
+                if (mapFromZone != null) {
                     List<String> fromZone = new ArrayList<>();
-                    for (String fromZoneStr : fromZone_map.get(tl).split(",")) {
+                    for (String fromZoneStr : mapFromZone.get(tl).split(",")) {
                         fromZone.add(fromZoneStr);
                     }
                     targetTerm.setFromZones(fromZone);
                 }
 
                 // ToZone arrays
-                if (toZone_map != null) {
+                if (mapToZone != null) {
                     List<String> toZone = new ArrayList<>();
-                    for (String toZoneStr : toZone_map.get(tl).split(",")) {
+                    for (String toZoneStr : mapToZone.get(tl).split(",")) {
                         toZone.add(toZoneStr);
                     }
                     targetTerm.setToZones(toZone);
                 }
 
                 // Destination Services.
-                if (destPort_map != null) {
+                if (mapDestPort != null) {
                     Set<ServicesJson> destServicesJsonList = new HashSet<>();
-                    for (String destServices : destPort_map.get(tl).split(",")) {
+                    for (String destServices : mapDestPort.get(tl).split(",")) {
                         ServicesJson destServicesJson = new ServicesJson();
                         destServicesJson.setType("REFERENCE");
                         if (destServices.equals(ANY)) {
@@ -657,19 +649,19 @@ public class CreateFirewallController extends RestrictedBaseController {
                     targetTerm.setDestServices(destServicesJsonList);
                 }
                 // ExpandableServicesList
-                if ((srcPort_map != null) && (destPort_map != null)) {
-                    String servicesCollateString = srcPort_map.get(tl) + "," + destPort_map.get(tl);
+                if ((mapSrcPort != null) && (mapDestPort != null)) {
+                    String servicesCollateString = mapSrcPort.get(tl) + "," + mapDestPort.get(tl);
                     expandableServicesList.add(servicesCollateString);
-                } else if (srcPort_map != null) {
-                    expandableServicesList.add(srcPort_map.get(tl));
-                } else if (destPort_map != null) {
-                    expandableServicesList.add(destPort_map.get(tl));
+                } else if (mapSrcPort != null) {
+                    expandableServicesList.add(mapSrcPort.get(tl));
+                } else if (mapDestPort != null) {
+                    expandableServicesList.add(mapDestPort.get(tl));
                 }
 
-                if (srcIP_map != null) {
+                if (mapSrcIp != null) {
                     // Source List
                     List<AddressJson> sourceListArrayJson = new ArrayList<>();
-                    for (String srcList : srcIP_map.get(tl).split(",")) {
+                    for (String srcList : mapSrcIp.get(tl).split(",")) {
                         AddressJson srcListJson = new AddressJson();
                         if (srcList.equals(ANY)) {
                             srcListJson.setType("any");
@@ -687,10 +679,10 @@ public class CreateFirewallController extends RestrictedBaseController {
                     }
                     targetTerm.setSourceList(sourceListArrayJson);
                 }
-                if (destIP_map != null) {
+                if (mapDestIP != null) {
                     // Destination List
                     List<AddressJson> destListArrayJson = new ArrayList<>();
-                    for (String destList : destIP_map.get(tl).split(",")) {
+                    for (String destList : mapDestIP.get(tl).split(",")) {
                         AddressJson destListJson = new AddressJson();
                         if (destList.equals(ANY)) {
                             destListJson.setType("any");
@@ -709,13 +701,13 @@ public class CreateFirewallController extends RestrictedBaseController {
                     targetTerm.setDestinationList(destListArrayJson);
                 }
                 // ExpandablePrefixIPList
-                if ((srcIP_map != null) && (destIP_map != null)) {
-                    String collateString = srcIP_map.get(tl) + "," + destIP_map.get(tl);
-                    expandablePrefixIPList.add(collateString);
-                } else if (srcIP_map != null) {
-                    expandablePrefixIPList.add(srcIP_map.get(tl));
-                } else if (destIP_map != null) {
-                    expandablePrefixIPList.add(destIP_map.get(tl));
+                if ((mapSrcIp != null) && (mapDestIP != null)) {
+                    String collateString = mapSrcIp.get(tl) + "," + mapDestIP.get(tl);
+                    expandablePrefixIpList.add(collateString);
+                } else if (mapSrcIp != null) {
+                    expandablePrefixIpList.add(mapSrcIp.get(tl));
+                } else if (mapDestIP != null) {
+                    expandablePrefixIpList.add(mapDestIP.get(tl));
                 }
                 termList.add(targetTerm);
                 targetTerm.setPosition(Integer.toString(ruleCount++));
@@ -800,7 +792,7 @@ public class CreateFirewallController extends RestrictedBaseController {
 
                             servListArray.add(targetAnyUdp);
                         }
-                    } else {// This is a group
+                    } else { // This is a group
                         GroupServiceList sg;
                         targetSg = new ServiceGroupJson();
                         sg = mappingServiceGroup(t);
@@ -835,15 +827,13 @@ public class CreateFirewallController extends RestrictedBaseController {
                 }
             }
 
-            Set<PrefixIPList> prefixIPList = new HashSet<>();
-            for (String prefixList : expandablePrefixIPList) {
+            Set<PrefixIPList> prefixIpList = new HashSet<>();
+            for (String prefixList : expandablePrefixIpList) {
                 for (String prefixIP : prefixList.split(",")) {
                     if (!prefixIP.startsWith(GROUP)) {
                         if (!prefixIP.equals(ANY)) {
-                            List<AddressMembers> addMembersList = new ArrayList<>();
                             List<String> valueDesc;
                             PrefixIPList targetAddressList = new PrefixIPList();
-                            AddressMembers addressMembers = new AddressMembers();
                             targetAddressList.setName(prefixIP);
                             policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:" + prefixIP);
                             valueDesc = mapping(prefixIP);
@@ -852,18 +842,18 @@ public class CreateFirewallController extends RestrictedBaseController {
                                         + valueDesc.get(1));
                                 targetAddressList.setDescription(valueDesc.get(1));
                             }
-
+                            AddressMembers addressMembers = new AddressMembers();
                             addressMembers.setType("SUBNET");
                             if (!valueDesc.isEmpty()) {
                                 addressMembers.setValue(valueDesc.get(0));
                             }
-
+                            List<AddressMembers> addMembersList = new ArrayList<>();
                             addMembersList.add(addressMembers);
 
                             targetAddressList.setMembers(addMembersList);
-                            prefixIPList.add(targetAddressList);
+                            prefixIpList.add(targetAddressList);
                         }
-                    } else {// This is a group
+                    } else { // This is a group
                         AddressGroup ag;
                         addressSg = new AddressGroupJson();
                         ag = mappingAddressGroup(prefixIP);
@@ -874,14 +864,13 @@ public class CreateFirewallController extends RestrictedBaseController {
 
                         List<AddressMembersJson> addrMembersList = new ArrayList<>();
                         for (String groupString : ag.getPrefixList().split(",")) {
-                            List<String> valueDesc;
                             AddressMembersJson addressMembers = new AddressMembersJson();
                             addressMembers.setType("REFERENCES");
                             addressMembers.setName(groupString);
                             addrMembersList.add(addressMembers);
                             // Expand the group Name
                             addressMembersJson = new AddressMembers();
-                            valueDesc = mapping(groupString);
+                            List<String> valueDesc = mapping(groupString);
 
                             addressMembersJson.setName(groupString);
                             addressMembersJson.setType("SUBNET");
@@ -909,7 +898,7 @@ public class CreateFirewallController extends RestrictedBaseController {
 
             Set<Object> addressGroup = new HashSet<>();
 
-            for (Object addObj : prefixIPList) {
+            for (Object addObj : prefixIpList) {
                 addressGroup.add(addObj);
             }
 
@@ -925,9 +914,8 @@ public class CreateFirewallController extends RestrictedBaseController {
             tc.setAddressGroups(addressGroup);
             tc.setFirewallRuleList(termList);
 
-            ObjectWriter om = new ObjectMapper().writer();
             try {
-                json = om.writeValueAsString(tc);
+                json = new ObjectMapper().writer().writeValueAsString(tc);
             } catch (JsonGenerationException e) {
                 policyLogger.error("JsonGenerationException Ocured", e);
             } catch (JsonMappingException e) {
index b77f6a7..afe2ce1 100644 (file)
@@ -34,7 +34,6 @@ import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
-import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.HashMap;
@@ -91,6 +90,9 @@ import org.springframework.web.servlet.ModelAndView;
 @RequestMapping("/")
 public class CreateOptimizationController extends RestrictedBaseController {
     private static final Logger LOGGER = FlexLogger.getLogger(CreateOptimizationController.class);
+
+    private static final int BUFFER = 2048;
+
     private static CommonClassDao commonClassDao;
 
     public static CommonClassDao getCommonClassDao() {
@@ -141,6 +143,13 @@ public class CreateOptimizationController extends RestrictedBaseController {
     private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
     CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
 
+    /**
+     * setDataToPolicyRestAdapter.
+     *
+     * @param policyData PolicyRestAdapter
+     * @param root JsonNode
+     * @return PolicyRestAdapter
+     */
     public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
         String jsonContent = null;
         try {
@@ -178,7 +187,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
         }
         LOGGER.info("input json: " + json);
         LOGGER.info("input jsonContent: " + jsonContent);
-        String cleanJson = msController.cleanUPJson(json);
+        String cleanJson = msController.cleanUpJson(json);
 
         // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
         String tempJson =
@@ -189,6 +198,14 @@ public class CreateOptimizationController extends RestrictedBaseController {
         return policyAdapter;
     }
 
+    /**
+     * getOptimizationTemplateData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @return ModelAndView
+     * @throws IOException IOException
+     */
     @RequestMapping(
             value = {"/policyController/getOptimizationTemplateData.htm"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -200,10 +217,10 @@ public class CreateOptimizationController extends RestrictedBaseController {
         JsonNode root = mapper.readTree(request.getReader());
 
         String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
-        String servicename = value.toString().split("-v")[0];
+        String servicename = value.split("-v")[0];
         String version = null;
-        if (value.toString().contains("-v")) {
-            version = value.toString().split("-v")[1];
+        if (value.contains("-v")) {
+            version = value.split("-v")[1];
         }
 
         OptimizationModels returnModel = getAttributeObject(servicename, version);
@@ -230,8 +247,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
         // Get all keys with "MANY-true" defined in their value from subAttribute
         Set<String> allkeys = null;
         if (returnModel.getSubattributes() != null && !returnModel.getSubattributes().isEmpty()) {
-            JSONObject json = new JSONObject(returnModel.getSubattributes());
-            getAllKeys(json);
+            getAllKeys(new JSONObject(returnModel.getSubattributes()));
             allkeys = allManyTrueKeys;
             allManyTrueKeys = new HashSet<>();
             LOGGER.info("allkeys : " + allkeys);
@@ -284,19 +300,18 @@ public class CreateOptimizationController extends RestrictedBaseController {
         response.setContentType(APPLICATIONJSON);
         request.setCharacterEncoding(UTF8);
         List<Object> list = new ArrayList<>();
-        PrintWriter out = response.getWriter();
         String responseString = mapper.writeValueAsString(returnModel);
-        JSONObject j = null;
+        JSONObject json = null;
         if ("".equals(nameOfTrueKeys)) {
-            j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+            json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
                     + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
         } else {
-            j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+            json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
                     + ",allManyTrueKeys: " + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
                     + headDefautlsData + "}");
         }
-        list.add(j);
-        out.write(list.toString());
+        list.add(json);
+        response.getWriter().write(list.toString());
         return null;
     }
 
@@ -419,10 +434,12 @@ public class CreateOptimizationController extends RestrictedBaseController {
     private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
         for (int i = 0; i < arr.length(); i++) {
             Object obj = arr.get(i);
-            if (obj instanceof JSONObject)
+            if (obj instanceof JSONObject) {
                 keys.addAll(getAllKeys(arr.getJSONObject(i)));
-            if (obj instanceof JSONArray)
+            }
+            if (obj instanceof JSONArray) {
                 keys.addAll(getAllKeys(arr.getJSONArray(i)));
+            }
         }
 
         return keys;
@@ -437,15 +454,25 @@ public class CreateOptimizationController extends RestrictedBaseController {
                 LOGGER.info("obj : " + obj);
                 allManyTrueKeys.add(key);
             }
-            if (obj instanceof JSONObject)
+            if (obj instanceof JSONObject) {
                 keys.addAll(getAllKeys(json.getJSONObject(key)));
-            if (obj instanceof JSONArray)
+            }
+            if (obj instanceof JSONArray) {
                 keys.addAll(getAllKeys(json.getJSONArray(key)));
+            }
         }
 
         return keys;
     }
 
+    /**
+     * getModelServiceVersionData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @return ModelAndView
+     * @throws IOException IOException
+     */
     @RequestMapping(
             value = {"/policyController/getModelServiceVersionData.htm"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -455,19 +482,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
         JsonNode root = mapper.readTree(request.getReader());
 
-        String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
-        String servicename = value.split("-v")[0];
-        Set<String> returnList = getVersionList(servicename);
+        final String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
+        final String servicename = value.split("-v")[0];
 
         response.setCharacterEncoding(UTF8);
         response.setContentType(APPLICATIONJSON);
         request.setCharacterEncoding(UTF8);
         List<Object> list = new ArrayList<>();
-        PrintWriter out = response.getWriter();
-        String responseString = mapper.writeValueAsString(returnList);
-        JSONObject j = new JSONObject("{optimizationModelVersionData: " + responseString + "}");
-        list.add(j);
-        out.write(list.toString());
+        list.add(new JSONObject("{optimizationModelVersionData: "
+                + mapper.writeValueAsString(getVersionList(servicename)) + "}"));
+        response.getWriter().write(list.toString());
         return null;
     }
 
@@ -512,76 +536,66 @@ public class CreateOptimizationController extends RestrictedBaseController {
                 modelName);
     }
 
+    /**
+     * prePopulatePolicyData.
+     *
+     * @param policyAdapter PolicyRestAdapter
+     * @param entity PolicyEntity
+     */
     public void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
-        if (policyAdapter.getPolicyData() instanceof PolicyType) {
-            Object policyData = policyAdapter.getPolicyData();
-            PolicyType policy = (PolicyType) policyData;
-            policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-            String policyNameValue =
-                    policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4);
-            policyAdapter.setPolicyName(policyNameValue);
-            String description = "";
-            try {
-                description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
-            } catch (Exception e) {
-                LOGGER.error("Error while collecting the description tag in " + policyNameValue, e);
-                description = policy.getDescription();
-            }
-            policyAdapter.setPolicyDescription(description);
-            // Get the target data under policy.
-            TargetType target = policy.getTarget();
-            if (target != null) {
-                // Under target we have AnyOFType
-                List<AnyOfType> anyOfList = target.getAnyOf();
-                if (anyOfList != null) {
-                    Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
-                    while (iterAnyOf.hasNext()) {
-                        AnyOfType anyOf = iterAnyOf.next();
-                        // Under AnyOFType we have AllOFType
-                        List<AllOfType> allOfList = anyOf.getAllOf();
-                        if (allOfList != null) {
-                            Iterator<AllOfType> iterAllOf = allOfList.iterator();
-                            while (iterAllOf.hasNext()) {
-                                AllOfType allOf = iterAllOf.next();
-                                // Under AllOFType we have Match
-                                List<MatchType> matchList = allOf.getMatch();
-                                if (matchList != null) {
-                                    Iterator<MatchType> iterMatch = matchList.iterator();
-                                    while (matchList.size() > 1 && iterMatch.hasNext()) {
-                                        MatchType match = iterMatch.next();
-                                        //
-                                        // Under the match we have attribute value and
-                                        // attributeDesignator. So,finally down to the actual attribute.
-                                        //
-                                        AttributeValueType attributeValue = match.getAttributeValue();
-                                        String value = (String) attributeValue.getContent().get(0);
-                                        AttributeDesignatorType designator = match.getAttributeDesignator();
-                                        String attributeId = designator.getAttributeId();
-                                        // First match in the target is OnapName, so set that value.
-                                        if ("ONAPName".equals(attributeId)) {
-                                            policyAdapter.setOnapName(value);
-                                        }
-                                        if ("RiskType".equals(attributeId)) {
-                                            policyAdapter.setRiskType(value);
-                                        }
-                                        if ("RiskLevel".equals(attributeId)) {
-                                            policyAdapter.setRiskLevel(value);
-                                        }
-                                        if ("guard".equals(attributeId)) {
-                                            policyAdapter.setGuard(value);
-                                        }
-                                        if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
-                                            PolicyController controller = new PolicyController();
-                                            String newDate = controller.convertDate(value);
-                                            policyAdapter.setTtlDate(newDate);
-                                        }
-                                    }
-                                    readFile(policyAdapter, entity);
-                                }
-                            }
-                        }
+        if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+            return;
+        }
+        Object policyData = policyAdapter.getPolicyData();
+        PolicyType policy = (PolicyType) policyData;
+        policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+        String policyNameValue =
+                policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4);
+        policyAdapter.setPolicyName(policyNameValue);
+        String description = "";
+        try {
+            description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+        } catch (Exception e) {
+            LOGGER.error("Error while collecting the description tag in " + policyNameValue, e);
+            description = policy.getDescription();
+        }
+        policyAdapter.setPolicyDescription(description);
+        // Get the target data under policy.
+        TargetType target = policy.getTarget();
+        if (target == null) {
+            return;
+        }
+        for (AnyOfType anyOf : target.getAnyOf()) {
+            for (AllOfType allOf : anyOf.getAllOf()) {
+                for (MatchType match : allOf.getMatch()) {
+                    //
+                    // Under the match we have attribute value and
+                    // attributeDesignator. So,finally down to the actual attribute.
+                    //
+                    AttributeValueType attributeValue = match.getAttributeValue();
+                    String value = (String) attributeValue.getContent().get(0);
+                    AttributeDesignatorType designator = match.getAttributeDesignator();
+                    String attributeId = designator.getAttributeId();
+                    // First match in the target is OnapName, so set that value.
+                    if ("ONAPName".equals(attributeId)) {
+                        policyAdapter.setOnapName(value);
+                    }
+                    if ("RiskType".equals(attributeId)) {
+                        policyAdapter.setRiskType(value);
+                    }
+                    if ("RiskLevel".equals(attributeId)) {
+                        policyAdapter.setRiskLevel(value);
+                    }
+                    if ("guard".equals(attributeId)) {
+                        policyAdapter.setGuard(value);
+                    }
+                    if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
+                        PolicyController controller = new PolicyController();
+                        String newDate = controller.convertDate(value);
+                        policyAdapter.setTtlDate(newDate);
                     }
                 }
+                readFile(policyAdapter, entity);
             }
         }
     }
@@ -617,6 +631,14 @@ public class CreateOptimizationController extends RestrictedBaseController {
 
     }
 
+    /**
+     * setModelData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @throws IOException IOException
+     * @throws FileUploadException FileUploadException
+     */
     @RequestMapping(
             value = {"/oof_dictionary/set_ModelData"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -661,16 +683,10 @@ public class CreateOptimizationController extends RestrictedBaseController {
         }
 
         if (!errorMsg.isEmpty()) {
-
-            PrintWriter out = response.getWriter();
-
             response.setCharacterEncoding(UTF8);
             response.setContentType(APPLICATIONJSON);
             request.setCharacterEncoding(UTF8);
-
-            JSONObject j = new JSONObject();
-            j.put("errorMsg", errorMsg);
-            out.write(j.toString());
+            response.getWriter().write(new JSONObject().put("errorMsg", errorMsg).toString());
             return;
         }
 
@@ -737,20 +753,18 @@ public class CreateOptimizationController extends RestrictedBaseController {
 
         }
 
-        PrintWriter out = response.getWriter();
-
         response.setCharacterEncoding(UTF8);
         response.setContentType(APPLICATIONJSON);
         request.setCharacterEncoding(UTF8);
 
         ObjectMapper mapper = new ObjectMapper();
-        JSONObject j = new JSONObject();
-        j.put("classListDatas", modelList);
-        j.put("modelDatas", mapper.writeValueAsString(classMap));
-        j.put("modelType", modelType);
-        j.put("dataOrderInfo", modelUtil.getDataOrderInfo());
+        JSONObject json = new JSONObject();
+        json.put("classListDatas", modelList);
+        json.put("modelDatas", mapper.writeValueAsString(classMap));
+        json.put("modelType", modelType);
+        json.put("dataOrderInfo", modelUtil.getDataOrderInfo());
 
-        out.write(j.toString());
+        response.getWriter().write(json.toString());
     }
 
     /*
@@ -758,7 +772,6 @@ public class CreateOptimizationController extends RestrictedBaseController {
      */
     @SuppressWarnings("rawtypes")
     private void extractFolder(String zipFile) {
-        int BUFFER = 2048;
         File file = new File(zipFile);
 
         try (ZipFile zip = new ZipFile(file)) {
@@ -815,16 +828,12 @@ public class CreateOptimizationController extends RestrictedBaseController {
 
         classMap.putAll(tempMap);
         LOGGER.info(tempMap);
-
-        return;
-
     }
 
     private List<File> listModelFiles(String directoryName) {
         File fileDirectory = new File(directoryName);
         List<File> resultList = new ArrayList<>();
-        File[] fList = fileDirectory.listFiles();
-        for (File file : fList) {
+        for (File file : fileDirectory.listFiles()) {
             if (file.isFile()) {
                 resultList.add(file);
             } else if (file.isDirectory()) {
@@ -837,9 +846,9 @@ public class CreateOptimizationController extends RestrictedBaseController {
 
     private List<String> createList() {
         List<String> list = new ArrayList<>();
-        for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
-            if (cMap.getValue().isPolicyTempalate()) {
-                list.add(cMap.getKey());
+        for (Entry<String, MSAttributeObject> entrySet : classMap.entrySet()) {
+            if (entrySet.getValue().isPolicyTempalate()) {
+                list.add(entrySet.getKey());
             }
 
         }
index f7295d5..7112285 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -22,7 +22,6 @@ package org.onap.policy.controller;
 
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 
@@ -51,100 +50,99 @@ public class CreatePolicyController extends RestrictedBaseController {
     private ArrayList<Object> attributeList;
     boolean isValidForm = false;
 
+    /**
+     * prePopulateBaseConfigPolicyData.
+     *
+     * @param policyAdapter PolicyRestAdapter
+     * @param entity PolicyEntity
+     */
     public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
         attributeList = new ArrayList<>();
-        if (policyAdapter.getPolicyData() instanceof PolicyType) {
-            Object policyData = policyAdapter.getPolicyData();
-            PolicyType policy = (PolicyType) policyData;
-            policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-            policyAdapter.setConfigType(entity.getConfigurationData().getConfigType());
-            policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
-            String policyNameValue =
-                    policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1);
-            policyAdapter.setPolicyName(policyNameValue);
-            String description = "";
-            try {
-                description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
-            } catch (Exception e) {
-                policyLogger.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
-                description = policy.getDescription();
-            }
-            policyAdapter.setPolicyDescription(description);
-            // Get the target data under policy.
-            TargetType target = policy.getTarget();
-            if (target != null) {
-                // Under target we have AnyOFType
-                List<AnyOfType> anyOfList = target.getAnyOf();
-                if (anyOfList != null) {
-                    Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
-                    while (iterAnyOf.hasNext()) {
-                        AnyOfType anyOf = iterAnyOf.next();
-                        // Under AnyOFType we have AllOFType
-                        List<AllOfType> allOfList = anyOf.getAllOf();
-                        if (allOfList != null) {
-                            Iterator<AllOfType> iterAllOf = allOfList.iterator();
-                            int index = 0;
-                            while (iterAllOf.hasNext()) {
-                                AllOfType allOf = iterAllOf.next();
-                                // Under AllOFType we have Match
-                                List<MatchType> matchList = allOf.getMatch();
-                                if (matchList != null) {
-                                    Iterator<MatchType> iterMatch = matchList.iterator();
-                                    while (iterMatch.hasNext()) {
-                                        MatchType match = iterMatch.next();
-                                        //
-                                        // Under the match we have attribute value and
-                                        // attributeDesignator. So,finally down to the actual attribute.
-                                        //
-                                        AttributeValueType attributeValue = match.getAttributeValue();
-                                        String value = (String) attributeValue.getContent().get(0);
-                                        AttributeDesignatorType designator = match.getAttributeDesignator();
-                                        String attributeId = designator.getAttributeId();
-                                        // First match in the target is OnapName, so set that value.
-                                        if ("ONAPName".equals(attributeId)) {
-                                            policyAdapter.setOnapName(value);
-                                        }
-                                        if ("RiskType".equals(attributeId)) {
-                                            policyAdapter.setRiskType(value);
-                                        }
-                                        if ("RiskLevel".equals(attributeId)) {
-                                            policyAdapter.setRiskLevel(value);
-                                        }
-                                        if ("guard".equals(attributeId)) {
-                                            policyAdapter.setGuard(value);
-                                        }
-                                        if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
-                                            PolicyController controller = new PolicyController();
-                                            String newDate = controller.convertDate(value);
-                                            policyAdapter.setTtlDate(newDate);
-                                        }
-                                        if ("ConfigName".equals(attributeId)) {
-                                            policyAdapter.setConfigName(value);
-                                        }
-                                        // After Onap and Config it is optional to have attributes, so
-                                        // check weather dynamic values or there or not.
-                                        if (index >= 7) {
-                                            Map<String, String> attribute = new HashMap<>();
-                                            attribute.put("key", attributeId);
-                                            attribute.put("value", value);
-                                            attributeList.add(attribute);
-                                        }
-                                        index++;
-                                    }
-                                }
-                            }
+        if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+            return;
+        }
+        Object policyData = policyAdapter.getPolicyData();
+        PolicyType policy = (PolicyType) policyData;
+        policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+        policyAdapter.setConfigType(entity.getConfigurationData().getConfigType());
+        policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
+        String policyNameValue =
+                policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1);
+        policyAdapter.setPolicyName(policyNameValue);
+        String description = "";
+        try {
+            description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+        } catch (Exception e) {
+            policyLogger.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
+            description = policy.getDescription();
+        }
+        policyAdapter.setPolicyDescription(description);
+        // Get the target data under policy.
+        TargetType target = policy.getTarget();
+        //
+        // NOTE: target.getAnyOf() will NEVER return null
+        //
+        if (target != null) {
+            // Under target we have AnyOFType
+            for (AnyOfType anyOf : target.getAnyOf()) {
+                // Under AnyOFType we have AllOFType
+                //
+                // NOTE: anyOf.getAllOf() will NEVER return null
+                //
+                int index = 0;
+                for (AllOfType allOf : anyOf.getAllOf()) {
+                    // Under AllOFType we have Match
+                    // NOTE: allOf.getMatch() will NEVER be NULL
+                    //
+                    for (MatchType match : allOf.getMatch()) {
+                        //
+                        // Under the match we have attribute value and
+                        // attributeDesignator. So,finally down to the actual attribute.
+                        //
+                        AttributeValueType attributeValue = match.getAttributeValue();
+                        String value = (String) attributeValue.getContent().get(0);
+                        AttributeDesignatorType designator = match.getAttributeDesignator();
+                        String attributeId = designator.getAttributeId();
+                        // First match in the target is OnapName, so set that value.
+                        if ("ONAPName".equals(attributeId)) {
+                            policyAdapter.setOnapName(value);
+                        }
+                        if ("RiskType".equals(attributeId)) {
+                            policyAdapter.setRiskType(value);
+                        }
+                        if ("RiskLevel".equals(attributeId)) {
+                            policyAdapter.setRiskLevel(value);
+                        }
+                        if ("guard".equals(attributeId)) {
+                            policyAdapter.setGuard(value);
                         }
+                        if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
+                            PolicyController controller = new PolicyController();
+                            String newDate = controller.convertDate(value);
+                            policyAdapter.setTtlDate(newDate);
+                        }
+                        if ("ConfigName".equals(attributeId)) {
+                            policyAdapter.setConfigName(value);
+                        }
+                        // After Onap and Config it is optional to have attributes, so
+                        // check weather dynamic values or there or not.
+                        if (index >= 7) {
+                            Map<String, String> attribute = new HashMap<>();
+                            attribute.put("key", attributeId);
+                            attribute.put("value", value);
+                            attributeList.add(attribute);
+                        }
+                        index++;
                     }
                 }
-
-                policyAdapter.setAttributes(attributeList);
             }
-            List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
-            for (Object o : ruleList) {
-                if (o instanceof RuleType) {
-                    // get the condition data under the rule for rule Algorithms.
-                    policyAdapter.setRuleID(((RuleType) o).getRuleId());
-                }
+            policyAdapter.setAttributes(attributeList);
+        }
+        List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+        for (Object object : ruleList) {
+            if (object instanceof RuleType) {
+                // get the condition data under the rule for rule Algorithms.
+                policyAdapter.setRuleID(((RuleType) object).getRuleId());
             }
         }
     }
index b90cc52..891398a 100644 (file)
@@ -122,7 +122,7 @@ public class DashboardController extends RestrictedBaseController {
 
     /**
      * This method is to retrieve all the data of last 30 days from PolicyEntity table as default.
-     * 
+     *
      * @param request object
      * @param response object contains retrieved data
      */
@@ -137,9 +137,7 @@ public class DashboardController extends RestrictedBaseController {
             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
             addPolicyCrudInfoToTable();
             model.put("papStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             policyLogger.error(exceptionOccured, e);
         }
@@ -147,7 +145,7 @@ public class DashboardController extends RestrictedBaseController {
 
     /**
      * This method retrieves data based on input criteria.
-     * 
+     *
      * @param request object
      * @param response object contains retrieved data
      */
@@ -188,9 +186,7 @@ public class DashboardController extends RestrictedBaseController {
             getPolicyData(lscope, lstage, isDelected, ttlDateAfter, ttlDateBefore);
             Map<String, Object> model = new HashMap<>();
             model.put("policyStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             response.setCharacterEncoding("UTF-8");
             PrintWriter out = response.getWriter();
@@ -201,7 +197,7 @@ public class DashboardController extends RestrictedBaseController {
 
     /**
      * This method is to retrieve data from PolicyEntity table.
-     * 
+     *
      * @param request object
      * @param response object contains retrieved data
      */
@@ -215,14 +211,18 @@ public class DashboardController extends RestrictedBaseController {
             ObjectMapper mapper = new ObjectMapper();
             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
             model.put("pdpStatusCRUDData", mapper.writeValueAsString(pdpStatusCrudData));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             policyLogger.error(exceptionOccured, e);
         }
     }
 
+    /**
+     * getData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/get_DashboardLoggingData"},
             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
@@ -232,14 +232,18 @@ public class DashboardController extends RestrictedBaseController {
             Map<String, Object> model = new HashMap<>();
             ObjectMapper mapper = new ObjectMapper();
             model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData()));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             policyLogger.error(exceptionOccured + e);
         }
     }
 
+    /**
+     * getSystemAlertData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/get_DashboardSystemAlertData"},
             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
@@ -249,14 +253,18 @@ public class DashboardController extends RestrictedBaseController {
             Map<String, Object> model = new HashMap<>();
             ObjectMapper mapper = new ObjectMapper();
             model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData()));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             policyLogger.error(exceptionOccured + e);
         }
     }
 
+    /**
+     * getPAPStatusData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/get_DashboardPAPStatusData"},
             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
@@ -268,21 +276,25 @@ public class DashboardController extends RestrictedBaseController {
             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
             addPAPToTable();
             model.put("papTableDatas", mapper.writeValueAsString(papStatusData));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             policyLogger.error(exceptionOccured + e);
         }
     }
 
+    /**
+     * getPDPStatusData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/get_DashboardPDPStatusData"},
             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
             produces = MediaType.APPLICATION_JSON_VALUE)
     public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response) {
         try {
-            Map<String, Object> model = new HashMap<>();
+            final Map<String, Object> model = new HashMap<>();
             ObjectMapper mapper = new ObjectMapper();
             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
             PolicyController controller = getPolicyControllerInstance();
@@ -290,29 +302,32 @@ public class DashboardController extends RestrictedBaseController {
             addPDPToTable();
             model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData));
             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(msg).toString());
         } catch (Exception e) {
             policyLogger.error(exceptionOccured + e);
         }
     }
 
+    /**
+     * getPolicyActivityData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/get_DashboardPolicyActivityData"},
             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
             produces = MediaType.APPLICATION_JSON_VALUE)
     public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response) {
         try {
-            Map<String, Object> model = new HashMap<>();
+            final Map<String, Object> model = new HashMap<>();
             ObjectMapper mapper = new ObjectMapper();
             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
             PolicyController controller = getPolicyControllerInstance();
             this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
             addPolicyToTable();
             model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             policyLogger.error(exceptionOccured + e);
         }
@@ -336,9 +351,9 @@ public class DashboardController extends RestrictedBaseController {
             papStatus = "CANNOT_CONNECT";
             policyLogger.error("Error getting PAP status, PAP not responding to requests", e1);
         }
-        String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+        String papUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
         JSONObject object = new JSONObject();
-        object.put("system", papURL);
+        object.put("system", papUrl);
         object.put("status", papStatus);
         List<Object> data = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
         object.put("noOfPolicy", data.size());
@@ -346,8 +361,8 @@ public class DashboardController extends RestrictedBaseController {
         papStatusData.add(0, object);
     }
 
-    /*
-     * Add the PAP Policy information to the PAP Table
+    /**
+     * Add the PAP Policy information to the PAP Table.
      */
     public void addPolicyCrudInfoToTable() {
         policyStatusCrudData = new ArrayList<>();
@@ -370,7 +385,7 @@ public class DashboardController extends RestrictedBaseController {
             object.put(scope, ((PolicyEntity) data).getScope());
             object.put("policyName", ((PolicyEntity) data).getPolicyName());
             object.put("version", ((PolicyEntity) data).getVersion());
-            if (isPushedToPDP(((PolicyEntity) data).getPolicyId())) {
+            if (isPushedToPdp(((PolicyEntity) data).getPolicyId())) {
                 object.put(stage, "PDP");
             } else {
                 object.put(stage, "PAP");
@@ -396,13 +411,13 @@ public class DashboardController extends RestrictedBaseController {
     /*
      * Add the PDP Policy information to the PDP Table
      */
-    private boolean isPushedToPDP(long policyId) {
+    private boolean isPushedToPdp(long policyId) {
         try {
             String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
             SimpleBindings geParams = new SimpleBindings();
             geParams.put("policyEntityId", policyId);
             List<Object> groupobject = commonClassDao.getDataByQuery(groupEntityquery, geParams);
-            if (groupobject != null && groupobject.size() > 0) {
+            if (groupobject != null && ! groupobject.isEmpty()) {
                 return true;
             }
         } catch (Exception e) {
@@ -488,7 +503,7 @@ public class DashboardController extends RestrictedBaseController {
         object.put(scope, data.getScope());
         object.put("policyName", data.getPolicyName());
         object.put("version", data.getVersion());
-        if (isPushedToPDP(data.getPolicyId())) {
+        if (isPushedToPdp(data.getPolicyId())) {
             object.put(stage, "PDP");
         } else {
             object.put(stage, "PAP");
@@ -512,7 +527,7 @@ public class DashboardController extends RestrictedBaseController {
     }
 
     /**
-     * Add PDP Information to the PDP Table
+     * Add PDP Information to the PDP Table.
      *
      */
     public void addPDPToTable() {
@@ -525,7 +540,7 @@ public class DashboardController extends RestrictedBaseController {
             for (PDP pdp : group.getPdps()) {
                 naCount = -1;
                 if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) {
-                    String pdpIpAddress = parseIPSystem(pdp.getId());
+                    String pdpIpAddress = parseIpSystem(pdp.getId());
                     int port = ((OnapPDP) pdp).getJmxPort();
                     if (port != 0) {
                         policyLogger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port);
@@ -562,7 +577,7 @@ public class DashboardController extends RestrictedBaseController {
         }
     }
 
-    private static String parseIPSystem(String line) {
+    private static String parseIpSystem(String line) {
         Pattern pattern = Pattern.compile("://(.+?):");
         Matcher ip = pattern.matcher(line);
         if (ip.find()) {
@@ -579,12 +594,12 @@ public class DashboardController extends RestrictedBaseController {
 
         policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server");
         HashMap map = null;
-        try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
+        try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) {
             jmxConnection.connect();
-            Object o = jmxConnection.getMBeanServerConnection()
+            Object obj = jmxConnection.getMBeanServerConnection()
                     .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
-            policyLogger.debug("pdpEvaluationNA value retreived: " + o);
-            return (long) o;
+            policyLogger.debug("pdpEvaluationNA value retreived: " + obj);
+            return (long) obj;
         } catch (MalformedURLException e) {
             policyLogger.error("MalformedURLException for JMX connection", e);
         } catch (IOException e) {
@@ -605,7 +620,7 @@ public class DashboardController extends RestrictedBaseController {
         return -1;
     }
 
-    private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException {
+    private static JMXServiceURL createConnectionUrl(String host, int port) throws MalformedURLException {
         return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
     }
 
@@ -633,8 +648,8 @@ public class DashboardController extends RestrictedBaseController {
                 // Add rows to the Policy Table
                 policyList = null;
                 if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) {
-                    String pdpIpAddress = parseIPSystem(pdp.getId());
-                    policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort(), "policyCount");
+                    String pdpIpAddress = parseIpSystem(pdp.getId());
+                    policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort());
                 }
                 if (policyList != null && policyList.toString().length() > 3) {
                     String[] splitPolicy = policyList.toString().split(",");
@@ -650,19 +665,15 @@ public class DashboardController extends RestrictedBaseController {
                         }
                     }
                 } else {
+                    JSONObject object = new JSONObject();
                     if (policyList != null) {
-                        JSONObject object = new JSONObject();
                         object.put("policyId", "Unable to retrieve policy information");
-                        object.put("fireCount", "NA");
-                        object.put("system", pdp.getId());
-                        policyActivityData.add(object);
                     } else {
-                        JSONObject object = new JSONObject();
                         object.put("policyId", "Unable to access PDP JMX Server");
-                        object.put("fireCount", "NA");
-                        object.put("system", pdp.getId());
-                        policyActivityData.add(object);
                     }
+                    object.put("fireCount", "NA");
+                    object.put("system", pdp.getId());
+                    policyActivityData.add(object);
                 }
             }
         }
@@ -672,16 +683,16 @@ public class DashboardController extends RestrictedBaseController {
      * Contact JMX Connector Sever and return the list of {policy id , count}
      */
     @SuppressWarnings({"rawtypes", "unchecked"})
-    private Object getPolicy(String host, int port, String jmxAttribute) {
+    private Object getPolicy(String host, int port) {
         policyLogger
                 .debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
         HashMap map = null;
-        try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
+        try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) {
             jmxConnection.connect();
-            Object o = jmxConnection.getMBeanServerConnection()
+            Object obj = jmxConnection.getMBeanServerConnection()
                     .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
-            policyLogger.debug("policyMap value retreived: " + o);
-            return o;
+            policyLogger.debug("policyMap value retreived: " + obj);
+            return obj;
         } catch (MalformedURLException e) {
             policyLogger.error("MalformedURLException for JMX connection", e);
         } catch (IOException e) {
@@ -711,8 +722,7 @@ public class DashboardController extends RestrictedBaseController {
 
     private static Integer countPolicyID(String line) {
         String[] splitLine = line.split("=");
-        String sCount = splitLine[1].replace("}", "");
-        return Integer.parseInt(sCount);
+        return Integer.parseInt(splitLine[1].replace("}", ""));
     }
 
 }
index d6a4e82..8ecf369 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -83,7 +83,13 @@ public class DecisionPolicyController extends RestrictedBaseController {
         // This constructor is empty
     }
 
-    public void rawXACMLPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+    /**
+     * rawXacmlPolicy. Should this method be private?
+     *
+     * @param policyAdapter PolicyRestAdapter
+     * @param entity PolicyEntity
+     */
+    public void rawXacmlPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
         try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyAdapter.getPolicyData())) {
             String name = StringUtils.substringAfter(entity.getPolicyName(), "Decision_");
             policyAdapter.setPolicyName(name.substring(0, name.indexOf('.')));
@@ -94,6 +100,12 @@ public class DecisionPolicyController extends RestrictedBaseController {
         }
     }
 
+    /**
+     * prePopulateDecisionPolicyData.
+     *
+     * @param policyAdapter PolicyRestAdapter
+     * @param entity PolicyEntity
+     */
     @SuppressWarnings("unchecked")
     public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
         List<Object> attributeList = new ArrayList<>();
@@ -109,237 +121,224 @@ public class DecisionPolicyController extends RestrictedBaseController {
         }
 
         if (rawPolicyCheck) {
-            rawXACMLPolicy(policyAdapter, entity);
-        } else {
-            RainyDayParams rainydayParams = new RainyDayParams();
-            Object policyData = policyAdapter.getPolicyData();
-            PolicyType policy = (PolicyType) policyData;
-            policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-
-            policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
-            String description = "";
-            String blackListEntryType = "Use Manual Entry";
-            try {
-                if (policy.getDescription().contains(BLENTRY)) {
-                    blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
-                            policy.getDescription().lastIndexOf(BLENTRY));
-                }
-                policyAdapter.setBlackListEntryType(blackListEntryType);
-                description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+            rawXacmlPolicy(policyAdapter, entity);
+            return;
+        }
+        RainyDayParams rainydayParams = new RainyDayParams();
+        Object policyData = policyAdapter.getPolicyData();
+        PolicyType policy = (PolicyType) policyData;
+        policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
 
-            } catch (Exception e) {
-                policyLogger.info("General error", e);
-                description = policy.getDescription();
+        policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
+        String description = "";
+        String blackListEntryType = "Use Manual Entry";
+        try {
+            if (policy.getDescription().contains(BLENTRY)) {
+                blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
+                        policy.getDescription().lastIndexOf(BLENTRY));
             }
-            policyAdapter.setPolicyDescription(description);
-            // Get the target data under policy for Action.
-            TargetType target = policy.getTarget();
-            if (target != null) {
-                // under target we have AnyOFType
-                List<AnyOfType> anyOfList = target.getAnyOf();
-                if (anyOfList != null) {
-                    Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
-                    while (iterAnyOf.hasNext()) {
-                        AnyOfType anyOf = iterAnyOf.next();
-                        // Under AntOfType we have AllOfType
-                        List<AllOfType> allOfList = anyOf.getAllOf();
-                        if (allOfList != null) {
-                            Iterator<AllOfType> iterAllOf = allOfList.iterator();
-                            while (iterAllOf.hasNext()) {
-                                AllOfType allOf = iterAllOf.next();
-                                // Under AllOfType we have Mathch.
-                                List<MatchType> matchList = allOf.getMatch();
-                                int index = 0;
-                                if (matchList != null) {
-                                    Iterator<MatchType> iterMatch = matchList.iterator();
-                                    while (iterMatch.hasNext()) {
-                                        MatchType match = iterMatch.next();
-                                        //
-                                        // Under the match we have attributevalue and
-                                        // attributeDesignator. So,finally down to the actual attribute.
-                                        //
-                                        AttributeValueType attributeValue = match.getAttributeValue();
-                                        String value = (String) attributeValue.getContent().get(0);
-                                        if (value != null) {
-                                            value = value.replaceAll("\\(\\?i\\)", "");
-                                        }
-                                        AttributeDesignatorType designator = match.getAttributeDesignator();
-                                        String attributeId = designator.getAttributeId();
-                                        // First match in the target is OnapName, so set that value.
-                                        if ("ONAPName".equals(attributeId)) {
-                                            policyAdapter.setOnapName(value);
-                                        }
-                                        // Component attributes are saved under Target here we are fetching them back.
-                                        // One row is default so we are not adding dynamic component at index 0.
-                                        if (index >= 1) {
-                                            Map<String, String> attribute = new HashMap<>();
-                                            attribute.put("key", attributeId);
-                                            attribute.put("value", value);
-                                            attributeList.add(attribute);
-                                        }
-                                        index++;
-                                    }
-                                }
-                                policyAdapter.setAttributes(attributeList);
-                            }
-                        }
+            policyAdapter.setBlackListEntryType(blackListEntryType);
+            description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+
+        } catch (Exception e) {
+            policyLogger.info("General error", e);
+            description = policy.getDescription();
+        }
+        policyAdapter.setPolicyDescription(description);
+        // Get the target data under policy for Action.
+        TargetType target = policy.getTarget();
+        if (target == null) {
+            rainydayParams.setTreatmentTableChoices(treatmentList);
+            policyAdapter.setRainyday(rainydayParams);
+            policyAdapter.setSettings(decisionList);
+            return;
+        }
+        // under target we have AnyOFType
+        for (AnyOfType anyOf : target.getAnyOf()) {
+            for (AllOfType allOf : anyOf.getAllOf()) {
+                int index = 0;
+                for (MatchType match : allOf.getMatch()) {
+                    //
+                    // Under the match we have attributevalue and
+                    // attributeDesignator. So,finally down to the actual attribute.
+                    //
+                    AttributeValueType attributeValue = match.getAttributeValue();
+                    String value = (String) attributeValue.getContent().get(0);
+                    if (value != null) {
+                        value = value.replaceAll("\\(\\?i\\)", "");
                     }
-                    // Setting rainy day attributes to the parameters object if they exist
-                    boolean rainy = false;
-                    if (!attributeList.isEmpty()) {
-                        for (int i = 0; i < attributeList.size(); i++) {
-                            Map<String, String> map = (Map<String, String>) attributeList.get(i);
-                            if ("WorkStep".equals(map.get("key"))) {
-                                rainydayParams.setWorkstep(map.get("value"));
-                                rainy = true;
-                            } else if ("BB_ID".equals(map.get("key"))) {
-                                rainydayParams.setBbid(map.get("value"));
-                                rainy = true;
-                            } else if ("ServiceType".equals(map.get("key"))) {
-                                rainydayParams.setServiceType(map.get("value"));
-                                rainy = true;
-                            } else if ("VNFType".equals(map.get("key"))) {
-                                rainydayParams.setVnfType(map.get("value"));
-                                rainy = true;
-                            }
-                        }
+                    AttributeDesignatorType designator = match.getAttributeDesignator();
+                    String attributeId = designator.getAttributeId();
+                    // First match in the target is OnapName, so set that value.
+                    if ("ONAPName".equals(attributeId)) {
+                        policyAdapter.setOnapName(value);
                     }
-                    if (rainy) {
-                        policyAdapter.setRuleProvider("Rainy_Day");
+                    // Component attributes are saved under Target here we are fetching them back.
+                    // One row is default so we are not adding dynamic component at index 0.
+                    if (index >= 1) {
+                        Map<String, String> attribute = new HashMap<>();
+                        attribute.put("key", attributeId);
+                        attribute.put("value", value);
+                        attributeList.add(attribute);
                     }
+                    index++;
                 }
+                policyAdapter.setAttributes(attributeList);
+            }
+        }
+        // Setting rainy day attributes to the parameters object if they exist
+        boolean rainy = false;
+        if (!attributeList.isEmpty()) {
+            for (int i = 0; i < attributeList.size(); i++) {
+                Map<String, String> map = (Map<String, String>) attributeList.get(i);
+                String key = map.get("key");
+                if ("WorkStep".equals(key)) {
+                    rainydayParams.setWorkstep(map.get("value"));
+                    rainy = true;
+                } else if ("BB_ID".equals(key)) {
+                    rainydayParams.setBbid(map.get("value"));
+                    rainy = true;
+                } else if ("ServiceType".equals(key)) {
+                    rainydayParams.setServiceType(map.get("value"));
+                    rainy = true;
+                } else if ("VNFType".equals(key)) {
+                    rainydayParams.setVnfType(map.get("value"));
+                    rainy = true;
+                }
+            }
+        }
+        if (rainy) {
+            policyAdapter.setRuleProvider("Rainy_Day");
+        }
 
-                List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
-                int index = 0;
-                for (Object object : ruleList) {
-                    if (object instanceof VariableDefinitionType) {
-                        VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
-                        Map<String, String> settings = new HashMap<>();
-                        settings.put("key", variableDefinitionType.getVariableId());
-                        JAXBElement<AttributeValueType> attributeValueTypeElement =
-                                (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
-                        if (attributeValueTypeElement != null) {
-                            AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
-                            settings.put("value", attributeValueType.getContent().get(0).toString());
+        List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+        int index = 0;
+        for (Object object : ruleList) {
+            if (object instanceof VariableDefinitionType) {
+                VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
+                Map<String, String> settings = new HashMap<>();
+                settings.put("key", variableDefinitionType.getVariableId());
+                JAXBElement<AttributeValueType> attributeValueTypeElement =
+                        (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
+                if (attributeValueTypeElement != null) {
+                    AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
+                    settings.put("value", attributeValueType.getContent().get(0).toString());
+                }
+                decisionList.add(settings);
+            } else if (object instanceof RuleType) {
+                // get the condition data under the rule for rule Algorithms.
+                if (((RuleType) object).getEffect().equals(EffectType.DENY)) {
+                    if (((RuleType) object).getAdviceExpressions() != null) {
+                        if ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+                                .getAdviceExpression().get(0).getAdviceId())) {
+                            policyAdapter.setRuleProvider("AAF");
+                            break;
+                        } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+                                .getAdviceExpression().get(0).getAdviceId())) {
+                            policyAdapter.setRuleProvider(GUARD_YAML);
+                        } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+                                .getAdviceExpression().get(0).getAdviceId())) {
+                            policyAdapter.setRuleProvider(GUARD_BL_YAML);
+                        } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+                                .getAdviceExpression().get(0).getAdviceId())) {
+                            policyAdapter.setRuleProvider(GUARD_MIN_MAX);
                         }
-                        decisionList.add(settings);
-                    } else if (object instanceof RuleType) {
-                        // get the condition data under the rule for rule Algorithms.
-                        if (((RuleType) object).getEffect().equals(EffectType.DENY)) {
-                            if (((RuleType) object).getAdviceExpressions() != null) {
-                                if ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
-                                        .getAdviceExpression().get(0).getAdviceId())) {
-                                    policyAdapter.setRuleProvider("AAF");
-                                    break;
-                                } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
-                                        .getAdviceExpression().get(0).getAdviceId())) {
-                                    policyAdapter.setRuleProvider(GUARD_YAML);
-                                } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
-                                        .getAdviceExpression().get(0).getAdviceId())) {
-                                    policyAdapter.setRuleProvider(GUARD_BL_YAML);
-                                } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
-                                        .getAdviceExpression().get(0).getAdviceId())) {
-                                    policyAdapter.setRuleProvider(GUARD_MIN_MAX);
+                    } else {
+                        policyAdapter.setRuleProvider("Custom");
+                    }
+                    ConditionType condition = ((RuleType) object).getCondition();
+                    if (condition != null) {
+                        ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
+                        decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
+                        ruleAlgoirthmTracker = new LinkedList<>();
+                        if (policyAdapter.getRuleProvider() != null
+                                && (GUARD_YAML.equals(policyAdapter.getRuleProvider())
+                                        || (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider()))
+                                        || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))) {
+                            YAMLParams yamlParams = new YAMLParams();
+                            for (int i = 0; i < attributeList.size(); i++) {
+                                Map<String, String> map = (Map<String, String>) attributeList.get(i);
+                                String key = map.get("key");
+                                if ("actor".equals(key)) {
+                                    yamlParams.setActor(map.get("value"));
+                                } else if ("recipe".equals(key)) {
+                                    yamlParams.setRecipe(map.get("value"));
+                                } else if ("target".equals(key)) {
+                                    yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
+                                } else if ("clname".equals(key)) {
+                                    yamlParams.setClname(map.get("value"));
+                                } else if ("min".equals(key)) {
+                                    yamlParams.setMin(map.get("value"));
+                                } else if ("max".equals(key)) {
+                                    yamlParams.setMax(map.get("value"));
                                 }
-                            } else {
-                                policyAdapter.setRuleProvider("Custom");
                             }
-                            ConditionType condition = ((RuleType) object).getCondition();
-                            if (condition != null) {
-                                ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
-                                decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
-                                ruleAlgoirthmTracker = new LinkedList<>();
-                                if (policyAdapter.getRuleProvider() != null
-                                        && (GUARD_YAML.equals(policyAdapter.getRuleProvider())
-                                                || (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider()))
-                                                || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))) {
-                                    YAMLParams yamlParams = new YAMLParams();
-                                    for (int i = 0; i < attributeList.size(); i++) {
-                                        Map<String, String> map = (Map<String, String>) attributeList.get(i);
-                                        if ("actor".equals(map.get("key"))) {
-                                            yamlParams.setActor(map.get("value"));
-                                        } else if ("recipe".equals(map.get("key"))) {
-                                            yamlParams.setRecipe(map.get("value"));
-                                        } else if ("target".equals(map.get("key"))) {
-                                            yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
-                                        } else if ("clname".equals(map.get("key"))) {
-                                            yamlParams.setClname(map.get("value"));
-                                        } else if ("min".equals(map.get("key"))) {
-                                            yamlParams.setMin(map.get("value"));
-                                        } else if ("max".equals(map.get("key"))) {
-                                            yamlParams.setMax(map.get("value"));
-                                        }
-                                    }
-                                    ApplyType apply =
-                                            (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue())
-                                                    .getExpression().get(0).getValue();
-                                    yamlParams.setGuardActiveStart(
-                                            ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent()
-                                                    .get(0).toString());
-                                    yamlParams.setGuardActiveEnd(
-                                            ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent()
-                                                    .get(0).toString());
-                                    if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
-                                        apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
-                                                .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
-                                                        .get(2).getValue();
-                                        Iterator<JAXBElement<?>> attributes = apply.getExpression().iterator();
-                                        List<String> blackList = new ArrayList<>();
-                                        while (attributes.hasNext()) {
-                                            blackList.add(((AttributeValueType) attributes.next().getValue())
-                                                    .getContent().get(0).toString());
-                                        }
-                                        yamlParams.setBlackList(blackList);
-                                        if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
-                                            policyAdapter.setBlackListEntries(blackList);
-                                        }
-                                    } else {
-                                        ApplyType timeWindowSection = (ApplyType) ((ApplyType) decisionApply
-                                                .getExpression().get(0).getValue()).getExpression().get(1).getValue();
-                                        yamlParams.setLimit(((AttributeValueType) timeWindowSection.getExpression()
-                                                .get(1).getValue()).getContent().get(0).toString());
-                                        String timeWindow = ((AttributeDesignatorType) ((ApplyType) timeWindowSection
-                                                .getExpression().get(0).getValue()).getExpression().get(0).getValue())
-                                                        .getIssuer();
-                                        yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1));
-                                        yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4,
-                                                timeWindow.lastIndexOf(':')));
-                                    }
-                                    policyAdapter.setYamlparams(yamlParams);
-                                    policyAdapter.setAttributes(new ArrayList<Object>());
-                                    policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
-                                    break;
+                            ApplyType apply =
+                                    (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue())
+                                            .getExpression().get(0).getValue();
+                            yamlParams.setGuardActiveStart(
+                                    ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent()
+                                            .get(0).toString());
+                            yamlParams.setGuardActiveEnd(
+                                    ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent()
+                                            .get(0).toString());
+                            if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
+                                apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
+                                        .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
+                                                .get(2).getValue();
+                                List<String> blackList = new ArrayList<>();
+                                for (JAXBElement<?> attr : apply.getExpression()) {
+                                    blackList.add(((AttributeValueType) attr.getValue())
+                                            .getContent().get(0).toString());
                                 }
-                                // Populating Rule Algorithms starting from compound.
-                                prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
-                                policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
+                                yamlParams.setBlackList(blackList);
+                                if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
+                                    policyAdapter.setBlackListEntries(blackList);
+                                }
+                            } else {
+                                ApplyType timeWindowSection = (ApplyType) ((ApplyType) decisionApply
+                                        .getExpression().get(0).getValue()).getExpression().get(1).getValue();
+                                yamlParams.setLimit(((AttributeValueType) timeWindowSection.getExpression()
+                                        .get(1).getValue()).getContent().get(0).toString());
+                                String timeWindow = ((AttributeDesignatorType) ((ApplyType) timeWindowSection
+                                        .getExpression().get(0).getValue()).getExpression().get(0).getValue())
+                                                .getIssuer();
+                                yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1));
+                                yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4,
+                                        timeWindow.lastIndexOf(':')));
                             }
-                        } else if (policyAdapter.getRuleProvider() != null
-                                && "Rainy_Day".equals(policyAdapter.getRuleProvider())
-                                && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
+                            policyAdapter.setYamlparams(yamlParams);
+                            policyAdapter.setAttributes(new ArrayList<Object>());
+                            policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
+                            break;
+                        }
+                        // Populating Rule Algorithms starting from compound.
+                        prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
+                        policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
+                    }
+                } else if (policyAdapter.getRuleProvider() != null
+                        && "Rainy_Day".equals(policyAdapter.getRuleProvider())
+                        && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
 
-                            TargetType ruleTarget = ((RuleType) object).getTarget();
-                            AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
+                    TargetType ruleTarget = ((RuleType) object).getTarget();
+                    AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
 
-                            String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1)
-                                    .getAttributeValue().getContent().get(0).toString();
-                            JAXBElement<AttributeValueType> tempTreatmentObj =
-                                    (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0)
-                                            .getAttributeAssignmentExpression().get(0).getExpression();
-                            String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
+                    String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1)
+                            .getAttributeValue().getContent().get(0).toString();
+                    JAXBElement<AttributeValueType> tempTreatmentObj =
+                            (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0)
+                                    .getAttributeAssignmentExpression().get(0).getExpression();
+                    String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
 
-                            prePopulateRainyDayTreatments(errorcode, treatment);
+                    prePopulateRainyDayTreatments(errorcode, treatment);
 
-                        }
-                    }
                 }
             }
-
-            rainydayParams.setTreatmentTableChoices(treatmentList);
-            policyAdapter.setRainyday(rainydayParams);
-            policyAdapter.setSettings(decisionList);
         }
 
+        rainydayParams.setTreatmentTableChoices(treatmentList);
+        policyAdapter.setRainyday(rainydayParams);
+        policyAdapter.setSettings(decisionList);
     }
 
     private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
@@ -404,36 +403,36 @@ public class DecisionPolicyController extends RestrictedBaseController {
                 index++;
             }
         }
-        if (isCompoundRule) {
-            // As it's compound rule, Get the Apply types
-            for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
-                ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
-                index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
-            }
-            // Populate combo box
-            if (policyLogger.isDebugEnabled()) {
-                policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
-            }
-            Map<String, String> rule = new HashMap<>();
-            for (String key : PolicyController.getDropDownMap().keySet()) {
-                String keyValue = PolicyController.getDropDownMap().get(key);
-                if (keyValue.equals(decisionApply.getFunctionId())) {
-                    rule.put("dynamicRuleAlgorithmCombo", key);
-                    break;
-                }
+        if (! isCompoundRule) {
+            return index;
+        }
+        // As it's compound rule, Get the Apply types
+        for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
+            ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
+            index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
+        }
+        // Populate combo box
+        if (policyLogger.isDebugEnabled()) {
+            policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
+        }
+        Map<String, String> rule = new HashMap<>();
+        for (String key : PolicyController.getDropDownMap().keySet()) {
+            String keyValue = PolicyController.getDropDownMap().get(key);
+            if (keyValue.equals(decisionApply.getFunctionId())) {
+                rule.put("dynamicRuleAlgorithmCombo", key);
+                break;
             }
-
-            rule.put("id", "A" + (index + 1));
-            // Populate Key and values for Compound Rule
-            rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1));
-            ruleAlgoirthmTracker.removeLast();
-            rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
-            ruleAlgoirthmTracker.removeLast();
-            ruleAlgoirthmTracker.addLast(index);
-            ruleAlgorithmList.add(rule);
-            index++;
         }
 
-        return index;
+        rule.put("id", "A" + (index + 1));
+        // Populate Key and values for Compound Rule
+        rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1));
+        ruleAlgoirthmTracker.removeLast();
+        rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
+        ruleAlgoirthmTracker.removeLast();
+        ruleAlgoirthmTracker.addLast(index);
+        ruleAlgorithmList.add(rule);
+
+        return ++index;
     }
 }
index 1cfdbb7..b50ca6d 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -85,7 +85,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
     /**
      * This method is used to Export the Black List entries data from Decision BlackList Guard YAML Policy. So, user can
      * update the file on adding or removing the entries, for updating the policies or using in other Environments.
-     * 
+     *
      * @param request the request contains the policy data. So, based on that we can populate and read and write the
      *        entries.
      * @param response after reading and writing the blacklist list entries to file, the file is copied to tmp directory
@@ -118,7 +118,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
 
             /*
              * Export FileName is the combination of BlacList+Scope+PolicyName+Version+PolicyCreatedDate.
-             * 
+             *
              */
 
             SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@@ -164,7 +164,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
     /**
      * This method is used to import the BlackList excel file into the system. Which is used to create Decision
      * Blacklist Guard YAML Policy.
-     * 
+     *
      * @param request the HTTP request contains file upload stream form GUI.
      * @param response the response is send to the GUI after reading the file input stream.
      */
@@ -182,9 +182,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
             } else {
                 readItems(items, errorLogs, model);
             }
-            JsonMessage msg = new JsonMessage(mapper.toJson(model));
-            JSONObject jsonResposne = new JSONObject(msg);
-            response.getWriter().write(jsonResposne.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.toJson(model))).toString());
         } catch (FileUploadException | IOException e) {
             policyLogger.error("Exception Occured while importing the BlackListEntry", e);
         }
@@ -192,7 +190,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
 
     /**
      * This method is used to read the first item, as we expect only one entry in the file upload.
-     * 
+     *
      * @param items The file entries which were uploaded from GUI.
      * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
      * @param model Map which stores key value (blacklist and append list data)
@@ -219,7 +217,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
 
     /**
      * This method is used to read the workbook in xls file item.
-     * 
+     *
      * @param fileName fileName as input parameter
      * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
      * @param model Map which stores key value (blacklist and append list data)
@@ -247,7 +245,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
 
     /**
      * This method is used to read all the rows from imported Excel sheet and set to respective objects.
-     * 
+     *
      * @param rowIterator Excel Sheet rows are passed as input parameters.
      * @param blackListEntries the data is set to this object, which is going to be added.
      * @param appendBlackListEntries the data is set to this object which is going to be removed.
@@ -267,7 +265,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
 
     /**
      * This method is used to read all the cells in the row.
-     * 
+     *
      * @param cellIterator iterating the cells and will parse based on the cell type.
      * @param blackListEntries the data is set to this object, which is going to be added.
      * @param appendBlackListEntries the data is set to this object which is going to be removed.
@@ -301,7 +299,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
 
     /**
      * This method is used to read the Action cell entry.
-     * 
+     *
      * @param cell reading the action entry cell.
      * @param lineNo counts the number of the cell.
      * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
@@ -329,7 +327,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
 
     /**
      * This method is used to read the BlackList cell entry.
-     * 
+     *
      * @param cell reading the blacklist entry cell.
      * @param lineNo counts the number of the cell.
      * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
@@ -354,7 +352,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
 
     /**
      * This method is used to add the data to blacklist and append list after parsing each and every row.
-     * 
+     *
      * @param actionEntry it has the input to add or not and holds either 0 or 1.
      * @param blackListEntries list to add blacklist entries based on action entry = 1.
      * @param appendBlackListEntries list to add append list entries based on action entry = 0.
@@ -371,7 +369,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
 
     /**
      * This method is used to identify the header of the cell.
-     * 
+     *
      * @param cell Excel sheet cell is passed as input parameter.
      * @return the column header name value
      */
index 56d882f..ae866c4 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -47,7 +47,6 @@ import org.onap.policy.model.PDPGroupContainer;
 import org.onap.policy.utils.UserUtils.Pair;
 import org.onap.policy.xacml.api.XACMLErrorConstants;
 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
-import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
 import org.onap.policy.xacml.std.pap.StdPDP;
 import org.onap.policy.xacml.std.pap.StdPDPGroup;
 import org.onap.portalsdk.core.controller.RestrictedBaseController;
@@ -83,6 +82,11 @@ public class PDPController extends RestrictedBaseController {
         this.policyController = policyController;
     }
 
+    /**
+     * refreshGroups.
+     *
+     * @param request HttpServletRequest
+     */
     public synchronized void refreshGroups(HttpServletRequest request) {
         synchronized (this.groups) {
             this.groups.clear();
@@ -94,11 +98,11 @@ public class PDPController extends RestrictedBaseController {
                 String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId();
                 List<Object> userRoles = controller.getRoles(userId);
                 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
-                roles = pair.u;
-                scopes = pair.t;
+                roles = pair.second;
+                scopes = pair.first;
 
                 if (!junit && controller.getPapEngine() == null) {
-                    setPAPEngine(request);
+                    setPapEngine(request);
                 }
                 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
                     if (!junit) {
@@ -148,35 +152,44 @@ public class PDPController extends RestrictedBaseController {
         }
     }
 
-    private void setPAPEngine(HttpServletRequest request) {
-        String myRequestURL = request.getRequestURL().toString();
+    private void setPapEngine(HttpServletRequest request) {
         try {
             //
             // Set the URL for the RESTful PAP Engine
             //
-            PolicyController.setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
+            PolicyController.setPapEngine(new RESTfulPAPEngine(request.getRequestURL().toString()));
         } catch (Exception e) {
             policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP", e);
         }
     }
 
+    /**
+     * getPDPGroupEntityData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/get_PDPGroupData"},
             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
             produces = MediaType.APPLICATION_JSON_VALUE)
     public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response) {
         try {
-            ObjectMapper mapper = new ObjectMapper();
             refreshGroups(request);
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(
+                    new ObjectMapper().writeValueAsString(groups))).toString());
         } catch (Exception e) {
             policyLogger.error(
                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while retrieving the PDP Group data" + e);
         }
     }
 
+    /**
+     * savePDPGroup.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/pdp_Group/save_pdp_group"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -190,10 +203,10 @@ public class PDPController extends RestrictedBaseController {
 
             String userId = UserUtils.getUserSession(request).getOrgUserId();
             policyLogger.info(
-                    "****************************************Logging UserID for Save PDP Group Function*****************************************");
+                    "*******************Logging UserID for Save PDP Group Function*******************************");
             policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpGroupData").toString());
             policyLogger.info(
-                    "***************************************************************************************************************************");
+                    "********************************************************************************************");
 
             StdPDPGroup pdpGroupData = mapper
                     .readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
@@ -214,11 +227,8 @@ public class PDPController extends RestrictedBaseController {
             response.setContentType("application / json");
             request.setCharacterEncoding("UTF-8");
 
-            PrintWriter out = response.getWriter();
             refreshGroups(request);
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
-            JSONObject j = new JSONObject(msg);
-            out.write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
         } catch (Exception e) {
             policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e);
             response.setCharacterEncoding("UTF-8");
@@ -234,6 +244,12 @@ public class PDPController extends RestrictedBaseController {
         }
     }
 
+    /**
+     * removePDPGroup.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/pdp_Group/remove_pdp_group"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -247,10 +263,10 @@ public class PDPController extends RestrictedBaseController {
 
             String userId = UserUtils.getUserSession(request).getOrgUserId();
             policyLogger.info(
-                    "****************************************Logging UserID for Remove PDP Group Function*****************************************");
+                    "*********************Logging UserID for Remove PDP Group Function*******************************");
             policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpGroupData").toString());
             policyLogger.info(
-                    "*****************************************************************************************************************************");
+                    "************************************************************************************************");
 
             StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
             if ("Default".equals(pdpGroupData.getName())) {
@@ -262,13 +278,8 @@ public class PDPController extends RestrictedBaseController {
             response.setCharacterEncoding("UTF-8");
             response.setContentType("application / json");
             request.setCharacterEncoding("UTF-8");
-
-            PrintWriter out = response.getWriter();
-
             refreshGroups(request);
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
-            JSONObject j = new JSONObject(msg);
-            out.write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
         } catch (Exception e) {
             policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing the PDP Group" + e);
             PrintWriter out;
@@ -283,6 +294,12 @@ public class PDPController extends RestrictedBaseController {
         }
     }
 
+    /**
+     * savePDPToGroup.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/pdp_Group/save_pdpTogroup"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -299,11 +316,11 @@ public class PDPController extends RestrictedBaseController {
 
             String userId = UserUtils.getUserSession(request).getOrgUserId();
             policyLogger.info(
-                    "****************************************Logging UserID while Saving  pdp in  PDP Group*****************************************");
+                    "*************Logging UserID while Saving  pdp in  PDP Group***********************************");
             policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpInGroup").toString()
                     + "Active Group Data: " + root.get("activePDP").toString());
             policyLogger.info(
-                    "*******************************************************************************************************************************");
+                    "**********************************************************************************************");
 
             try {
 
@@ -322,12 +339,8 @@ public class PDPController extends RestrictedBaseController {
             response.setCharacterEncoding("UTF-8");
             response.setContentType("application / json");
             request.setCharacterEncoding("UTF-8");
-
-            PrintWriter out = response.getWriter();
             refreshGroups(request);
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
-            JSONObject j = new JSONObject(msg);
-            out.write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
         } catch (Exception e) {
             policyLogger
                     .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Creating Pdp in PDP Group" + e);
@@ -343,6 +356,12 @@ public class PDPController extends RestrictedBaseController {
         }
     }
 
+    /**
+     * removePDPFromGroup.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     */
     @RequestMapping(
             value = {"/pdp_Group/remove_pdpFromGroup"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -353,36 +372,31 @@ public class PDPController extends RestrictedBaseController {
             JsonNode root = mapper.readTree(request.getReader());
             PolicyController controller = getPolicyControllerInstance();
             this.container = new PDPGroupContainer(controller.getPapEngine());
-            StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
-            StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
 
             String userId = UserUtils.getUserSession(request).getOrgUserId();
             policyLogger.info(
-                    "****************************************Logging UserID while Removing  pdp from  PDP Group*****************************************");
+                    "********************Logging UserID while Removing  pdp from  PDP Group**************************");
             policyLogger.info("UserId:  " + userId + "Delete PDP Group Data:  " + root.get("data").toString()
                     + "Active Group Data: " + root.get("activePDP").toString());
             policyLogger.info(
-                    "***********************************************************************************************************************************");
+                    "************************************************************************************************");
 
+            StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
+            StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
             this.container.removePDP(deletePdp, activeGroupData);
             response.setCharacterEncoding("UTF-8");
             response.setContentType("application / json");
             request.setCharacterEncoding("UTF-8");
 
-            PrintWriter out = response.getWriter();
             refreshGroups(request);
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
-            JSONObject j = new JSONObject(msg);
-            out.write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
         } catch (Exception e) {
             policyLogger.error(
                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing Pdp from PDP Group" + e);
-            PrintWriter out;
             try {
                 response.setCharacterEncoding("UTF-8");
                 request.setCharacterEncoding("UTF-8");
-                out = response.getWriter();
-                out.write(e.getMessage());
+                response.getWriter().write(e.getMessage());
             } catch (Exception e1) {
                 policyLogger.error("Exception Occured" + e1);
             }
index 78fb873..7769ac7 100644 (file)
@@ -164,8 +164,8 @@ public class PolicyController extends RestrictedBaseController {
         return jUnit;
     }
 
-    public static void setjUnit(boolean jUnit) {
-        PolicyController.jUnit = jUnit;
+    public static void setjUnit(boolean isJunit) {
+        PolicyController.jUnit = isJunit;
     }
 
     @Autowired
@@ -321,9 +321,7 @@ public class PolicyController extends RestrictedBaseController {
             ObjectMapper mapper = new ObjectMapper();
             model.put("functionDefinitionDatas",
                     mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             policyLogger.error(
                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while retriving the Function Definition data" + e);
@@ -378,9 +376,7 @@ public class PolicyController extends RestrictedBaseController {
             Map<String, Object> model = new HashMap<>();
             ObjectMapper mapper = new ObjectMapper();
             model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             policyLogger.error("Exception Occured" + e);
         }
@@ -439,7 +435,7 @@ public class PolicyController extends RestrictedBaseController {
             } else {
                 userRoles = getRoles(userId);
                 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
-                roles = pair.u;
+                roles = pair.second;
                 if (!roles.contains(filteredRole)) {
                     savePolicyRoles(name, filteredRole, userId);
                 }
@@ -601,11 +597,11 @@ public class PolicyController extends RestrictedBaseController {
     /**
      * Switch Version Policy Content.
      *
-     * @param pName which is used to find associated versions.
+     * @param thePolicyName which is used to find associated versions.
      * @return list of available versions based on policy name.
      */
-    public JSONObject switchVersionPolicyContent(String pName) {
-        String policyName = pName;
+    public JSONObject switchVersionPolicyContent(String thePolicyName) {
+        String policyName = thePolicyName;
         String dbCheckName = policyName.replace("/", ".");
         if (dbCheckName.contains("Config_")) {
             dbCheckName = dbCheckName.replace(".Config_", ":Config_");
@@ -621,14 +617,13 @@ public class PolicyController extends RestrictedBaseController {
         SimpleBindings params = new SimpleBindings();
         params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
         params.put("splitDBCheckName0", splitDbCheckName[0]);
-        List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
         List<String> av = new ArrayList<>();
-        for (Object entity : policyEntity) {
-            PolicyEntity pEntity = (PolicyEntity) entity;
-            String removeExtension = pEntity.getPolicyName().replace(".xml", "");
+        for (Object entity : commonClassDao.getDataByQuery(query, params)) {
+            PolicyEntity policyEntity = (PolicyEntity) entity;
+            String removeExtension = policyEntity.getPolicyName().replace(".xml", "");
             String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1);
-            String userName = getUserId(pEntity, "@ModifiedBy:");
-            av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName);
+            String userName = getUserId(policyEntity, "@ModifiedBy:");
+            av.add(version + " | " + policyEntity.getModifiedDate() + " | " + userName);
         }
         if (policyName.contains("/")) {
             policyName = policyName.replace("/", File.separator);
@@ -642,13 +637,20 @@ public class PolicyController extends RestrictedBaseController {
         return el;
     }
 
+    /**
+     * getUserId.
+     *
+     * @param data PolicyEntity
+     * @param value String
+     * @return String
+     */
     public String getUserId(PolicyEntity data, String value) {
         String userId = "";
-        String uValue = value;
+        String userValue = value; // Why?
         String description = getDescription(data);
-        if (description.contains(uValue)) {
-            userId = description.substring(description.indexOf(uValue) + uValue.length(),
-                    description.lastIndexOf(uValue));
+        if (description.contains(userValue)) {
+            userId = description.substring(description.indexOf(userValue) + userValue.length(),
+                    description.lastIndexOf(userValue));
         }
         UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId);
         if (userInfo == null) {
@@ -657,6 +659,12 @@ public class PolicyController extends RestrictedBaseController {
         return userInfo.getUserName();
     }
 
+    /**
+     * getDescription.
+     *
+     * @param data PolicyEntity
+     * @return String
+     */
     public String getDescription(PolicyEntity data) {
         InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
         Object policy = XACMLPolicyScanner.readPolicy(stream);
@@ -664,13 +672,19 @@ public class PolicyController extends RestrictedBaseController {
             return ((PolicySetType) policy).getDescription();
         } else if (policy instanceof PolicyType) {
             return ((PolicyType) policy).getDescription();
-        } else {
-            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: "
-                    + policy.getClass().getCanonicalName());
-            return null;
         }
+        PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: "
+                + policy.getClass().getCanonicalName());
+        return null;
     }
 
+    /**
+     * getUserInfo.
+     *
+     * @param data PolicyEntity
+     * @param activePolicies list of active policies
+     * @return array of String
+     */
     public String[] getUserInfo(PolicyEntity data, List<PolicyVersion> activePolicies) {
         String policyName = data.getScope().replace(".", File.separator) + File.separator
                 + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.'));
@@ -963,14 +977,14 @@ public class PolicyController extends RestrictedBaseController {
     /**
      * Function to convert date.
      *
-     * @param dateTTL input date value.
+     * @param dateTimeToLive input date value.
      * @return
      */
-    public String convertDate(String dateTTL) {
-        String formateDate = null;
-        if (dateTTL.contains("-")) {
-            formateDate = dateTTL.replace("-", "/");
+    public String convertDate(String dateTimeToLive) {
+        String formatDate = null;
+        if (dateTimeToLive.contains("-")) {
+            formatDate = dateTimeToLive.replace("-", "/");
         }
-        return formateDate;
+        return formatDate;
     }
 }
index 11075ef..380341f 100644 (file)
@@ -268,8 +268,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
         // Check if the Role and Scope Size are Null get the values from db.
         List<Object> userRoles = controller.getRoles(userId);
         Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
-        List<String> roles = pair.u;
-        Set<String> scopes = pair.t;
+        List<String> roles = pair.second;
+        Set<String> scopes = pair.first;
 
         try (FileInputStream excelFile = new FileInputStream(new File(file));
                 HSSFWorkbook workbook = new HSSFWorkbook(excelFile)) {
@@ -563,6 +563,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
         return false;
     }
 
+    @SuppressWarnings("rawtypes")
     private boolean isContinue(List<String> roles, String scope, UserInfo userInfo, Set scopes) {
         if (roles.contains(admin) || roles.contains(editor)) {
             if (scopes.isEmpty()) {
index eeff137..51bc3e9 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -21,7 +21,7 @@
 package org.onap.policy.controller;
 
 /*
- * 
+ *
  * */
 import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.JsonNode;
@@ -58,6 +58,14 @@ public class PolicyNotificationController extends RestrictedBaseController {
     @Autowired
     CommonClassDao commonClassDao;
 
+    /**
+     * watchPolicy.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @return ModelAndView
+     * @throws IOException IOException
+     */
     @RequestMapping(value = {"/watchPolicy"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
     public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
         StringBuilder path = new StringBuilder();
@@ -114,11 +122,8 @@ public class PolicyNotificationController extends RestrictedBaseController {
             response.setContentType("application / json");
             request.setCharacterEncoding("UTF-8");
 
-            PrintWriter out = response.getWriter();
-            String responseString = mapper.writeValueAsString(responseValue);
-            JSONObject j = new JSONObject("{watchData: " + responseString + "}");
-            out.write(j.toString());
-            return null;
+            response.getWriter().write(new JSONObject("{watchData: "
+                    + mapper.writeValueAsString(responseValue) + "}").toString());
         } catch (Exception e) {
             response.setCharacterEncoding("UTF-8");
             request.setCharacterEncoding("UTF-8");
index f416386..4fa848e 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -26,7 +26,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 
-import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -82,9 +81,7 @@ public class PolicyRolesController extends RestrictedBaseController {
             Map<String, Object> model = new HashMap<>();
             ObjectMapper mapper = new ObjectMapper();
             model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles()));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             LOGGER.error("Exception Occured" + e);
         }
@@ -116,11 +113,11 @@ public class PolicyRolesController extends RestrictedBaseController {
                 }
             }
             LOGGER.info(
-                    "****************************************Logging UserID for Roles Function********************************************************");
+                    "*************************Logging UserID for Roles Function***********************************");
             LOGGER.info("UserId:  " + userId + "Updating the Scope for following user" + adapter.getLoginId()
                     + "ScopeNames" + adapter.getScope());
             LOGGER.info(
-                    "*********************************************************************************************************************************");
+                    "*********************************************************************************************");
             UserInfo userInfo = new UserInfo();
             userInfo.setUserLoginId(adapter.getLoginId().getUserName());
             userInfo.setUserName(adapter.getLoginId().getUserName());
@@ -129,11 +126,11 @@ public class PolicyRolesController extends RestrictedBaseController {
             if (adapter.getId() == 0 && "mechid".equals(adapter.getRole())) {
                 // Save new mechid scopes entity data.
                 LOGGER.info(
-                        "****************************************Logging UserID for New Mechid Function***************************************************");
+                        "*********************Logging UserID for New Mechid Function********************************");
                 LOGGER.info("UserId:" + userId + "Adding new mechid-scopes for following user" + adapter.getLoginId()
                         + "ScopeNames " + adapter.getScope());
                 LOGGER.info(
-                        "*********************************************************************************************************************************");
+                        "*******************************************************************************************");
                 // First add the mechid to userinfo
                 commonClassDao.save(userInfo);
                 checkNew = true;
@@ -153,12 +150,8 @@ public class PolicyRolesController extends RestrictedBaseController {
             response.setCharacterEncoding("UTF-8");
             response.setContentType("application / json");
             request.setCharacterEncoding("UTF-8");
-
-            PrintWriter out = response.getWriter();
-            String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles());
-            JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}");
-
-            out.write(j.toString());
+            response.getWriter().write(new JSONObject("{rolesDatas: "
+                + mapper.writeValueAsString(commonClassDao.getUserRoles()) + "}").toString());
         } catch (Exception e) {
             LOGGER.error("Exception Occured" + e);
         }
@@ -183,9 +176,7 @@ public class PolicyRolesController extends RestrictedBaseController {
             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
             List<String> scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName");
             model.put("scopeDatas", mapper.writeValueAsString(scopesData));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
             LOGGER.error("Exception Occured" + e);
         }
index fc94087..0c29f8f 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -47,6 +47,14 @@ public class PolicyValidationController extends RestrictedBaseController {
 
     private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class);
 
+    /**
+     * validatePolicy.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @return ModelAndView
+     * @throws IOException IOException
+     */
     @RequestMapping(
             value = {"/policyController/validate_policy.htm"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -61,12 +69,8 @@ public class PolicyValidationController extends RestrictedBaseController {
             PolicyRestAdapter policyData = wrapper.populateRequestParameters(request);
             responseString = validation.validatePolicy(policyData);
 
-            PrintWriter out = response.getWriter();
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
-            JSONObject j = new JSONObject(msg);
-            out.write(j.toString());
-
-            return null;
+            response.getWriter().write(new JSONObject(
+                    new JsonMessage(mapper.writeValueAsString(responseString.toString()))).toString());
         } catch (Exception e) {
             LOGGER.error("Exception Occured During Policy Validation" + e);
             response.setCharacterEncoding("UTF-8");
index abd7f0e..a4b2c88 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -221,8 +221,8 @@ public class CommonClassDaoImpl implements CommonClassDao {
         Transaction tx = session.beginTransaction();
         List<PolicyRoles> rolesData = null;
         try {
-            Criteria cr = session.createCriteria(PolicyRoles.class);
-            Disjunction disjunction = Restrictions.disjunction();
+            final Criteria cr = session.createCriteria(PolicyRoles.class);
+            final Disjunction disjunction = Restrictions.disjunction();
             Conjunction conjunction1 = Restrictions.conjunction();
             conjunction1.add(Restrictions.eq("role", "admin"));
             Conjunction conjunction2 = Restrictions.conjunction();
@@ -318,10 +318,12 @@ public class CommonClassDaoImpl implements CommonClassDao {
 
     @Override
     public void updateClAlarms(String arg0, String arg1) {
+        // why is there no code here?
     }
 
     @Override
     public void updateClYaml(String arg0, String arg1) {
+        // why is there no code here?
     }
 
     @Override
index c02d3b1..6c4fd7e 100644 (file)
@@ -113,6 +113,9 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         return itemId instanceof OnapPDPGroup;
     }
 
+    /**
+     * refreshGroups.
+     */
     public synchronized void refreshGroups() {
         synchronized (this.groups) {
             this.groups.clear();
@@ -134,6 +137,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         return Collections.unmodifiableList(this.groups);
     }
 
+    /**
+     * makeDefault.
+     *
+     * @param group OnapPDPGroup
+     */
     public void makeDefault(OnapPDPGroup group) {
         try {
             this.papEngine.setDefaultGroup(group);
@@ -144,6 +152,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         return;
     }
 
+    /**
+     * removeGroup.
+     *
+     * @param group OnapPDPGroup
+     * @param newGroup OnapPDPGroup
+     * @throws PAPException PAPException
+     */
     public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
         if (LOGGER.isTraceEnabled()) {
             LOGGER.trace("removeGroup: " + group + " new group for PDPs: " + newGroup);
@@ -159,6 +174,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         }
     }
 
+    /**
+     * removePDP.
+     *
+     * @param pdp OnapPDP
+     * @param group OnapPDPGroup
+     * @throws PAPException PAPException
+     */
     public void removePDP(OnapPDP pdp, OnapPDPGroup group) throws PAPException {
         if (LOGGER.isTraceEnabled()) {
             LOGGER.trace("removePDP: " + pdp + " from group: " + group);
@@ -171,6 +193,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         }
     }
 
+    /**
+     * updatePDP.
+     *
+     * @param pdp OnapPDP
+     */
     public void updatePDP(OnapPDP pdp) {
         try {
             papEngine.updatePDP(pdp);
@@ -179,6 +206,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         }
     }
 
+    /**
+     * updateGroup.
+     *
+     * @param group OnapPDPGroup
+     */
     public void updateGroup(OnapPDPGroup group) {
         try {
             papEngine.updateGroup(group);
@@ -216,6 +248,17 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         return Collections.unmodifiableCollection(items);
     }
 
+    @Override
+    public List<?> getItemIds(int startIndex, int numberOfItems) {
+        synchronized (this.groups) {
+            int endIndex = startIndex + numberOfItems;
+            if (endIndex > this.groups.size()) {
+                endIndex = this.groups.size() - 1;
+            }
+            return this.groups.subList(startIndex, endIndex);
+        }
+    }
+
     @Override
     public Class<?> getType(Object propertyId) {
         if (propertyId.equals(PROPERTY_ID)) {
@@ -269,6 +312,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         throw new UnsupportedOperationException("PDP Container cannot add a given item.");
     }
 
+    /**
+     * addNewGroup.
+     *
+     * @param name String
+     * @param description String
+     * @throws PAPException PAPException
+     */
     public void addNewGroup(String name, String description) throws PAPException {
         if (LOGGER.isTraceEnabled()) {
             LOGGER.trace("addNewGroup " + name + " " + description);
@@ -276,6 +326,16 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         this.papEngine.newGroup(name, description);
     }
 
+    /**
+     * addNewPDP.
+     *
+     * @param id String
+     * @param group OnapPDPGroup
+     * @param name String
+     * @param description String
+     * @param jmxport int
+     * @throws PAPException PAPException
+     */
     public void addNewPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
             throws PAPException {
         if (LOGGER.isTraceEnabled()) {
@@ -284,6 +344,12 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         this.papEngine.newPDP(id, group, name, description, jmxport);
     }
 
+    /**
+     * movePDP.
+     *
+     * @param pdp OnapPDP
+     * @param group OnapPDPGroup
+     */
     public void movePDP(OnapPDP pdp, OnapPDPGroup group) {
         try {
             this.papEngine.movePDP(pdp, group);
@@ -427,17 +493,6 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
         return this.groups.get(index);
     }
 
-    @Override
-    public List<?> getItemIds(int startIndex, int numberOfItems) {
-        synchronized (this.groups) {
-            int endIndex = startIndex + numberOfItems;
-            if (endIndex > this.groups.size()) {
-                endIndex = this.groups.size() - 1;
-            }
-            return this.groups.subList(startIndex, endIndex);
-        }
-    }
-
     @Override
     public Object addItemAt(int index) {
         throw new UnsupportedOperationException("Cannot addItemAt");
index 22c4486..f9f93c0 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -36,18 +36,18 @@ public final class UserUtils {
     }
 
     public static class Pair<T, U> {
-        public final T t;
-        public final U u;
+        public final T first;
+        public final U second;
 
-        public Pair(T t, U u) {
-            this.t = t;
-            this.u = u;
+        public Pair(T first, U second) {
+            this.first = first;
+            this.second = second;
         }
     }
 
     /**
      * Check Role and its Scopes.
-     * 
+     *
      * @param userRoles list of UserRoles.
      * @return return role and scope from UserRole Object.
      */
@@ -76,7 +76,7 @@ public final class UserUtils {
 
     /**
      * Get Role by Scope based on UserRole Object.
-     * 
+     *
      * @param userRoles list of UserRoles.
      * @return return the map<scope, role>.
      */
@@ -95,7 +95,7 @@ public final class UserUtils {
 
     /**
      * Read non super role scopes and add to map.
-     * 
+     *
      * @param userRole Role Object.
      * @param rolesList roleList Object.
      * @return return the map<scope, role>.
@@ -116,7 +116,7 @@ public final class UserUtils {
 
     /**
      * Trim Scope Value.
-     * 
+     *
      * @param scope string scope name.
      * @return trim scope.
      */
index 3bd48d6..2f079f1 100644 (file)
@@ -31,6 +31,10 @@ import org.mockito.Mockito;
 import org.onap.policy.controller.PolicyController;
 
 public class HibernateSessionTest {
+
+    /**
+     * setup.
+     */
     @Before
     public void setup() {
         PolicyController.setLogdbUrl("testURL");
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ActionPolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ActionPolicyControllerTest.java
new file mode 100644 (file)
index 0000000..e34cab4
--- /dev/null
@@ -0,0 +1,205 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.controller;
+
+import static org.assertj.core.api.Assertions.assertThatCode;
+
+import com.att.research.xacml.api.XACML3;
+import java.io.IOException;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
+import org.junit.Test;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+
+public class ActionPolicyControllerTest {
+
+    @Test
+    public void testBasicConstructor() throws IOException {
+        ActionPolicyController controller = new ActionPolicyController();
+        final PolicyRestAdapter adapter = new PolicyRestAdapter();
+        //
+        // Cover the simple if instance branch
+        //
+        assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException();
+    }
+
+    @Test
+    public void testNoDescriptionNoTargetType() throws IOException {
+        //
+        // Do the test - with no description and
+        // no TargetType to cover those branches.
+        //
+        PolicyRestAdapter adapter = new PolicyRestAdapter();
+        adapter.setPolicyData(new PolicyType());
+        adapter.setPolicyName("name");
+        ActionPolicyController controller = new ActionPolicyController();
+        assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException();
+    }
+
+    @Test
+    public void testWithDescriptionEmptyTargetType() throws IOException {
+        //
+        // Create a simple PolicyType
+        //
+        PolicyType policy = new PolicyType();
+        policy.setTarget(new TargetType());
+        policy.setDescription("i am a description. @CreatedBy: policy designer");
+        //
+        // Now do the test - description and
+        // TargetType but its empty
+        //
+        PolicyRestAdapter adapter = new PolicyRestAdapter();
+        adapter.setPolicyData(policy);
+        adapter.setPolicyName("name");
+        ActionPolicyController controller = new ActionPolicyController();
+        assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException();
+    }
+
+
+    @Test
+    public void testWithTargetTypeWithAnyOf() throws IOException {
+        //
+        // Create TargetType with empty AnyOf
+        //
+        AttributeValueType value = new AttributeValueType();
+        value.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+        value.getContent().add(new String("value"));
+        AttributeDesignatorType designator = new AttributeDesignatorType();
+        designator.setAttributeId("foo:bar");
+        designator.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+        designator.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_ACTION.stringValue());
+
+        MatchType match = new MatchType();
+        match.setMatchId(XACML3.ID_FUNCTION_STRING_EQUAL.stringValue());
+        match.setAttributeValue(value);
+        match.setAttributeDesignator(designator);
+        AllOfType allOf = new AllOfType();
+        allOf.getMatch().add(match);
+        AnyOfType anyOf = new AnyOfType();
+        anyOf.getAllOf().add(allOf);
+        TargetType target = new TargetType();
+        target.getAnyOf().add(anyOf);
+        //
+        // Create a simple Rule with NO obligations but a Condition
+        //
+        RuleType rule = new RuleType();
+        rule.setRuleId("id:rule");
+        rule.setEffect(EffectType.PERMIT);
+
+        AttributeValueType expressionValue = new AttributeValueType();
+        expressionValue.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+        expressionValue.getContent().add(new String("a string value"));
+
+        designator = new AttributeDesignatorType();
+        designator.setAttributeId("foo:bar");
+        designator.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+        designator.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_ACTION.stringValue());
+
+        ApplyType applyOneAndOnly = new ApplyType();
+        applyOneAndOnly.setDescription("apply this");
+        applyOneAndOnly.setFunctionId(XACML3.ID_FUNCTION_STRING_ONE_AND_ONLY.stringValue());
+        applyOneAndOnly.getExpression().add(new ObjectFactory().createAttributeDesignator(designator));
+
+        ApplyType applyOneAndOnly2 = new ApplyType();
+        applyOneAndOnly2.setDescription("apply this");
+        applyOneAndOnly2.setFunctionId(XACML3.ID_FUNCTION_STRING_ONE_AND_ONLY.stringValue());
+        applyOneAndOnly2.getExpression().add(new ObjectFactory().createAttributeValue(expressionValue));
+
+        ApplyType apply = new ApplyType();
+        apply.setDescription("apply this");
+        apply.setFunctionId(XACML3.ID_FUNCTION_STRING_EQUAL.stringValue());
+        apply.getExpression().add(new ObjectFactory().createApply(applyOneAndOnly));
+        apply.getExpression().add(new ObjectFactory().createApply(applyOneAndOnly2));
+
+
+        ConditionType condition = new ConditionType();
+        condition.setExpression(new ObjectFactory().createApply(apply));
+        rule.setCondition(condition);
+        //
+        // Create a simple Rule WITH obligations
+        //
+        AttributeValueType val = new AttributeValueType();
+        val.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+        val.getContent().add(new String("obligation data"));
+
+        AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
+        assignment.setAttributeId("ob:id:1");
+        assignment.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue());
+        assignment.setExpression(new ObjectFactory().createAttributeValue(val));
+
+        AttributeValueType val2 = new AttributeValueType();
+        val2.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+        val2.getContent().add(new String("iamperformer"));
+
+        AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
+        assignment2.setAttributeId("performer");
+        assignment2.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue());
+        assignment2.setExpression(new ObjectFactory().createAttributeValue(val2));
+
+        ObligationExpressionType ob = new ObligationExpressionType();
+        ob.setFulfillOn(EffectType.PERMIT);
+        ob.setObligationId("id:obligation");
+        ob.getAttributeAssignmentExpression().add(assignment);
+        ob.getAttributeAssignmentExpression().add(assignment2);
+        ObligationExpressionsType obs = new ObligationExpressionsType();
+        obs.getObligationExpression().add(ob);
+        RuleType obligationRule = new RuleType();
+        obligationRule.setRuleId("id:rule:obligations");
+        obligationRule.setEffect(EffectType.DENY);
+        obligationRule.setObligationExpressions(obs);
+        //
+        // Create a PolicyType
+        //
+        PolicyType policy = new PolicyType();
+        policy.setDescription("i am a description. @CreatedBy: policy designer");
+        policy.setTarget(target);
+        policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
+        policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(obligationRule);
+        //
+        // Add something the ActionPolicyController will skip over
+        // to catch that branch
+        //
+        policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(new VariableDefinitionType());
+        //
+        // Now do the test - description and
+        // TargetType but its empty
+        //
+        PolicyRestAdapter adapter = new PolicyRestAdapter();
+        adapter.setPolicyData(policy);
+        adapter.setPolicyName("name");
+        ActionPolicyController controller = new ActionPolicyController();
+        assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException();
+    }
+}
index 68da8e7..85337f1 100644 (file)
@@ -22,6 +22,7 @@
 
 package org.onap.policy.controller;
 
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.mockito.Mockito.mock;
@@ -54,6 +55,11 @@ public class AdminTabControllerTest {
     private HttpServletRequest request;
     private MockHttpServletResponse response;
 
+    /**
+     * Before.
+     *
+     * @throws Exception Exception
+     */
     @Before
     public void setUp() throws Exception {
 
@@ -82,6 +88,7 @@ public class AdminTabControllerTest {
     @Test
     public void testGetAdminRole() {
         AdminTabController admin = new AdminTabController();
+        assertNotNull(AdminTabController.getCommonClassDao());
         try {
             admin.getAdminTabEntityData(request, response);
             assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("lockdowndata"));
index 7d2d5f8..64c3b04 100644 (file)
@@ -45,7 +45,7 @@ import org.powermock.modules.junit4.PowerMockRunner;
 
 @RunWith(PowerMockRunner.class)
 public class AutoPushControllerTest {
-    private PolicyController controller = new PolicyController();;
+    private PolicyController controller = new PolicyController();
     private AutoPushController apController = new AutoPushController();
 
     @Rule
@@ -93,22 +93,22 @@ public class AutoPushControllerTest {
         Mockito.when(UserUtils.getUserSession(Mockito.any())).thenReturn(user);
 
         // Mock policy controller
-        PolicyController pController = Mockito.mock(PolicyController.class);
-        PowerMockito.whenNew(PolicyController.class).withNoArguments().thenReturn(pController);
-        Mockito.when(pController.getRoles(Mockito.any())).thenReturn(null);
+        PolicyController policyController = Mockito.mock(PolicyController.class);
+        PowerMockito.whenNew(PolicyController.class).withNoArguments().thenReturn(policyController);
+        Mockito.when(policyController.getRoles(Mockito.any())).thenReturn(null);
 
         // Test group container
         MockHttpServletRequest request = new MockHttpServletRequest();
         MockHttpServletResponse response = new MockHttpServletResponse();
         apController.getPolicyGroupContainerData(request, response);
-        assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
+        assertEquals(HttpServletResponse.SC_OK, response.getStatusCode());
 
         // Test push
         apController.pushPolicyToPDPGroup(request, response);
-        assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
+        assertEquals(HttpServletResponse.SC_OK, response.getStatusCode());
 
         // Test remove
         apController.removePDPGroup(request, response);
-        assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
+        assertEquals(HttpServletResponse.SC_OK, response.getStatusCode());
     }
 }
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java
new file mode 100644 (file)
index 0000000..6a431a0
--- /dev/null
@@ -0,0 +1,139 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.controller;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import com.att.research.xacml.api.XACML3;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.jpa.ConfigurationDataEntity;
+import org.onap.policy.rest.jpa.PolicyEntity;
+
+public class CreatePolicyControllerTest {
+
+    private PolicyEntity entity;
+
+    /**
+     * before - sets up the mocked PolicyEntity.
+     */
+    @Before
+    public void before() {
+        //
+        // PolicyEntity
+        //
+        ConfigurationDataEntity dataEntity = mock(ConfigurationDataEntity.class);
+        when(dataEntity.getConfigType()).thenReturn("configtype");
+        entity = mock(PolicyEntity.class);
+        when(entity.getConfigurationData()).thenReturn(dataEntity);
+    }
+
+    @Test
+    public void testEasyStuff() {
+        CreatePolicyController controller = new CreatePolicyController();
+        PolicyRestAdapter adapter = new PolicyRestAdapter();
+        controller.prePopulateBaseConfigPolicyData(adapter, null);
+        //
+        // Create a simple PolicyType
+        //
+        VariableDefinitionType var = new VariableDefinitionType();
+        PolicyType policy = new PolicyType();
+        policy.setDescription("i am a description. @CreatedBy: policy designer");
+        policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(var);
+        adapter.setPolicyData(policy);
+        adapter.setPolicyName("name");
+        controller.prePopulateBaseConfigPolicyData(adapter, entity);
+    }
+
+    @Test
+    public void testBadDescription() {
+        PolicyRestAdapter adapter = new PolicyRestAdapter();
+        //
+        // Create a simple PolicyType
+        //
+        VariableDefinitionType var = new VariableDefinitionType();
+        PolicyType policy = new PolicyType();
+        policy.setDescription("i am a description");
+        policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(var);
+        adapter.setPolicyData(policy);
+        adapter.setPolicyName("name");
+        CreatePolicyController controller = new CreatePolicyController();
+        controller.prePopulateBaseConfigPolicyData(adapter, entity);
+    }
+
+    @Test
+    public void testExpectedPolicyContents() {
+        AllOfType allOf = new AllOfType();
+        allOf.getMatch().add(createMatchType("ONAPName", "ONAPName"));
+        allOf.getMatch().add(createMatchType("RiskType", "RiskType"));
+        allOf.getMatch().add(createMatchType("RiskLevel", "RiskLevel"));
+        allOf.getMatch().add(createMatchType("guard", "guard"));
+        allOf.getMatch().add(createMatchType("TTLDate", "TTLDate"));
+        allOf.getMatch().add(createMatchType("ConfigName", "ConfigName"));
+        allOf.getMatch().add(createMatchType("NA", "TTLDate"));
+        allOf.getMatch().add(createMatchType("custom", "custom"));
+        allOf.getMatch().add(createMatchType("custom", "custom"));
+        allOf.getMatch().add(createMatchType("custom", "custom"));
+
+        AnyOfType anyOf = new AnyOfType();
+        anyOf.getAllOf().add(allOf);
+
+        TargetType target = new TargetType();
+        target.getAnyOf().add(anyOf);
+
+        RuleType rule = new RuleType();
+        PolicyType policy = new PolicyType();
+        policy.setDescription("i am a description. @CreatedBy: policy designer");
+        policy.setTarget(target);
+        policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
+        PolicyRestAdapter adapter = new PolicyRestAdapter();
+        adapter.setPolicyData(policy);
+        adapter.setPolicyName("name");
+        CreatePolicyController controller = new CreatePolicyController();
+        controller.prePopulateBaseConfigPolicyData(adapter, entity);
+    }
+
+    private MatchType createMatchType(String strValue, String id) {
+        AttributeValueType value = new AttributeValueType();
+        value.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+        value.getContent().add(new String(strValue));
+        AttributeDesignatorType designator = new AttributeDesignatorType();
+        designator.setAttributeId(id);
+
+        MatchType match = new MatchType();
+        match.setAttributeValue(value);
+        match.setAttributeDesignator(designator);
+
+        return match;
+    }
+
+}
index 3bc89c9..16c5384 100644 (file)
@@ -64,6 +64,11 @@ public class CommonClassDaoImplTest {
     Server server;
     CommonClassDaoImpl commonClassDao;
 
+    /**
+     * setUp.
+     *
+     * @throws Exception Exception
+     */
     @Before
     public void setUp() throws Exception {
         try {
@@ -148,17 +153,17 @@ public class CommonClassDaoImplTest {
         try {
             // Add data
             UserInfo userinfo = new UserInfo();
-            String loginId_userName = "Test";
-            userinfo.setUserLoginId(loginId_userName);
-            userinfo.setUserName(loginId_userName);
+            String loginIdUserName = "Test";
+            userinfo.setUserLoginId(loginIdUserName);
+            userinfo.setUserName(loginIdUserName);
             commonClassDao.save(userinfo);
 
             List<Object> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
 
             assertEquals(1, dataCur.size());
             UserInfo cur = (UserInfo) dataCur.get(0);
-            assertEquals(loginId_userName, cur.getUserLoginId());
-            assertEquals(loginId_userName, cur.getUserName());
+            assertEquals(loginIdUserName, cur.getUserLoginId());
+            assertEquals(loginIdUserName, cur.getUserName());
 
             assertFalse(dataCur.isEmpty());
 
@@ -190,7 +195,7 @@ public class CommonClassDaoImplTest {
             assertTrue(1 == dataCur.size());
             assertTrue(dataCur.get(0) instanceof PolicyEntity);
             assertEquals(name, ((PolicyEntity) dataCur.get(0)).getPolicyName());
-            assertEquals(pe, ((PolicyEntity) dataCur.get(0)));
+            assertEquals(pe, (dataCur.get(0)));
 
         } catch (Exception e) {
             logger.debug("Exception Occured" + e);
@@ -229,7 +234,7 @@ public class CommonClassDaoImplTest {
             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
 
             assertTrue(1 == dataCur.size());
-            assertEquals(pv, (PolicyVersion) dataCur.get(0));
+            assertEquals(pv, dataCur.get(0));
 
         } catch (Exception e) {
             logger.debug("Exception Occured" + e);
@@ -244,11 +249,11 @@ public class CommonClassDaoImplTest {
         try {
             // Add data
             WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
-            String policyFileName = "banana";
             watch.setLoginIds("Test");
             watch.setPolicyName("bananaWatch");
             commonClassDao.save(watch);
 
+            String policyFileName = "banana";
             if (policyFileName.contains("/")) {
                 policyFileName = policyFileName.substring(0, policyFileName.indexOf("/"));
                 policyFileName = policyFileName.replace("/", File.separator);
@@ -268,7 +273,7 @@ public class CommonClassDaoImplTest {
             // Assertions
             assertTrue(dataCur.size() == 1);
             assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
-            assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0));
+            assertEquals(watch, dataCur.get(0));
 
         } catch (Exception e) {
             logger.debug("Exception Occured" + e);
@@ -294,19 +299,19 @@ public class CommonClassDaoImplTest {
             commonClassDao.save(pe);
 
             String dbCheckName = "dummyScope:action";
-            String[] splitDBCheckName = dbCheckName.split(":");
 
             // Current Implementation
             String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
             SimpleBindings params = new SimpleBindings();
-            params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
-            params.put("splitDBCheckName0", splitDBCheckName[0]);
+            String[] splitDbCheckName = dbCheckName.split(":");
+            params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
+            params.put("splitDBCheckName0", splitDbCheckName[0]);
             List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
 
             // Assertions
             assertTrue(dataCur.size() == 1);
             assertTrue(dataCur.get(0) instanceof PolicyEntity);
-            assertEquals(pe, (PolicyEntity) dataCur.get(0));
+            assertEquals(pe, dataCur.get(0));
 
         } catch (Exception e) {
             logger.debug("Exception Occured" + e);
@@ -337,7 +342,7 @@ public class CommonClassDaoImplTest {
             // Assertions
             assertTrue(dataCur.size() == 1);
             assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
-            assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0));
+            assertEquals(watch, dataCur.get(0));
 
         } catch (Exception e) {
             logger.debug("Exception Occured" + e);
@@ -381,8 +386,8 @@ public class CommonClassDaoImplTest {
 
             if (dataCur.size() >= 1) {
                 assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
-                assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0)));
-                assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0)));
+                assertFalse(watch.equals(dataCur.get(0)));
+                assertFalse(watch.equals(dataCur.get(0)));
             }
         } catch (Exception e) {
             logger.debug("Exception Occured" + e);