Resolved XACML Platform Sonar issues 79/65079/3
authorrb7147 <rb7147@att.com>
Thu, 6 Sep 2018 20:36:22 +0000 (16:36 -0400)
committerrb7147 <rb7147@att.com>
Mon, 10 Sep 2018 15:01:49 +0000 (11:01 -0400)
Issue-ID: POLICY-902
Change-Id: If22627dfe7df993b5c725ddf3a66c10ebbaa73ca
Signed-off-by: rb7147 <rb7147@att.com>
ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java
ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java
ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java
ONAP-REST/src/main/java/org/onap/policy/rest/util/MSModelUtils.java
ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java

index ff4525f..75d7645 100644 (file)
@@ -125,6 +125,8 @@ public class PolicyDBDao {
     private static final String policyDBDaoVar = "PolicyDBDao";
     private static final String duplicatePolicyId = "Somehow, more than one policy with the id ";
     private static final String foundInDB = " were found in the database";
+    private static final String TIMESTAMP = "\n   TimeStamp = ";
+    private static final String CAUGHTEXCEPTIONONNOTIFY = "Caught Exception on notifyOthers(";
 
     private static boolean isJunit = false;
 
@@ -788,7 +790,7 @@ public class PolicyDBDao {
                 }
             }
             boolean needToUpdate = false;
-            if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord, transaction)) {
+            if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord)) {
                 needToUpdate = true;
             }
             if (!stringEquals(localGroupClone.getId(), groupRecord.getGroupId())
@@ -818,7 +820,7 @@ public class PolicyDBDao {
     // this will also handle removes, since incoming pdpGroup has no policies internally, we are just going to add
     // them all in from the db
     private boolean updateGroupPoliciesInFileSystem(OnapPDPGroup pdpGroup, OnapPDPGroup oldPdpGroup,
-            GroupEntity groupRecord, PolicyDBDaoTransaction transaction) throws PAPException, PolicyDBException {
+            GroupEntity groupRecord) throws PAPException, PolicyDBException {
         if (!(pdpGroup instanceof StdPDPGroup)) {
             throw new PAPException("group is not a StdPDPGroup");
         }
@@ -1485,7 +1487,7 @@ public class PolicyDBDao {
                     if (logger.isDebugEnabled()) {
                         Date date = new java.util.Date();
                         logger.debug("\n\nTransactionTimer.run() - SLEEPING: " + "\n   sleepTime (ms) = " + sleepTime
-                                + "\n   TimeStamp = " + date.getTime() + "\n\n");
+                                + TIMESTAMP + date.getTime() + "\n\n");
                     }
                     try {
                         Thread.sleep(sleepTime);
@@ -1493,7 +1495,7 @@ public class PolicyDBDao {
                         // probably, the transaction was completed, the last thing we want to do is roll back
                         if (logger.isDebugEnabled()) {
                             Date date = new java.util.Date();
-                            logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " + "\n   TimeStamp = "
+                            logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " + TIMESTAMP
                                     + date.getTime() + "\n\n");
                         }
                         Thread.currentThread().interrupt();
@@ -1501,7 +1503,7 @@ public class PolicyDBDao {
                     }
                     if (logger.isDebugEnabled()) {
                         Date date = new java.util.Date();
-                        logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " + "\n   TimeStamp = "
+                        logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " + TIMESTAMP
                                 + date.getTime() + "\n\n");
                     }
                     rollbackTransaction();
@@ -1561,7 +1563,7 @@ public class PolicyDBDao {
                             notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId);
                         } catch (Exception e) {
                             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar,
-                                    "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ","
+                                    CAUGHTEXCEPTIONONNOTIFY + policyId + "," + POLICY_NOTIFICATION + ","
                                             + newGroupId + ")");
                         }
                     } else {
@@ -1569,7 +1571,7 @@ public class PolicyDBDao {
                             notifyOthers(policyId, POLICY_NOTIFICATION);
                         } catch (Exception e) {
                             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar,
-                                    "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ")");
+                                    CAUGHTEXCEPTIONONNOTIFY + policyId + "," + POLICY_NOTIFICATION + ")");
                         }
                     }
                 }
@@ -1580,7 +1582,7 @@ public class PolicyDBDao {
                             notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId);
                         } catch (Exception e) {
                             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar,
-                                    "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ","
+                                    CAUGHTEXCEPTIONONNOTIFY + groupId + "," + GROUP_NOTIFICATION + ","
                                             + newGroupId + ")");
                         }
                     } else {
@@ -1588,7 +1590,7 @@ public class PolicyDBDao {
                             notifyOthers(groupId, GROUP_NOTIFICATION);
                         } catch (Exception e) {
                             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar,
-                                    "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ")");
+                                    CAUGHTEXCEPTIONONNOTIFY + groupId + "," + GROUP_NOTIFICATION + ")");
                         }
                     }
                 }
@@ -1598,7 +1600,7 @@ public class PolicyDBDao {
                         notifyOthers(pdpId, PDP_NOTIFICATION);
                     } catch (Exception e) {
                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar,
-                                "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION + ")");
+                                CAUGHTEXCEPTIONONNOTIFY + pdpId + "," + PDP_NOTIFICATION + ")");
                     }
                 }
             }
@@ -1769,7 +1771,7 @@ public class PolicyDBDao {
                             newConfigurationDataEntity.setModifiedBy(username);
                         }
                         if (newConfigurationDataEntity.getDescription() == null
-                                || !newConfigurationDataEntity.getDescription().equals("")) {
+                                || !"".equals(newConfigurationDataEntity.getDescription())) {
                             newConfigurationDataEntity.setDescription("");
                         }
                         if (newConfigurationDataEntity.getConfigBody() == null
index 87cafc4..fcf319c 100644 (file)
@@ -497,7 +497,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
     }
 
     protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response,
-            ONAPLoggingContext loggingContext) throws ServletException, IOException {
+            ONAPLoggingContext loggingContext) throws IOException {
         try {
             // prevent multiple configuration changes from stacking up
             logger.info("XACMLPdpServlet: checking remainingCapacity of Queue.");
@@ -649,92 +649,63 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
         XACMLRest.dumpRequest(request);
 
         String pathInfo = request.getRequestURI();
-        if (pathInfo != null) {
+        if (pathInfo != null && "/pdp/test".equals(pathInfo)) {
             // health check from Global Site Selector (iDNS).
             // DO NOT do a im.startTransaction for the test request
-            if (pathInfo.equals("/pdp/test")) {
-                loggingContext.setServiceName("iDNS:PDP.test");
+            loggingContext.setServiceName("iDNS:PDP.test");
+            try {
+                im.evaluateSanity();
+                // If we make it this far, all is well
+                String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK";
+                PolicyLogger.debug(message);
+                PolicyLogger.audit("Success");
+                response.setStatus(HttpServletResponse.SC_OK);
+                return;
+            } catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException fpe) {
+                // No forward progress is being made
+                String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is not making forward progress."
+                        + " Exception Message: " + fpe.getMessage();
+                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + fpe);
+                PolicyLogger.audit("Transaction Failed - See Error.log");
                 try {
-                    im.evaluateSanity();
-                    // If we make it this far, all is well
-                    String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK";
-                    PolicyLogger.debug(message);
-                    loggingContext.transactionEnded();
-                    PolicyLogger.audit("Success");
-                    response.setStatus(HttpServletResponse.SC_OK);
-                    return;
-                } catch (ForwardProgressException fpe) {
-                    // No forward progress is being made
-                    String message = "GET:/pdp/test called and PDP " + pdpResourceName
-                            + " is not making forward progress." + " Exception Message: " + fpe.getMessage();
-                    PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + fpe);
-                    loggingContext.transactionEnded();
-                    PolicyLogger.audit("Transaction Failed - See Error.log");
-                    try {
-                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                    } catch (Exception e1) {
-                        logger.error("Exception occured while sending error in response" + e1);
-                    }
-                    return;
-                } catch (AdministrativeStateException ase) {
-                    // Administrative State is locked
-                    String message = "GET:/pdp/test called and PDP " + pdpResourceName
-                            + " Administrative State is LOCKED " + " Exception Message: " + ase.getMessage();
-                    PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + ase);
-                    loggingContext.transactionEnded();
-                    PolicyLogger.audit("Transaction Failed - See Error.log");
-                    try {
-                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                    } catch (Exception e1) {
-                        logger.error("Exception occured while sending error in response" + e1);
-                    }
-                    return;
-                } catch (StandbyStatusException sse) {
-                    // Administrative State is locked
-                    String message = "GET:/pdp/test called and PDP " + pdpResourceName
-                            + " Standby Status is NOT PROVIDING SERVICE " + " Exception Message: " + sse.getMessage();
-                    PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + sse);
-                    loggingContext.transactionEnded();
-                    PolicyLogger.audit("Transaction Failed - See Error.log");
-                    try {
-                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                    } catch (Exception e1) {
-                        logger.error("Exception occured while sending error in response" + e1);
-                    }
-                    return;
-                } catch (Exception e) {
-                    // A subsystem is not making progress or is not responding
-                    String eMsg = e.getMessage();
-                    if (eMsg == null) {
-                        eMsg = "No Exception Message";
-                    }
-                    String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure."
-                            + " Exception Message: " + eMsg;
-                    PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
-                    // Get the specific list of subsystems that failed
-                    String failedNodeList = null;
-                    for (String node : dependencyNodes) {
-                        if (eMsg.contains(node)) {
-                            if (failedNodeList == null) {
-                                failedNodeList = node;
-                            } else {
-                                failedNodeList = failedNodeList.concat("," + node);
-                            }
+                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                } catch (Exception e1) {
+                    logger.error("Exception occured while sending error in response" + e1);
+                }
+                return;
+            } catch (Exception e) {
+                // A subsystem is not making progress or is not responding
+                String eMsg = e.getMessage();
+                if (eMsg == null) {
+                    eMsg = "No Exception Message";
+                }
+                String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure."
+                        + " Exception Message: " + eMsg;
+                PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message);
+                // Get the specific list of subsystems that failed
+                String failedNodeList = null;
+                for (String node : dependencyNodes) {
+                    if (eMsg.contains(node)) {
+                        if (failedNodeList == null) {
+                            failedNodeList = node;
+                        } else {
+                            failedNodeList = failedNodeList.concat("," + node);
                         }
                     }
-                    if (failedNodeList == null) {
-                        failedNodeList = "UnknownSubSystem";
-                    }
-                    response.addHeader("X-ONAP-SubsystemFailure", failedNodeList);
-                    try {
-                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
-                    } catch (Exception e1) {
-                        logger.error("Exception occured while sending error in response" + e1);
-                    }
-                    loggingContext.transactionEnded();
-                    PolicyLogger.audit("Transaction Failed - See Error.log" + e);
-                    return;
                 }
+                if (failedNodeList == null) {
+                    failedNodeList = "UnknownSubSystem";
+                }
+                response.addHeader("X-ONAP-SubsystemFailure", failedNodeList);
+                try {
+                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
+                } catch (Exception e1) {
+                    logger.error("Exception occured while sending error in response" + e1);
+                }
+                PolicyLogger.audit("Transaction Failed - See Error.log" + e);
+                return;
+            } finally {
+                loggingContext.transactionEnded();
             }
         }
 
@@ -1001,7 +972,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
                 if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
                     pdpRequest = JSONRequest.load(incomingRequestString);
                 } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
-                        || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
+                        || "application/xacml+xml".equalsIgnoreCase(contentType.getMimeType())) {
                     pdpRequest = DOMRequest.load(incomingRequestString);
                 }
             } catch (Exception e) {
@@ -1035,7 +1006,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
         // Did we successfully get and parse a request?
         //
         if (pdpRequest == null || pdpRequest.getRequestAttributes() == null
-                || pdpRequest.getRequestAttributes().size() <= 0) {
+                || pdpRequest.getRequestAttributes().isEmpty()) {
             String message = "Zero Attributes found in the request";
             logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message);
index edadf53..e3faaff 100644 (file)
@@ -129,14 +129,6 @@ public class PolicyRestAdapter {
     private String blackListEntryType;
     private String rawXacmlPolicy;
 
-    public String getRawXacmlPolicy() {
-        return rawXacmlPolicy;
-    }
-
-    public void setRawXacmlPolicy(String rawXacmlPolicy) {
-        this.rawXacmlPolicy = rawXacmlPolicy;
-    }
-
     // Rainy Day Decision
     private RainyDayParams rainyday;
     private Map<String, String> rainydayMap;
@@ -1145,4 +1137,12 @@ public class PolicyRestAdapter {
     public void setBlackListEntryType(String blackListEntryType) {
         this.blackListEntryType = blackListEntryType;
     }
+    
+    public String getRawXacmlPolicy() {
+        return rawXacmlPolicy;
+    }
+
+    public void setRawXacmlPolicy(String rawXacmlPolicy) {
+        this.rawXacmlPolicy = rawXacmlPolicy;
+    }
 }
index 411ecaa..0384d0b 100644 (file)
@@ -172,11 +172,11 @@ public class MSModelUtils {
             addEnumClassMap();
         }
         if (!matchingClass.isEmpty()){
-            CheckForMatchingClass();
+            checkForMatchingClass();
         }
     }
 
-    private void CheckForMatchingClass() {
+    private void checkForMatchingClass() {
         HashMap<String, String> tempAttribute = new HashMap<>();
 
         for (Entry<String, String> set : matchingClass.entrySet()){
@@ -194,14 +194,14 @@ public class MSModelUtils {
                 }
 
             }
-            UpdateMatching(tempAttribute, key);
+            updateMatching(tempAttribute, key);
         }
 
     }
 
 
 
-    private void UpdateMatching(HashMap<String, String> tempAttribute, String key) {
+    private void updateMatching(HashMap<String, String> tempAttribute, String key) {
         Map<String, MSAttributeObject> newClass = classMap;
 
         for (Entry<String, MSAttributeObject> updateClass :  newClass.entrySet()){
@@ -392,20 +392,14 @@ public class MSModelUtils {
     }
 
     public String checkRequiredPattern(int upper, int lower) {
-
         String pattern = XACMLProperties.getProperty(XACMLRestProperties.PROP_XCORE_REQUIRED_PATTERN);
-
-        if (pattern!=null){
-            if (upper == Integer.parseInt(pattern.split(",")[1]) && lower==Integer.parseInt(pattern.split(",")[0])){
-                return REQUIREDTRUE;
-            }
+        if (pattern!=null && upper == Integer.parseInt(pattern.split(",")[1]) && lower==Integer.parseInt(pattern.split(",")[0])){
+            return REQUIREDTRUE;
         }
-
         return REQUIREDFALSE;
     }
 
     public JSONObject buildJavaObject(Map<String, String> map){
-
         return  new JSONObject(map);
     }
 
@@ -777,7 +771,7 @@ public class MSModelUtils {
      * For TOSCA Model
      */
     public String parseTosca(String fileName) {
-        LinkedHashMap<String, String> map = new LinkedHashMap<>();
+        Map<String, String> map = new LinkedHashMap<>();
         try {
             map = load(fileName);
             if (map != null && map.get(ERROR) != null) {
@@ -800,9 +794,9 @@ public class MSModelUtils {
     }
 
     @SuppressWarnings("unchecked")
-    public LinkedHashMap<String, String> load(String fileName) throws IOException, ParserException {
+    public Map<String, String> load(String fileName) throws IOException, ParserException {
         File newConfiguration = new File(fileName);
-        StringBuffer orderInfo = new StringBuffer("[");
+        StringBuilder orderInfo = new StringBuilder("[");
         Yaml yaml = new Yaml();
         LinkedHashMap<Object, Object> yamlMap = null;
         try (InputStream is = new FileInputStream(newConfiguration)) {
@@ -810,6 +804,7 @@ public class MSModelUtils {
         } catch (FileNotFoundException e) {
             logger.error(e);
         } catch (Exception e) {
+            logger.error(e);
             throw new ParserException("Invalid TOSCA Model format. Please make sure it is a valid YAML file");
         }
 
@@ -828,8 +823,8 @@ public class MSModelUtils {
 
         findNode(yamlMap);
 
-        if (!isDuplicatedAttributes && orderedElements != null && orderedElements.size() > 0) {
-            orderedElements.stream().forEach((string) -> {
+        if (!isDuplicatedAttributes && orderedElements != null && !orderedElements.isEmpty()) {
+            orderedElements.stream().forEach(string -> {
                 orderInfo.append(string);
                 orderInfo.append(",");
                 logger.info("Content: " + string);
@@ -972,7 +967,7 @@ public class MSModelUtils {
     }
 
 
-    void parseDataAndPolicyNodes(LinkedHashMap<String, String> map) {
+    void parseDataAndPolicyNodes(Map<String, String> map) {
         for (String key : map.keySet()) {
             if (key.contains("policy.nodes.Root")) {
                 continue;
@@ -1061,7 +1056,7 @@ public class MSModelUtils {
         logger.info("###############################################################################");
     }
 
-    LinkedHashMap<String, String> parseDataNodes(LinkedHashMap<String, String> map) {
+    LinkedHashMap<String, String> parseDataNodes(Map<String, String> map) {
         LinkedHashMap<String, String> dataMapForJson = new LinkedHashMap<>();
         matchableValues = new HashMap<>();
         for (String uniqueDataKey : uniqueDataKeys) {
@@ -1149,7 +1144,7 @@ public class MSModelUtils {
                                 if (constraintsValue == null) {
                                     break;
                                 } else {
-                                    System.out.println("constraintsValue => " + constraintsValue);
+                                    logger.info("constraintsValue => " + constraintsValue);
                                     if (constraintsValue.contains("=")) {
                                         constraintsValue = constraintsValue.replace("=", "equal-sign");
                                     }
@@ -1170,7 +1165,6 @@ public class MSModelUtils {
                                     + ".description";
                     String userDefinedValue = map.get(findUserDefined);
                     String description = map.get(findDescription);
-                    // String requiredValue = map.get(required);
                     String trimValue = userDefinedValue.substring(userDefinedValue.lastIndexOf('.') + 1);
                     StringBuilder referenceIndividualStringBuilder = new StringBuilder();
                     referenceIndividualStringBuilder.append(trimValue + REQUIREDVALUE);
@@ -1246,9 +1240,9 @@ public class MSModelUtils {
         for (Map.Entry<String, LinkedHashMap<String, String>> entry : mapKey.entrySet()) {
             String keySetString = entry.getKey();
             LinkedHashMap<String, String> keyValues = mapKey.get(keySetString);
-            if (keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(STRING)
-                    || keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(INTEGER)
-                    || keyValues.get("type") != null && keyValues.get("type").equalsIgnoreCase(BOOLEAN)) {
+            if (keyValues.get("type") != null && (STRING.equalsIgnoreCase(keyValues.get("type"))
+                    || INTEGER.equalsIgnoreCase(keyValues.get("type"))
+                    || BOOLEAN.equalsIgnoreCase(keyValues.get("type")))) {
                 StringBuilder attributeIndividualStringBuilder = new StringBuilder();
                 attributeIndividualStringBuilder.append(keySetString + "=");
                 attributeIndividualStringBuilder.append(keyValues.get("type") + DEFAULTVALUE);
@@ -1256,15 +1250,14 @@ public class MSModelUtils {
                 attributeIndividualStringBuilder.append(keyValues.get("required") + MANYFALSE);
                 attributeIndividualStringBuilder.append(DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY));
                 attributeStringBuilder.append(attributeIndividualStringBuilder + ",");
-                if (keyValues.get(MATCHABLEKEY) != null && keyValues.get(MATCHABLEKEY).equalsIgnoreCase("true")) {
+                if (keyValues.get(MATCHABLEKEY) != null && "true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) {
                     matchableValues.put(keySetString, MATCHINGTRUE);
                 }
             } else if (LIST.equalsIgnoreCase(keyValues.get("type"))) {
-
                 if ("true".equalsIgnoreCase(keyValues.get(MATCHABLEKEY))) {
                     matchableValues.put(keySetString, MATCHINGTRUE);
                 }
-                // List Datatype
+                // List Data type
                 Set<String> keys = keyValues.keySet();
                 Iterator<String> itr = keys.iterator();
                 boolean isDefinedType = false;
@@ -1291,7 +1284,7 @@ public class MSModelUtils {
 
                 }
 
-                if (!isDefinedType && LIST.equalsIgnoreCase(keyValues.get("type"))) { 
+                if (!isDefinedType && LIST.equalsIgnoreCase(keyValues.get("type"))) {
                     if (constraints == null || constraints.isEmpty()) {
                         referenceStringBuilder.append(keySetString + "=MANY-true" + ",");
                     }
@@ -1313,7 +1306,7 @@ public class MSModelUtils {
                 }
 
             }
-            if (constraints != null && constraints.isEmpty() == false) {
+            if (constraints != null && !constraints.isEmpty()) {
                 // List handling.
                 listBuffer.append(keySetString.toUpperCase() + "=[");
                 for (String str : constraints) {
@@ -1353,16 +1346,14 @@ public class MSModelUtils {
             if (key.equals(PROPERTIES_KEY) && value instanceof Map) {
                 saveNodes((LinkedHashMap<?, ?>) value);
                 if (isDuplicatedAttributes) {
-                    orderedElements = new ArrayList<String>();
+                    orderedElements = new ArrayList<>();
                     return;
                 }
             }
 
-            if (!key.equals("policy.nodes.Root")) {
+            if (!"policy.nodes.Root".equals(key) && value instanceof Map) {
                 // value is a Map object, then make a recursive call
-                if (value instanceof Map) {
-                    findNode((LinkedHashMap<Object, Object>) value);
-                }
+                findNode((LinkedHashMap<Object, Object>) value);
             }
         });
 
index e1d0223..2aaa4e1 100644 (file)
@@ -142,7 +142,7 @@ public class XACMLPolicyWriter {
         if (policy instanceof PolicyType) {
             policyElement = new ObjectFactory().createPolicy((PolicyType) policy); 
             return getByteArrayInputStream(policyElement, PolicyType.class);
-        } else if (policy instanceof PolicyType) {
+        } else if (policy instanceof PolicySetType) {
             policyElement = new ObjectFactory().createPolicySet((PolicySetType) policy); 
             return getByteArrayInputStream(policyElement, PolicySetType.class);
         } 
index fdbee2a..69c3d2f 100644 (file)
@@ -63,27 +63,28 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
 @RequestMapping("/")
 public class DecisionPolicyController extends RestrictedBaseController {
     private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class);
-
-    public DecisionPolicyController() {
-        // This constructor is empty
-    }
-
+    
+    public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
+    private static final String BLENTRY = "@blEntry@";
+    private static final String DECISIONRAWTYPE = "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
+    private static final String GUARD_YAML= "GUARD_YAML";
+    private static final String GUARD_BL_YAML= "GUARD_BL_YAML";
+   
     protected PolicyRestAdapter policyAdapter = null;
-    private ArrayList<Object> attributeList;
-    private ArrayList<Object> decisionList;
     private ArrayList<Object> ruleAlgorithmList;
     private ArrayList<Object> treatmentList = null;
     protected LinkedList<Integer> ruleAlgoirthmTracker;
-    public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
-    private static final String blEntry = "@blEntry@";
-    private static final String decisionRawType = "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
-
+    
+    public DecisionPolicyController() {
+        // This constructor is empty
+    }
+    
     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('.')));
             policyAdapter.setRuleProvider("Raw");
-            policyAdapter.setRawXacmlPolicy(IOUtils.toString(policyXmlStream).replaceAll(decisionRawType, ""));
+            policyAdapter.setRawXacmlPolicy(IOUtils.toString(policyXmlStream).replaceAll(DECISIONRAWTYPE, ""));
         } catch (IOException e) {
             policyLogger.error("Exception Occured while setting XACML Raw Object" + e);
         }
@@ -91,16 +92,16 @@ public class DecisionPolicyController extends RestrictedBaseController {
 
     @SuppressWarnings("unchecked")
     public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
-        attributeList = new ArrayList<>();
-        decisionList = new ArrayList<>();
+        List<Object> attributeList = new ArrayList<>();
+        List<Object> decisionList = new ArrayList<>();
         ruleAlgorithmList = new ArrayList<>();
         treatmentList = new ArrayList<>();
 
         boolean rawPolicyCheck = false;
         if (policyAdapter.getPolicyData() instanceof PolicySetType) {
-            rawPolicyCheck = ((PolicySetType) policyAdapter.getPolicyData()).getDescription().contains(decisionRawType);
+            rawPolicyCheck = ((PolicySetType) policyAdapter.getPolicyData()).getDescription().contains(DECISIONRAWTYPE);
         } else {
-            rawPolicyCheck = ((PolicyType) policyAdapter.getPolicyData()).getDescription().contains(decisionRawType);
+            rawPolicyCheck = ((PolicyType) policyAdapter.getPolicyData()).getDescription().contains(DECISIONRAWTYPE);
         }
 
         if (rawPolicyCheck) {
@@ -115,9 +116,9 @@ public class DecisionPolicyController extends RestrictedBaseController {
             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));
+                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:"));
@@ -226,12 +227,12 @@ public class DecisionPolicyController extends RestrictedBaseController {
                                         .getAdviceExpression().get(0).getAdviceId())) {
                                     policyAdapter.setRuleProvider("AAF");
                                     break;
-                                } else if ("GUARD_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+                                } 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()
+                                    policyAdapter.setRuleProvider(GUARD_YAML);
+                                } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
                                         .getAdviceExpression().get(0).getAdviceId())) {
-                                    policyAdapter.setRuleProvider("GUARD_BL_YAML");
+                                    policyAdapter.setRuleProvider(GUARD_BL_YAML);
                                 }
                             } else {
                                 policyAdapter.setRuleProvider("Custom");
@@ -242,8 +243,8 @@ public class DecisionPolicyController extends RestrictedBaseController {
                                 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_YAML.equals(policyAdapter.getRuleProvider())
+                                                || (GUARD_BL_YAML.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);
@@ -266,7 +267,7 @@ public class DecisionPolicyController extends RestrictedBaseController {
                                     yamlParams.setGuardActiveEnd(
                                             ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent()
                                                     .get(0).toString());
-                                    if ("GUARD_BL_YAML".equals(policyAdapter.getRuleProvider())) {
+                                    if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
                                         apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
                                                 .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
                                                         .get(2).getValue();