aboutsummaryrefslogtreecommitdiffstats
path: root/POLICY-SDK-APP/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'POLICY-SDK-APP/src/main')
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java39
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java42
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java66
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java10
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java9
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java17
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java13
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java10
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java8
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java42
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java163
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java116
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java12
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java30
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java34
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java88
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java6
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java48
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java3
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java2
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java4
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java7
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java70
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java6
24 files changed, 411 insertions, 434 deletions
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java
index 49eb80802..643320496 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java
@@ -44,6 +44,18 @@ import org.onap.policy.xacml.api.XACMLErrorConstants;
import com.att.research.xacml.util.XACMLProperties;
+/**
+ * What is not good about this class is that once a value has been set for pdpProperties path
+ * you cannot change it. That may be ok for a highly controlled production environment in which
+ * nothing changes, but not a very good implementation.
+ *
+ * The reset() method has been added to assist with the above problem in order to
+ * acquire >80% JUnit code coverage.
+ *
+ * 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 CheckPDP {
private static Path pdpPath = null;
private static Long oldModified = null;
@@ -57,6 +69,12 @@ public class CheckPDP {
public static Map<String, String> getPdpMap() {
return pdpMap;
}
+
+ private static void reset() {
+ pdpPath = null;
+ oldModified = null;
+ pdpMap = null;
+ }
public static boolean validateID(String id) {
// ReadFile
@@ -66,6 +84,9 @@ public class CheckPDP {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
return false;
}
+ if (pdpMap == null) {
+ return false;
+ }
// Check ID
return pdpMap.containsKey(id);
}
@@ -83,15 +104,12 @@ public class CheckPDP {
}
if (pdpPath == null) {
pdpPath = Paths.get(pdpFile);
- if (!pdpPath.toFile().exists()) {
+ if (!pdpPath.toString().endsWith(".properties") || !pdpPath.toFile().exists()) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath.toString());
-
- }
- if (pdpPath.toString().endsWith(".properties")) {
- readProps();
- } else {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + pdpFile);
+ CheckPDP.reset();
+ return;
}
+ readProps();
}
// Check if File is updated recently
else {
@@ -120,13 +138,14 @@ public class CheckPDP {
for (String propKey : sorted) {
loadPDPProperties(propKey, pdpProp);
}
- if (pdpMap == null || pdpMap.isEmpty()) {
- LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
- }
in.close();
} catch (IOException e) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
}
+ if (pdpMap == null || pdpMap.isEmpty()) {
+ LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
+ CheckPDP.reset();
+ }
}
private static void loadPDPProperties(String propKey, Properties pdpProp){
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
index 545143a22..42010f147 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
@@ -41,33 +41,26 @@ public class PolicyAdapter {
private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class);
public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- String policyNameValue;
- String configPolicyName = null ;
if(extendedOptions(policyAdapter, entity)){
return;
}
+ String policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
+ String configPolicyName = null ;
if(policyAdapter.getPolicyName().startsWith("Config_PM")){
- policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
configPolicyName = "ClosedLoop_PM";
}else if(policyAdapter.getPolicyName().startsWith("Config_Fault")){
- policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
configPolicyName = "ClosedLoop_Fault";
}else if(policyAdapter.getPolicyName().startsWith("Config_FW")){
- policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
configPolicyName = "Firewall Config";
}else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")){
- policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
configPolicyName = "BRMS_Raw";
}else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")){
- policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
configPolicyName = "BRMS_Param";
}else if(policyAdapter.getPolicyName().startsWith("Config_MS")){
- policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
configPolicyName = "Micro Service";
}else if(policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName().startsWith("Decision") ){
- policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
+ // No configPolicyName is applicable
}else{
- policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
configPolicyName = "Base";
}
if (policyNameValue != null) {
@@ -78,41 +71,32 @@ public class PolicyAdapter {
}
if("Action".equalsIgnoreCase(policyAdapter.getPolicyType())){
- ActionPolicyController actionController = new ActionPolicyController();
- actionController.prePopulateActionPolicyData(policyAdapter, entity);
+ new ActionPolicyController().prePopulateActionPolicyData(policyAdapter, entity);
}
if("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())){
- DecisionPolicyController decisionController = new DecisionPolicyController();
- decisionController.prePopulateDecisionPolicyData(policyAdapter, entity);
+ new DecisionPolicyController().prePopulateDecisionPolicyData(policyAdapter, entity);
}
if("Config".equalsIgnoreCase(policyAdapter.getPolicyType())){
if("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
- CreatePolicyController baseController = new CreatePolicyController();
- baseController.prePopulateBaseConfigPolicyData(policyAdapter, entity);
+ new CreatePolicyController().prePopulateBaseConfigPolicyData(policyAdapter, entity);
}
else if("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
- CreateBRMSRawController brmsController = new CreateBRMSRawController();
- brmsController.prePopulateBRMSRawPolicyData(policyAdapter, entity);
+ new CreateBRMSRawController().prePopulateBRMSRawPolicyData(policyAdapter, entity);
}
else if("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
- CreateBRMSParamController paramController = new CreateBRMSParamController();
- paramController.prePopulateBRMSParamPolicyData(policyAdapter, entity);
+ new CreateBRMSParamController().prePopulateBRMSParamPolicyData(policyAdapter, entity);
}
else if("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
- CreateClosedLoopFaultController newFaultTemplate = new CreateClosedLoopFaultController();
- newFaultTemplate.prePopulateClosedLoopFaultPolicyData(policyAdapter, entity);
+ new CreateClosedLoopFaultController().prePopulateClosedLoopFaultPolicyData(policyAdapter, entity);
}
else if("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
- CreateClosedLoopPMController pmController = new CreateClosedLoopPMController();
- pmController.prePopulateClosedLoopPMPolicyData(policyAdapter, entity);
+ new CreateClosedLoopPMController().prePopulateClosedLoopPMPolicyData(policyAdapter, entity);
}
else if("Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
- CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
- msController.prePopulateDCAEMSPolicyData(policyAdapter, entity);
+ new CreateDcaeMicroServiceController().prePopulateDCAEMSPolicyData(policyAdapter, entity);
}
else if("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
- CreateFirewallController firewallController = new CreateFirewallController();
- firewallController.prePopulateFWPolicyData(policyAdapter, entity);
+ new CreateFirewallController().prePopulateFWPolicyData(policyAdapter, entity);
}
}
}
@@ -130,7 +114,5 @@ public class PolicyAdapter {
}
return null;
}
-
-
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
index e62c87839..54a14cb8d 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
@@ -68,7 +68,6 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.components.HumanPolicyComponent;
import org.onap.policy.controller.PolicyController;
import org.onap.policy.controller.PolicyExportAndImportController;
-import org.onap.policy.model.Roles;
import org.onap.policy.rest.XACMLRest;
import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
@@ -79,6 +78,7 @@ import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.onap.policy.rest.jpa.UserInfo;
import org.onap.policy.utils.PolicyUtils;
+import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.util.XACMLPolicyScanner;
import org.onap.portalsdk.core.web.support.UserUtils;
@@ -314,8 +314,8 @@ public class PolicyManagerServlet extends HttpServlet {
}
private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
- Set<String> scopes = null;
- List<String> roles = null;
+ Set<String> scopes;
+ List<String> roles;
List<Object> policyData = new ArrayList<>();
JSONArray policyList = null;
if(params.has("policyList")){
@@ -326,24 +326,10 @@ public class PolicyManagerServlet extends HttpServlet {
try {
//Get the Login Id of the User from Request
String userId = UserUtils.getUserSession(request).getOrgUserId();
- //Check if the Role and Scope Size are Null get the values from db.
List<Object> userRoles = controller.getRoles(userId);
- roles = new ArrayList<>();
- scopes = new HashSet<>();
- for(Object role: userRoles){
- Roles userRole = (Roles) role;
- roles.add(userRole.getRole());
- if(userRole.getScope() != null){
- if(userRole.getScope().contains(",")){
- String[] multipleScopes = userRole.getScope().split(",");
- for(int i =0; i < multipleScopes.length; i++){
- scopes.add(multipleScopes[i]);
- }
- }else{
- scopes.add(userRole.getScope());
- }
- }
- }
+ Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+ roles = pair.u;
+ scopes = pair.t;
if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
if(scopes.isEmpty()){
return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
@@ -442,7 +428,7 @@ public class PolicyManagerServlet extends HttpServlet {
policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
}
- String activePolicy = null;
+ String activePolicy;
PolicyController controller = getPolicyControllerInstance();
if(params.toString().contains("activeVersion")){
String activeVersion = params.getString("activeVersion");
@@ -572,24 +558,10 @@ public class PolicyManagerServlet extends HttpServlet {
//Get the Login Id of the User from Request
String testUserID = getTestUserId();
String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
- //Check if the Role and Scope Size are Null get the values from db.
List<Object> userRoles = controller.getRoles(userId);
- roles = new ArrayList<>();
- scopes = new HashSet<>();
- for(Object role: userRoles){
- Roles userRole = (Roles) role;
- roles.add(userRole.getRole());
- if(userRole.getScope() != null){
- if(userRole.getScope().contains(",")){
- String[] multipleScopes = userRole.getScope().split(",");
- for(int i =0; i < multipleScopes.length; i++){
- scopes.add(multipleScopes[i]);
- }
- }else{
- scopes.add(userRole.getScope());
- }
- }
- }
+ Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+ roles = pair.u;
+ scopes = pair.t;
List<JSONObject> resultList = new ArrayList<>();
boolean onlyFolders = params.getBoolean("onlyFolders");
@@ -659,7 +631,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
private List<Object> queryPolicyEditorScopes(String scopeName){
- String scopeNamequery = "";
+ String scopeNamequery;
SimpleBindings params = new SimpleBindings();
if(scopeName == null){
scopeNamequery = "from PolicyEditorScopes";
@@ -668,7 +640,7 @@ public class PolicyManagerServlet extends HttpServlet {
params.put("scopeName", scopeName + "%");
}
PolicyController controller = getPolicyControllerInstance();
- List<Object> scopesList = null;
+ List<Object> scopesList;
if(PolicyController.isjUnit()){
scopesList = controller.getDataByQuery(scopeNamequery, null);
}else{
@@ -692,8 +664,8 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings params = new SimpleBindings();
params.put("scopeName", scopeName + "%");
- List<Object> activePolicies = null;
- List<Object> scopesList = null;
+ List<Object> activePolicies;
+ List<Object> scopesList;
if(PolicyController.isjUnit()){
activePolicies = controller.getDataByQuery(query, null);
scopesList = controller.getDataByQuery(scopeNamequery, null);
@@ -727,7 +699,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
}
- String scopeNameCheck = null;
+ String scopeNameCheck;
for (Object list : activePolicies) {
PolicyVersion policy = (PolicyVersion) list;
String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
@@ -862,7 +834,7 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
try {
- PolicyEntity entity = null;
+ PolicyEntity entity;
PolicyController controller = getPolicyControllerInstance();
String policyVersionName = newPath.replace(".xml", "");
@@ -1004,7 +976,7 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
FileWriter fw = null;
- String queryEntityName = null;
+ String queryEntityName;
PolicyController controller = getPolicyControllerInstance();
PolicyEntity cloneEntity = new PolicyEntity();
cloneEntity.setPolicyName(newpolicyName);
@@ -1174,7 +1146,7 @@ public class PolicyManagerServlet extends HttpServlet {
path = path.substring(path.indexOf('/')+1);
String policyNamewithExtension = path.replace("/", File.separator);
String policyVersionName = policyNamewithExtension.replace(".xml", "");
- String query = "";
+ String query;
SimpleBindings policyParams = new SimpleBindings();
if(path.endsWith(".xml")){
policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
@@ -1413,7 +1385,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 = null;
+ List<Object> queryData;
if(PolicyController.isjUnit()){
queryData = controller.getDataByQuery(query, null);
}else{
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java
index 36e94c2ca..895adbe41 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java
@@ -143,11 +143,9 @@ public class PolicyNotificationMail{
}
}
if(sendFlag){
- AnnotationConfigApplicationContext ctx = null;
- try {
+ try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
to = list.getLoginIds()+"@"+PolicyController.getSmtpEmailExtension();
to = to.trim();
- ctx = new AnnotationConfigApplicationContext();
ctx.register(PolicyNotificationMail.class);
ctx.refresh();
JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class);
@@ -158,15 +156,11 @@ public class PolicyNotificationMail{
mailMsg.setSubject(subject);
mailMsg.setText(message);
mailSender.send(mimeMessage);
- if(mode.equalsIgnoreCase("Rename") || mode.contains("Delete") || mode.contains("Move")){
+ if("Rename".equalsIgnoreCase(mode) || mode.contains("Delete") || mode.contains("Move")){
policyNotificationDao.delete(watch);
}
} catch (Exception e) {
policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e);
- }finally{
- if(ctx != null){
- ctx.close();
- }
}
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
index d930a6d7a..63d0cb298 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
@@ -141,14 +141,11 @@ public class PolicyRestController extends RestrictedBaseController{
if(policyData.getConfigPolicyType() != null){
if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){
- CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController();
- policyData = faultController.setDataToPolicyRestAdapter(policyData, root);
+ policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root);
}else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
- CreateFirewallController fwController = new CreateFirewallController();
- policyData = fwController.setDataToPolicyRestAdapter(policyData);
+ policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData);
}else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){
- CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
- policyData = msController.setDataToPolicyRestAdapter(policyData, root);
+ policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root);
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java
index 512901d4f..de1c551fc 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java
@@ -24,7 +24,6 @@ package org.onap.policy.components;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
-import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Path;
@@ -132,12 +131,10 @@ public class HumanPolicyComponent{
}
private static String processPolicy() {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("ENTER");
-
- FileInputStream pIS = null;
- try {
- pIS = new FileInputStream(policyFile);
+ }
+ try (FileInputStream pIS = new FileInputStream(policyFile)){
Object policy = XACMLPolicyScanner.readPolicy(pIS);
if (policy == null)
throw new IllegalArgumentException("Policy File " + policyFile.getName() +
@@ -160,14 +157,6 @@ public class HumanPolicyComponent{
": " + e.getMessage();
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + msg, e);
throw new IllegalArgumentException(msg);
- } finally {
- if (pIS != null) {
- try {
- pIS.close();
- } catch (IOException e) {
- LOGGER.warn(e.getMessage(), e);
- }
- }
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
index 88cb2e265..a556beeaa 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
@@ -26,6 +26,7 @@ import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import javax.xml.bind.JAXBElement;
@@ -166,8 +167,9 @@ public class ActionPolicyController extends RestrictedBaseController {
AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression
.getExpression().getValue();
if (attributeID.equals(PERFORMER_ATTRIBUTEID)) {
- for (String key : performer.keySet()) {
- String keyValue = performer.get(key);
+ for ( Entry<String, String> entry: performer.entrySet()) {
+ String key = entry.getKey();
+ String keyValue = entry.getValue();
if (keyValue.equals(attributeValue.getContent().get(0))) {
policyAdapter.setActionPerformer(key);
}
@@ -235,10 +237,9 @@ public class ActionPolicyController extends RestrictedBaseController {
ruleMap.put("id", "A" + (index + 1));
// Populate combo box
Map<String, String> dropDownMap = PolicyController.getDropDownMap();
- for (String key : dropDownMap.keySet()) {
- String keyValue = dropDownMap.get(key);
- if (keyValue.equals(actionApply.getFunctionId())) {
- ruleMap.put("dynamicRuleAlgorithmCombo", key);
+ for ( Entry<String, String> entry : dropDownMap.entrySet()) {
+ if (entry.getValue().equals(actionApply.getFunctionId())) {
+ ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey());
}
}
// Populate the key and value fields
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
index e578d9108..df1ca6a9f 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
@@ -85,7 +85,9 @@ public class CreateBRMSParamController extends RestrictedBaseController {
CreateBRMSParamController.commonClassDao = commonClassDao;
}
- public CreateBRMSParamController(){}
+ public CreateBRMSParamController(){
+ // Empty constructor
+ }
protected PolicyRestAdapter policyAdapter = null;
private HashMap<String, String> dynamicLayoutMap;
@@ -185,7 +187,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
String[] components = params.toString().split(":");
String caption = "";
for (int i = 0; i < components.length; i++) {
- String type = "";
+ String type;
if (i == 0) {
caption = components[i];
}
@@ -415,7 +417,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
String[] components = params.toString().split("\\);");
if(components!= null && components.length > 0){
for (int i = 0; i < components.length; i++) {
- String value = null;
+ String value;
components[i] = components[i]+")";
String caption = components[i].substring(0,
components[i].indexOf('('));
@@ -456,7 +458,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
policyData.setEditPolicy(true);
}
- String body = "";
+ String body;
body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
index e93fbf4e5..3ab4f4f16 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
@@ -131,16 +131,16 @@ public class CreateBRMSRawController{
AttributeDesignatorType designator = match.getAttributeDesignator();
String attributeId = designator.getAttributeId();
- if (attributeId.equals("RiskType")){
+ if ("RiskType".equals(attributeId)){
policyAdapter.setRiskType(value);
}
- if (attributeId.equals("RiskLevel")){
+ if ("RiskLevel".equals(attributeId)){
policyAdapter.setRiskLevel(value);
}
- if (attributeId.equals("guard")){
+ if ("guard".equals(attributeId)){
policyAdapter.setGuard(value);
}
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
PolicyController controller = new PolicyController();
String newDate = controller.convertDate(value);
policyAdapter.setTtlDate(newDate);
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
index 8ce32670f..158ea6248 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
@@ -73,7 +73,9 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{
CreateClosedLoopFaultController.commonclassdao = commonclassdao;
}
- public CreateClosedLoopFaultController(){}
+ public CreateClosedLoopFaultController(){
+ // Empty constructor
+ }
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root){
try{
@@ -245,35 +247,35 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{
TrapDatas trapDatas = (TrapDatas) object;
ArrayList<Object> attributeList = new ArrayList<>();
// Read the Trap
- if(!trap.equals("nill")){
+ if(! "nill".equals(trap)){
try{
if(trap.startsWith("Trap")){
- if(trap.equals("Trap1")){
+ if("Trap1".equals(trap)){
attributeList = trapDatas.getTrap1();
- }else if(trap.equals("Trap2")){
+ }else if("Trap2".equals(trap)){
attributeList = trapDatas.getTrap2();
- }else if(trap.equals("Trap3")){
+ }else if("Trap3".equals(trap)){
attributeList = trapDatas.getTrap3();
- }else if(trap.equals("Trap4")){
+ }else if("Trap4".equals(trap)){
attributeList = trapDatas.getTrap4();
- }else if(trap.equals("Trap5")){
+ }else if("Trap5".equals(trap)){
attributeList = trapDatas.getTrap5();
- }else if(trap.equals("Trap6")){
+ }else if("Trap6".equals(trap)){
attributeList = trapDatas.getTrap6();
}
}else{
if(trap.startsWith("Fault")){
- if(trap.equals("Fault1")){
+ if("Fault1".equals(trap)){
attributeList = trapDatas.getTrap1();
- }else if(trap.equals("Fault2")){
+ }else if("Fault2".equals(trap)){
attributeList = trapDatas.getTrap2();
- }else if(trap.equals("Fault3")){
+ }else if("Fault3".equals(trap)){
attributeList = trapDatas.getTrap3();
- }else if(trap.equals("Fault4")){
+ }else if("Fault4".equals(trap)){
attributeList = trapDatas.getTrap4();
- }else if(trap.equals("Fault5")){
+ }else if("Fault5".equals(trap)){
attributeList = trapDatas.getTrap5();
- }else if(trap.equals("Fault6")){
+ }else if("Fault6".equals(trap)){
attributeList = trapDatas.getTrap6();
}
}
@@ -548,22 +550,22 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{
String attributeId = designator.getAttributeId();
// First match in the target is OnapName, so set that value.
- if (attributeId.equals("ONAPName")) {
+ if ("ONAPName".equals(attributeId)) {
policyAdapter.setOnapName(value);
OnapName onapName = new OnapName();
onapName.setOnapName(value);
policyAdapter.setOnapNameField(onapName);
}
- if (attributeId.equals("RiskType")){
+ if ("RiskType".equals(attributeId)){
policyAdapter.setRiskType(value);
}
- if (attributeId.equals("RiskLevel")){
+ if ("RiskLevel".equals(attributeId)){
policyAdapter.setRiskLevel(value);
}
- if (attributeId.equals("guard")){
+ if ("guard".equals(attributeId)){
policyAdapter.setGuard(value);
}
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
PolicyController controller = new PolicyController();
String newDate = controller.convertDate(value);
policyAdapter.setTtlDate(newDate);
@@ -584,7 +586,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{
ObjectMapper mapper = new ObjectMapper();
try {
ClosedLoopFaultBody closedLoopBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class);
- if(closedLoopBody.getClosedLoopPolicyStatus().equalsIgnoreCase("ACTIVE")){
+ if("ACTIVE".equalsIgnoreCase(closedLoopBody.getClosedLoopPolicyStatus())){
closedLoopBody.setClosedLoopPolicyStatus("Active");
}else{
closedLoopBody.setClosedLoopPolicyStatus("InActive");
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
index d8ccd9a02..431482d40 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
@@ -158,7 +158,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
}
- public CreateDcaeMicroServiceController(){}
+ public CreateDcaeMicroServiceController(){
+ // Empty Constructor
+ }
protected PolicyRestAdapter policyAdapter = null;
private int priorityCount;
@@ -431,7 +433,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return settings;
}
- public Map<String, String> load(byte[] source) throws IOException {
+ public Map<String, String> load(byte[] source) {
Yaml yaml = new Yaml();
@SuppressWarnings("unchecked")
Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(Arrays.toString(source));
@@ -701,7 +703,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
Iterator<String> itr=keys.iterator();
while(itr.hasNext()){
String key= itr.next();
- if((!("type").equals(key) ||("required").equals(key)))
+ if(!("type").equals(key) ||("required").equals(key))
{
String value= keyValues.get(key);
//The "." in the value determines if its a string or a user defined type.
@@ -721,10 +723,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
- if(keyValues.get("type").equalsIgnoreCase(LIST)){
- if(constraints == null || constraints.isEmpty()){
+ if(keyValues.get("type").equalsIgnoreCase(LIST) &&
+ (constraints == null || constraints.isEmpty()) ) {
referenceStringBuilder.append(keySetString+"=MANY-true"+",");
- }
}
}else{
//User defined Datatype.
@@ -829,8 +830,10 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
ObjectNode node = nodeFactory.objectNode();
String prevKey = null;
- String presKey = null;
- for(String key: element.keySet()){
+ String presKey;
+ for(Entry<String, String> entry: element.entrySet()){
+ String key = entry.getKey();
+ String value = entry.getValue();
if(key.contains(".")){
presKey = key.substring(0,key.indexOf('.'));
}else if(key.contains("@")){
@@ -858,7 +861,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
nodeKey = key.substring(0,key.indexOf('.'));
}
if(nodeKey.equals(key.substring(0,key.indexOf('.')))){
- node.put(key.substring(key.indexOf('.')+1), element.get(key));
+ node.put(key.substring(key.indexOf('.')+1), value);
}else{
if(node.size()!=0){
if(nodeKey.contains("@")){
@@ -887,54 +890,30 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if(nodeKey.contains("@")){
arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
}
- node.put(key.substring(key.indexOf('.')+1), element.get(key));
+ node.put(key.substring(key.indexOf('.')+1), value);
}
- }else if(node.size()!=0){
- if(nodeKey.contains("@")){
- if(arryKey==null){
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }
- if(nodeKey.endsWith("@0")){
- isArray = true;
- jsonArray = new JSONArray();
- }
- if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
- jsonArray.put(decodeContent(node));
- }
- jsonResult.put(arryKey, jsonArray);
- jsonArray = new JSONArray();
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }else{
- isArray = false;
- jsonResult.put(nodeKey, decodeContent(node));
- }
- node = nodeFactory.objectNode();
- if(key.contains("@")){
- isArray = true;
- if(key.endsWith("@0")|| jsonArray==null){
+ }else {
+ if(node.size()!=0){
+ if(nodeKey.contains("@")){
+ if(arryKey==null){
+ arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
+ }
+ if(nodeKey.endsWith("@0")){
+ isArray = true;
+ jsonArray = new JSONArray();
+ }
+ if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
+ jsonArray.put(decodeContent(node));
+ }
+ jsonResult.put(arryKey, jsonArray);
jsonArray = new JSONArray();
- }
- }else if(!key.contains("@")){
- isArray = false;
- }
- if(isArray){
- if(oldValue==null){
- oldValue = key.substring(0,key.indexOf('@'));
- }
- if(oldValue!=prevKey){
- oldValue = key.substring(0,key.indexOf('@'));
- }
- if(oldValue.equals(key.substring(0,key.indexOf('@')))){
- jsonArray.put(element.get(key));
+ arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
}else{
- jsonResult.put(oldValue, jsonArray);
- jsonArray = new JSONArray();
+ isArray = false;
+ jsonResult.put(nodeKey, decodeContent(node));
}
- oldValue = key.substring(0,key.indexOf('@'));
- }else{
- jsonResult.put(key, element.get(key));
+ node = nodeFactory.objectNode();
}
- }else{
if(key.contains("@")){
isArray = true;
if(key.endsWith("@0")|| jsonArray==null){
@@ -951,14 +930,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
oldValue = key.substring(0,key.indexOf('@'));
}
if(oldValue.equals(key.substring(0,key.indexOf('@')))){
- jsonArray.put(element.get(key));
+ jsonArray.put(value);
}else{
jsonResult.put(oldValue, jsonArray);
jsonArray = new JSONArray();
}
oldValue = key.substring(0,key.indexOf('@'));
}else{
- jsonResult.put(key, element.get(key));
+ jsonResult.put(key, value);
}
}
}
@@ -1053,7 +1032,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
List<Object> list = new ArrayList<>();
PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(returnModel);
- JSONObject j = null;
+ JSONObject j;
if("".equals(allManyTrueKeys)){
j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}");
}else{
@@ -1103,7 +1082,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
for (Entry<String, String> keySet : attributeMap.entrySet()){
array = new JSONArray();
String value = keySet.getValue();
- if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
array.put(value);
object.put(keySet.getKey().trim(), array);
}else {
@@ -1115,14 +1094,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
array = new JSONArray();
String value = keySet.getValue().split(":")[0];
if (gsonObject.containsKey(value)){
- if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
array.put(recursiveReference(value, gsonObject, enumAttribute));
object.put(keySet.getKey().trim(), array);
}else {
object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
}
}else {
- if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
array.put(value.trim());
object.put(keySet.getKey().trim(), array);
}else {
@@ -1148,14 +1127,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
String[] splitValue = m.getValue().split(":");
array = new JSONArray();
if (subAttributeMap.containsKey(splitValue[0])){
- if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
object.put(m.getKey().trim(), array);
}else {
object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
}
} else{
- if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
array.put(splitValue[0].trim());
object.put(m.getKey().trim(), array);
}else {
@@ -1203,7 +1182,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if(referAttributes != null){
String[] referAarray = referAttributes.split(",");
- String []element= null;
+ String []element;
for(int i=0; i<referAarray.length; i++){
element = referAarray[i].split("=");
if(element.length > 1 && element[1].contains("MANY-true")){
@@ -1373,28 +1352,28 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
AttributeDesignatorType designator = match.getAttributeDesignator();
String attributeId = designator.getAttributeId();
// First match in the target is OnapName, so set that value.
- if (attributeId.equals("ONAPName")) {
+ if ("ONAPName".equals(attributeId)) {
policyAdapter.setOnapName(value);
}
- if (attributeId.equals("ConfigName")){
+ if ("ConfigName".equals(attributeId)){
policyAdapter.setConfigName(value);
}
- if (attributeId.equals("uuid")){
+ if ("uuid".equals(attributeId)){
policyAdapter.setUuid(value);
}
- if (attributeId.equals("location")){
+ if ("location".equals(attributeId)){
policyAdapter.setLocation(value);
}
- if (attributeId.equals("RiskType")){
+ if ("RiskType".equals(attributeId)){
policyAdapter.setRiskType(value);
}
- if (attributeId.equals("RiskLevel")){
+ if ("RiskLevel".equals(attributeId)){
policyAdapter.setRiskLevel(value);
}
- if (attributeId.equals("guard")){
+ if ("guard".equals(attributeId)){
policyAdapter.setGuard(value);
}
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
PolicyController controller = new PolicyController();
String newDate = controller.convertDate(value);
policyAdapter.setTtlDate(newDate);
@@ -1458,8 +1437,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if(value instanceof LinkedHashMap<?, ?>){
LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
- for(String objKey: secondObjec.keySet()){
- data.put(key+"." +objKey, secondObjec.get(objKey));
+ for( Entry<String, Object> entry : secondObjec.entrySet()){
+ data.put(key+"." + entry.getKey(), entry.getValue());
}
}else if(value instanceof ArrayList){
ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
@@ -1468,8 +1447,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if(arrayvalue instanceof LinkedHashMap<?, ?>){
LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
- for(String objKey: newData.keySet()){
- data.put(key+"@"+i+"." +objKey, newData.get(objKey));
+ for(Entry<String, Object> entry: newData.entrySet()){
+ data.put(key+"@"+i+"." +entry.getKey(), entry.getValue());
}
}else if(arrayvalue instanceof ArrayList){
ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
@@ -1499,7 +1478,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
//Convert the map values and set into JSON body
public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
Map<String, String> attribute = new HashMap<>();
- StringBuilder temp = null;
+ StringBuilder temp;
String key;
String value;
for (Entry<String, String> entry : attributesMap.entrySet()) {
@@ -1604,7 +1583,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
File file = new File(this.newFile);
fileList.add(file);
}
- String modelType= "";
+ String modelType;
if(! yml){
modelType="xmi";
//Process Main Model file first
@@ -1675,9 +1654,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
int BUFFER = 2048;
File file = new File(zipFile);
- ZipFile zip = null;
- try {
- zip = new ZipFile(file);
+ try (ZipFile zip = new ZipFile(file)) {
String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
checkZipDirectory(this.directory);
@@ -1697,15 +1674,20 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if (!entry.isDirectory()){
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
- byte data[] = new byte[BUFFER];
- FileOutputStream fos = new FileOutputStream(destFile);
- BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
- while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
- dest.write(data, 0, currentByte);
+ 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) {
+ dest.write(data, 0, currentByte);
+ }
+ dest.flush();
+ } catch (IOException e) {
+ LOGGER.error("Failed to write zip contents to {}" + destFile + e);
+ //
+ // PLD should I throw e?
+ //
+ throw e;
}
- dest.flush();
- dest.close();
- is.close();
}
if (currentEntry.endsWith(".zip")){
@@ -1714,20 +1696,13 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
} catch (IOException e) {
LOGGER.error("Failed to unzip model file " + zipFile, e);
- }finally{
- try {
- if(zip != null)
- zip.close();
- } catch (IOException e) {
- LOGGER.error("Exception Occured While closing zipfile " + e);
- }
}
}
private void retreiveDependency(String workingFile, Boolean modelClass) {
MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
- HashMap<String, MSAttributeObject> tempMap;
+ Map<String, MSAttributeObject> tempMap;
tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java
index f0681a388..2750ff505 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java
@@ -119,7 +119,7 @@ public class CreateFirewallController extends RestrictedBaseController {
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData){
- String jsonBody="";
+ String jsonBody;
termCollectorList = new ArrayList <>();
tagCollectorList = new ArrayList <>();
if(! policyData.getAttributes().isEmpty()){
@@ -134,7 +134,7 @@ public class CreateFirewallController extends RestrictedBaseController {
}
}
jsonBody = constructJson(policyData);
- if (jsonBody != null && !jsonBody.equalsIgnoreCase("")) {
+ if (jsonBody != null && ! "".equalsIgnoreCase(jsonBody)) {
policyData.setJsonBody(jsonBody);
} else {
policyData.setJsonBody("{}");
@@ -145,8 +145,8 @@ public class CreateFirewallController extends RestrictedBaseController {
}
private List<String> mapping(String expandableList) {
- String value = null;
- String desc = null;
+ String value;
+ String desc;
List <String> valueDesc= new ArrayList<>();
List<Object> prefixListData = commonClassDao.getData(PrefixList.class);
for (int i = 0; i< prefixListData.size(); i++) {
@@ -227,7 +227,7 @@ public class CreateFirewallController extends RestrictedBaseController {
TermCollector tc1=null;
try {
//Json conversion.
- String data=null;
+ String data;
SecurityZone jpaSecurityZone;
data = entity.getConfigurationData().getConfigBody();
tc1 = mapper.readValue(data, TermCollector.class);
@@ -244,7 +244,7 @@ public class CreateFirewallController extends RestrictedBaseController {
policyLogger.error("Exception Caused while Retriving the JSON body data" +e);
}
- Map<String, String> termTagMap=null;
+ Map<String, String> termTagMap;
if(tc1 != null){
for(int i=0;i<tc1.getFirewallRuleList().size();i++){
termTagMap = new HashMap <>();
@@ -298,7 +298,7 @@ public class CreateFirewallController extends RestrictedBaseController {
if (("guard").equals(attributeId)){
policyAdapter.setGuard(value);
}
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
PolicyController controller = new PolicyController();
String newDate = controller.convertDate(value);
policyAdapter.setTtlDate(newDate);
@@ -330,13 +330,13 @@ public class CreateFirewallController extends RestrictedBaseController {
}
}
TermList jpaTermList;
- String ruleSrcList=null;
- String ruleDestList=null;
- String ruleSrcPort=null;
- String ruleDestPort=null;
- String ruleAction=null;
- List <String> valueDesc= new ArrayList<>();
- StringBuffer displayString = new StringBuffer();
+ String ruleSrcList;
+ String ruleDestList;
+ String ruleSrcPort;
+ String ruleDestPort;
+ String ruleAction;
+ List <String> valueDesc;
+ StringBuilder displayString = new StringBuilder();
for (String id : termCollectorList) {
List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id);
jpaTermList = (TermList) tmList.get(0);
@@ -349,15 +349,17 @@ public class CreateFirewallController extends RestrictedBaseController {
if(srcList.startsWith(GROUP)){
AddressGroup ag;
ag= mappingAddressGroup(srcList);
- displayString.append("\n\t"+"Group has :"+ag.getPrefixList()+"\n");
- for(String groupItems:ag.getPrefixList().split(",")){
- valueDesc=mapping(groupItems);
- displayString.append("\n\t"+"Name: "+groupItems);
- if(!valueDesc.isEmpty()){
- displayString.append("\n\t"+"Description: "+valueDesc.get(1));
- displayString.append("\n\t"+"Value: "+valueDesc.get(0));
+ displayString.append("\n\t"+"Group has :"+(ag != null ? ag.getPrefixList() : "") +"\n");
+ if (ag != null) {
+ for(String groupItems:ag.getPrefixList().split(",")){
+ valueDesc=mapping(groupItems);
+ displayString.append("\n\t"+"Name: "+groupItems);
+ if(!valueDesc.isEmpty()){
+ displayString.append("\n\t"+"Description: "+valueDesc.get(1));
+ displayString.append("\n\t"+"Value: "+valueDesc.get(0));
+ }
+ displayString.append("\n");
}
- displayString.append("\n");
}
}else{
if(!srcList.equals(ANY)){
@@ -372,20 +374,22 @@ public class CreateFirewallController extends RestrictedBaseController {
displayString.append("\n");
}
ruleDestList= jpaTermList.getDestIPList();
- if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& !ruleDestList.equals("null")){
+ if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& ! "null".equals(ruleDestList)){
displayString.append("Destination IP List: " + jpaTermList.getDestIPList());
displayString.append(" ; \t\n");
for(String destList:ruleDestList.split(",")){
if(destList.startsWith(GROUP)){
AddressGroup ag;
ag= mappingAddressGroup(destList);
- displayString.append("\n\t"+"Group has :"+ag.getPrefixList()+"\n");
- for(String groupItems:ag.getPrefixList().split(",")){
- valueDesc=mapping(groupItems);
- displayString.append("\n\t"+"Name: "+groupItems);
- displayString.append("\n\t"+"Description: "+valueDesc.get(1));
- displayString.append("\n\t"+"Value: "+valueDesc.get(0));
- displayString.append("\n\t");
+ displayString.append("\n\t"+"Group has :"+ (ag != null ? ag.getPrefixList() : "") +"\n");
+ if (ag != null) {
+ for(String groupItems:ag.getPrefixList().split(",")){
+ valueDesc=mapping(groupItems);
+ displayString.append("\n\t"+"Name: "+groupItems);
+ displayString.append("\n\t"+"Description: "+valueDesc.get(1));
+ displayString.append("\n\t"+"Value: "+valueDesc.get(0));
+ displayString.append("\n\t");
+ }
}
}else{
if(!destList.equals(ANY)){
@@ -401,14 +405,14 @@ public class CreateFirewallController extends RestrictedBaseController {
}
ruleSrcPort=jpaTermList.getSrcPortList();
- if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !ruleSrcPort.equals("null")) {
+ if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !"null".equals(ruleSrcPort)) {
displayString.append("\n"+"Source Port List:"
+ ruleSrcPort);
displayString.append(" ; \t\n");
}
ruleDestPort= jpaTermList.getDestPortList();
- if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !ruleDestPort.equals("null")) {
+ if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !"null".equals(ruleDestPort)) {
displayString.append("\n"+"Destination Port List:"
+ ruleDestPort);
displayString.append(" ; \t\n");
@@ -416,19 +420,21 @@ public class CreateFirewallController extends RestrictedBaseController {
if(destServices.startsWith(GROUP)){
GroupServiceList sg;
sg= mappingServiceGroup(destServices);
- displayString.append("\n\t"+"Service Group has :"+sg.getServiceList()+"\n");
- for(String groupItems:sg.getServiceList().split(",")){
- ServiceList sl;
- sl= mappingServiceList(groupItems);
- displayString.append("\n\t"+"Name: "+
- sl.getServiceName());
- displayString.append("\n\t"+"Description: "+
- sl.getServiceDescription());
- displayString.append("\n\t"+"Transport-Protocol: "+
- sl.getServiceTransProtocol());
- displayString.append("\n\t"+"Ports: "+
- sl.getServicePorts());
- displayString.append("\n");
+ displayString.append("\n\t"+"Service Group has :"+ (sg != null ? sg.getServiceList() : "") +"\n");
+ if (sg != null) {
+ for(String groupItems:sg.getServiceList().split(",")){
+ ServiceList sl;
+ sl= mappingServiceList(groupItems);
+ displayString.append("\n\t"+"Name: "+
+ sl.getServiceName());
+ displayString.append("\n\t"+"Description: "+
+ sl.getServiceDescription());
+ displayString.append("\n\t"+"Transport-Protocol: "+
+ sl.getServiceTransProtocol());
+ displayString.append("\n\t"+"Ports: "+
+ sl.getServicePorts());
+ displayString.append("\n");
+ }
}
}
else{
@@ -654,7 +660,7 @@ public class CreateFirewallController extends RestrictedBaseController {
}
//ExpandableServicesList
if((srcPort_map!=null) && (destPort_map!=null)){
- String servicesCollateString = (srcPort_map.get(tl) + "," + destPort_map.get(tl));
+ String servicesCollateString = srcPort_map.get(tl) + "," + destPort_map.get(tl);
expandableServicesList.add(servicesCollateString);
}else if (srcPort_map!=null){
expandableServicesList.add(srcPort_map.get(tl));
@@ -707,8 +713,8 @@ public class CreateFirewallController extends RestrictedBaseController {
//ExpandablePrefixIPList
if ((srcIP_map!=null) && (destIP_map!=null))
{
- String collateString = (srcIP_map.get(tl) + "," + destIP_map
- .get(tl));
+ String collateString = srcIP_map.get(tl) + "," + destIP_map
+ .get(tl);
expandablePrefixIPList.add(collateString);
}
else if(srcIP_map!=null){
@@ -754,15 +760,15 @@ public class CreateFirewallController extends RestrictedBaseController {
Set<AddressGroupJson> addrGroupArray= new HashSet<>();
Set<AddressMembers> addrArray= new HashSet<> ();
- ServiceGroupJson targetSg= null;
- AddressGroupJson addressSg=null;
- ServiceListJson targetAny= null;
- ServiceListJson targetAnyTcp=null;
- ServiceListJson targetAnyUdp=null;
+ ServiceGroupJson targetSg;
+ AddressGroupJson addressSg;
+ ServiceListJson targetAny;
+ ServiceListJson targetAnyTcp;
+ ServiceListJson targetAnyUdp;
for(String serviceList:expandableServicesList){
for(String t: serviceList.split(",")){
- if((!t.startsWith(GROUP))){
+ if(!t.startsWith(GROUP)){
if(!t.equals(ANY)){
ServiceList sl;
targetSl= new ServiceListJson();
@@ -838,7 +844,7 @@ public class CreateFirewallController extends RestrictedBaseController {
Set<PrefixIPList> prefixIPList = new HashSet<>();
for(String prefixList:expandablePrefixIPList){
for(String prefixIP: prefixList.split(",")){
- if((!prefixIP.startsWith(GROUP))){
+ if(!prefixIP.startsWith(GROUP)){
if(!prefixIP.equals(ANY)){
List<AddressMembers> addMembersList= new ArrayList<>();
List<String> valueDesc;
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
index af4f9ffaf..6cd121ee6 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
@@ -101,24 +101,24 @@ public class CreatePolicyController extends RestrictedBaseController{
AttributeDesignatorType designator = match.getAttributeDesignator();
String attributeId = designator.getAttributeId();
// First match in the target is OnapName, so set that value.
- if (attributeId.equals("ONAPName")) {
+ if ("ONAPName".equals(attributeId)) {
policyAdapter.setOnapName(value);
}
- if (attributeId.equals("RiskType")){
+ if ("RiskType".equals(attributeId)){
policyAdapter.setRiskType(value);
}
- if (attributeId.equals("RiskLevel")){
+ if ("RiskLevel".equals(attributeId)){
policyAdapter.setRiskLevel(value);
}
- if (attributeId.equals("guard")){
+ if ("guard".equals(attributeId)){
policyAdapter.setGuard(value);
}
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
PolicyController controller = new PolicyController();
String newDate = controller.convertDate(value);
policyAdapter.setTtlDate(newDate);
}
- if (attributeId.equals("ConfigName")){
+ if ("ConfigName".equals(attributeId)){
policyAdapter.setConfigName(value);
}
// After Onap and Config it is optional to have attributes, so
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
index 6679b8954..adb91ec27 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
@@ -281,12 +281,9 @@ public class DashboardController extends RestrictedBaseController{
policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server");
HashMap map = null;
- JMXConnector jmxConnection;
- try {
- jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
+ try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)){
jmxConnection.connect();
Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
- jmxConnection.close();
policyLogger.debug("pdpEvaluationNA value retreived: " + o);
return (long) o;
} catch (MalformedURLException e) {
@@ -319,10 +316,10 @@ public class DashboardController extends RestrictedBaseController{
*/
private void addPolicyToTable() {
policyActivityData = new ArrayList<>();
- String policyID = null;
- int policyFireCount = 0;
+ String policyID;
+ int policyFireCount;
Map<String, String> policyMap = new HashMap<>();
- Object policyList = null;
+ Object policyList;
//get list of policy
for (PDPGroup group : this.pdpConatiner.getGroups()){
@@ -346,14 +343,12 @@ public class DashboardController extends RestrictedBaseController{
for (String policyKeyValue : splitPolicy){
policyID = urnPolicyID(policyKeyValue);
policyFireCount = countPolicyID(policyKeyValue);
- if (policyID != null ){
- if (policyMap.containsKey(policyID)){
- JSONObject object = new JSONObject();
- object.put("policyId", policyMap.get(policyID));
- object.put("fireCount", policyFireCount);
- object.put("system", pdp.getId());
- policyActivityData.add(object);
- }
+ if (policyID != null && policyMap.containsKey(policyID)){
+ JSONObject object = new JSONObject();
+ object.put("policyId", policyMap.get(policyID));
+ object.put("fireCount", policyFireCount);
+ object.put("system", pdp.getId());
+ policyActivityData.add(object);
}
}
}else {
@@ -382,12 +377,9 @@ public class DashboardController extends RestrictedBaseController{
private Object getPolicy(String host, int port, String jmxAttribute){
policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
HashMap map = null;
- JMXConnector jmxConnection;
- try {
- jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
+ try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
jmxConnection.connect();
Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
- jmxConnection.close();
policyLogger.debug("policyMap value retreived: " + o);
return o;
} catch (MalformedURLException e) {
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
index 46d24b207..6f8eea8e7 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
@@ -27,6 +27,7 @@ import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import javax.xml.bind.JAXBElement;
@@ -128,7 +129,7 @@ public class DecisionPolicyController extends RestrictedBaseController {
AttributeDesignatorType designator = match.getAttributeDesignator();
String attributeId = designator.getAttributeId();
// First match in the target is OnapName, so set that value.
- if (attributeId.equals("ONAPName")) {
+ if ("ONAPName".equals(attributeId)) {
policyAdapter.setOnapName(value);
}
// Component attributes are saved under Target here we are fetching them back.
@@ -151,16 +152,16 @@ public class DecisionPolicyController extends RestrictedBaseController {
if(!attributeList.isEmpty()) {
for(int i=0; i<attributeList.size() ; i++){
Map<String, String> map = (Map<String,String>)attributeList.get(i);
- if(map.get("key").equals("WorkStep")){
+ if("WorkStep".equals(map.get("key"))){
rainydayParams.setWorkstep(map.get("value"));
rainy=true;
- }else if(map.get("key").equals("BB_ID")){
+ }else if("BB_ID".equals(map.get("key"))){
rainydayParams.setBbid(map.get("value"));
rainy=true;
- }else if(map.get("key").equals("ServiceType")){
+ }else if("ServiceType".equals(map.get("key"))){
rainydayParams.setServiceType(map.get("value"));
rainy=true;
- }else if(map.get("key").equals("VNFType")){
+ }else if("VNFType".equals(map.get("key"))){
rainydayParams.setVnfType(map.get("value"));
rainy=true;
}
@@ -188,12 +189,12 @@ public class DecisionPolicyController extends RestrictedBaseController {
// get the condition data under the rule for rule Algorithms.
if(((RuleType) object).getEffect().equals(EffectType.DENY)) {
if(((RuleType) object).getAdviceExpressions()!=null){
- if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().equalsIgnoreCase("AAF")){
+ if("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
policyAdapter.setRuleProvider("AAF");
break;
- }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().equalsIgnoreCase("GUARD_YAML")){
+ }else if("GUARD_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
policyAdapter.setRuleProvider("GUARD_YAML");
- }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().equalsIgnoreCase("GUARD_BL_YAML")){
+ }else if("GUARD_BL_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
policyAdapter.setRuleProvider("GUARD_BL_YAML");
}
}else{
@@ -204,7 +205,7 @@ public class DecisionPolicyController extends RestrictedBaseController {
ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
ruleAlgoirthmTracker = new LinkedList<>();
- if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals("GUARD_YAML")||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){
+ if(policyAdapter.getRuleProvider()!=null && ("GUARD_YAML".equals(policyAdapter.getRuleProvider())||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){
YAMLParams yamlParams = new YAMLParams();
for(int i=0; i<attributeList.size() ; i++){
Map<String, String> map = (Map<String,String>)attributeList.get(i);
@@ -218,10 +219,10 @@ public class DecisionPolicyController extends RestrictedBaseController {
yamlParams.setClname(map.get("value"));
}
}
- ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue());
+ 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(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")){
+ 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<>();
@@ -245,7 +246,7 @@ public class DecisionPolicyController extends RestrictedBaseController {
prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
}
- } else if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("Rainy_Day")&& ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
+ } 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();
@@ -283,14 +284,13 @@ public class DecisionPolicyController extends RestrictedBaseController {
Map<String, String> ruleMap = new HashMap<>();
ruleMap.put("id", "A" + (index +1));
Map<String, String> dropDownMap = PolicyController.getDropDownMap();
- for (String key : dropDownMap.keySet()) {
- String keyValue = dropDownMap.get(key);
- if (keyValue.equals(decisionApply.getFunctionId())) {
- ruleMap.put("dynamicRuleAlgorithmCombo", key);
+ for (Entry<String, String> entry : dropDownMap.entrySet()) {
+ if (entry.getValue().equals(decisionApply.getFunctionId())) {
+ ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey());
}
}
// Populate the key and value fields
- if (((jaxbDecisionTypes.get(0).getValue()) instanceof AttributeValueType)) {
+ if ((jaxbDecisionTypes.get(0).getValue() instanceof AttributeValueType)) {
ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue();
List<JAXBElement<?>> jaxbInnerDecisionTypes = innerDecisionApply.getExpression();
if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) {
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
index e5ed3122e..7966af15b 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
@@ -38,7 +38,7 @@ import org.onap.policy.admin.RESTfulPAPEngine;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.model.PDPGroupContainer;
-import org.onap.policy.model.Roles;
+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;
@@ -88,26 +88,14 @@ public class PDPController extends RestrictedBaseController {
try {
PolicyController controller = getPolicyControllerInstance();
Set<PDPPolicy> filteredPolicies = new HashSet<>();
- Set<String> scopes = null;
- List<String> roles = null;
+ Set<String> scopes;
+ List<String> roles;
String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId();
List<Object> userRoles = controller.getRoles(userId);
- roles = new ArrayList<>();
- scopes = new HashSet<>();
- for(Object role: userRoles){
- Roles userRole = (Roles) role;
- roles.add(userRole.getRole());
- if(userRole.getScope() != null){
- if(userRole.getScope().contains(",")){
- String[] multipleScopes = userRole.getScope().split(",");
- for(int i =0; i < multipleScopes.length; i++){
- scopes.add(multipleScopes[i]);
- }
- }else{
- scopes.add(userRole.getScope());
- }
- }
- }
+ Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+ roles = pair.u;
+ scopes = pair.t;
+
if(!junit&& controller.getPapEngine()==null){
setPAPEngine(request);
}
@@ -118,39 +106,37 @@ public class PDPController extends RestrictedBaseController {
this.groups.addAll(this.getGroupsData());
}
}else{
- if(!userRoles.isEmpty()){
- if(!scopes.isEmpty()){
- this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
- List<OnapPDPGroup> tempGroups = new ArrayList<>();
- if(!groups.isEmpty()){
- Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
- while(pdpGroup.hasNext()){
- OnapPDPGroup group = pdpGroup.next();
- Set<PDPPolicy> policies = group.getPolicies();
- for(PDPPolicy policy : policies){
- for(String scope : scopes){
- scope = scope.replace(File.separator, ".");
- String policyName = policy.getId();
- if(policyName.contains(".Config_")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".Config_"));
- }else if(policyName.contains(".Action_")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".Action_"));
- }else if(policyName.contains(".Decision_")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_"));
- }
- if(policyName.startsWith(scope)){
- filteredPolicies.add(policy);
- }
+ if(!userRoles.isEmpty() && !scopes.isEmpty()){
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ List<OnapPDPGroup> tempGroups = new ArrayList<>();
+ if(!groups.isEmpty()){
+ Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
+ while(pdpGroup.hasNext()){
+ OnapPDPGroup group = pdpGroup.next();
+ Set<PDPPolicy> policies = group.getPolicies();
+ for(PDPPolicy policy : policies){
+ for(String scope : scopes){
+ scope = scope.replace(File.separator, ".");
+ String policyName = policy.getId();
+ if(policyName.contains(".Config_")){
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Config_"));
+ }else if(policyName.contains(".Action_")){
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Action_"));
+ }else if(policyName.contains(".Decision_")){
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_"));
+ }
+ if(policyName.startsWith(scope)){
+ filteredPolicies.add(policy);
}
}
- pdpGroup.remove();
- StdPDPGroup newGroup = (StdPDPGroup) group;
- newGroup.setPolicies(filteredPolicies);
- tempGroups.add(newGroup);
- }
- groups.clear();
- groups = tempGroups;
- }
+ }
+ pdpGroup.remove();
+ StdPDPGroup newGroup = (StdPDPGroup) group;
+ newGroup.setPolicies(filteredPolicies);
+ tempGroups.add(newGroup);
+ }
+ groups.clear();
+ groups = tempGroups;
}
}
}
@@ -254,7 +240,7 @@ public class PDPController extends RestrictedBaseController {
policyLogger.info("*****************************************************************************************************************************");
StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
- if(pdpGroupData.getName().equals("Default")) {
+ if("Default".equals(pdpGroupData.getName())) {
throw new UnsupportedOperationException("You can't remove the Default Group.");
}else{
this.container.removeGroup(pdpGroupData, null);
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
index 46510ba4f..2df70c726 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
@@ -29,6 +29,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Properties;
import javax.annotation.PostConstruct;
@@ -164,6 +165,7 @@ public class PolicyController extends RestrictedBaseController {
}
public PolicyController() {
+ // Empty constructor
}
@PostConstruct
@@ -241,8 +243,8 @@ public class PolicyController extends RestrictedBaseController {
//Initialize the FunctionDefinition table at Server Start up
Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
- for (Datatype id : functionMap.keySet()) {
- List<FunctionDefinition> functionDefinations = functionMap.get(id);
+ for ( Entry<Datatype, List<FunctionDefinition>> entry : functionMap.entrySet()) {
+ List<FunctionDefinition> functionDefinations = entry.getValue();
for (FunctionDefinition functionDef : functionDefinations) {
dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
index 5978f145e..5365af18c 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
@@ -29,7 +29,6 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
@@ -49,7 +48,6 @@ import org.apache.poi.ss.usermodel.Workbook;
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.model.Roles;
import org.onap.policy.rest.adapter.PolicyExportAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.ActionBodyEntity;
@@ -58,6 +56,7 @@ import org.onap.policy.rest.jpa.PolicyEditorScopes;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.onap.policy.rest.jpa.UserInfo;
+import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.web.support.UserUtils;
@@ -116,12 +115,14 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
PolicyExportAndImportController.commonClassDao = commonClassDao;
}
- public PolicyExportAndImportController(){}
+ public PolicyExportAndImportController(){
+ // Empty constructor
+ }
@RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
try{
- String file = null;
+ String file;
selectedPolicy = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
@@ -209,30 +210,17 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
boolean configExists = false;
boolean actionExists = false;
String configName = null;
- String scope = null;
- boolean finalColumn = false;
+ String scope;
+ boolean finalColumn;
PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
String userId = UserUtils.getUserSession(request).getOrgUserId();
UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId);
- //Check if the Role and Scope Size are Null get the values from db.
List<Object> userRoles = controller.getRoles(userId);
- roles = new ArrayList<>();
- scopes = new HashSet<>();
- for(Object role: userRoles){
- Roles userRole = (Roles) role;
- roles.add(userRole.getRole());
- if(userRole.getScope() != null){
- if(userRole.getScope().contains(",")){
- String[] multipleScopes = userRole.getScope().split(",");
- for(int i =0; i < multipleScopes.length; i++){
- scopes.add(multipleScopes[i]);
- }
- }else{
- scopes.add(userRole.getScope());
- }
- }
- }
+ Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+ roles = pair.u;
+ scopes = pair.t;
+
FileInputStream excelFile = new FileInputStream(new File(file));
workbook = new HSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
@@ -251,19 +239,19 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
Iterator<Cell> cellIterator = currentRow.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
- if (getCellHeaderName(cell).equalsIgnoreCase("policyName")) {
+ if ("policyName".equalsIgnoreCase(getCellHeaderName(cell))) {
policyEntity.setPolicyName(cell.getStringCellValue());
}
- if (getCellHeaderName(cell).equalsIgnoreCase("scope")) {
+ if ("scope".equalsIgnoreCase(getCellHeaderName(cell))) {
policyEntity.setScope(cell.getStringCellValue());
}
- if (getCellHeaderName(cell).equalsIgnoreCase("policyData")) {
+ if ("policyData".equalsIgnoreCase(getCellHeaderName(cell))) {
policyEntity.setPolicyData(cell.getStringCellValue());
}
- if (getCellHeaderName(cell).equalsIgnoreCase("description")) {
+ if ("description".equalsIgnoreCase(getCellHeaderName(cell))) {
policyEntity.setDescription(cell.getStringCellValue());
}
- if (getCellHeaderName(cell).equalsIgnoreCase("configurationbody")) {
+ if ("configurationbody".equalsIgnoreCase(getCellHeaderName(cell))) {
if(policyEntity.getPolicyName().contains("Config_")){
configExists = true;
configurationDataEntity.setConfigBody(cell.getStringCellValue());
@@ -272,7 +260,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
actionBodyEntity.setActionBody(cell.getStringCellValue());
}
}
- if (getCellHeaderName(cell).equalsIgnoreCase("configurationName")) {
+ if ("configurationName".equalsIgnoreCase(getCellHeaderName(cell))) {
finalColumn = true;
configName = cell.getStringCellValue();
if(policyEntity.getPolicyName().contains("Config_")){
@@ -312,7 +300,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
}
if (roles.contains(ADMIN) || roles.contains(EDITOR)) {
if(scopes.isEmpty()){
- //return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
+ logger.error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
}else{
//1. if Role contains admin, then check if parent scope has role admin, if not don't create a scope and add to list.
if(roles.contains(ADMIN)){
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java
index b9eb5ed15..170c30838 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java
@@ -21,6 +21,7 @@
package org.onap.policy.daoImp;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -253,7 +254,7 @@ public class CommonClassDaoImpl implements CommonClassDao{
@Override
public List<Object> checkExistingGroupListforUpdate(String arg0, String arg1) {
- return null;
+ return Collections.emptyList();
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java
index 5952761eb..d5767b46a 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java
@@ -113,7 +113,7 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier implements Po
}
public boolean isSupported(Object itemId) {
- return (itemId instanceof OnapPDPGroup);
+ return itemId instanceof OnapPDPGroup;
}
public synchronized void refreshGroups() {
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java
index 27fe71959..e73adf84b 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java
@@ -151,7 +151,7 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
if (this.policies.isEmpty()) {
return false;
}
- return (itemId.equals(this.policies.get(0)));
+ return itemId.equals(this.policies.get(0));
}
@Override
@@ -162,7 +162,7 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
if (this.policies.isEmpty()) {
return false;
}
- return (itemId.equals(this.policies.get(this.policies.size() - 1)));
+ return itemId.equals(this.policies.get(this.policies.size() - 1));
}
@Override
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java
index 3e935dd74..74576100a 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java
@@ -27,6 +27,7 @@ import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
+import java.util.Map.Entry;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -88,11 +89,9 @@ public class ConfigurableRESTUtils {
connection.setUseCaches(false);
// add hard-coded headers
- for (String headerName : hardCodedHeaderMap.keySet()) {
- connection.addRequestProperty(headerName, hardCodedHeaderMap.get(headerName));
+ for (Entry<String, String> entry : hardCodedHeaderMap.entrySet()) {
+ connection.addRequestProperty(entry.getKey(), entry.getValue());
}
-
-
if (jsonBody != null){
connection.setDoInput(true);
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java
new file mode 100644
index 000000000..a34983a5f
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java
@@ -0,0 +1,70 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2018 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.utils;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.onap.policy.controller.PolicyController;
+import org.onap.policy.model.Roles;
+
+public final class UserUtils {
+
+ private UserUtils () {
+ // Empty Constructor
+ }
+
+ public static class Pair<T, U> {
+ public final T t;
+ public final U u;
+
+ public Pair (T t, U u) {
+ this.t = t;
+ this.u = u;
+ }
+ }
+
+ public static Pair<Set<String>, List<String>> checkRoleAndScope(List<Object> userRoles) {
+ Set<String> scopes;
+ List<String> roles;
+ //Check if the Role and Scope Size are Null get the values from db.
+// List<Object> userRoles = ;
+ roles = new ArrayList<>();
+ scopes = new HashSet<>();
+ for(Object role: userRoles){
+ Roles userRole = (Roles) role;
+ roles.add(userRole.getRole());
+ if(userRole.getScope() != null){
+ if(userRole.getScope().contains(",")){
+ String[] multipleScopes = userRole.getScope().split(",");
+ for(int i =0; i < multipleScopes.length; i++){
+ scopes.add(multipleScopes[i]);
+ }
+ }else{
+ scopes.add(userRole.getScope());
+ }
+ }
+ }
+ return new Pair<>(scopes, roles);
+ }
+
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java
index 0fc293e5a..cbcf06249 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java
@@ -210,7 +210,7 @@ public class XACMLPolicyWriterWithPapNotify{
}
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8));
- HttpURLConnection connection = null;
+ HttpURLConnection connection;
UUID requestID = UUID.randomUUID();
URL url;
try {
@@ -297,7 +297,7 @@ public class XACMLPolicyWriterWithPapNotify{
public static boolean notifyPapOfDelete(String policyToDelete){
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8));
- HttpURLConnection connection = null;
+ HttpURLConnection connection;
UUID requestID = UUID.randomUUID();
String papUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
if(papUrl == null){
@@ -397,7 +397,7 @@ public class XACMLPolicyWriterWithPapNotify{
}
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8));
- HttpURLConnection connection = null;
+ HttpURLConnection connection;
UUID requestID = UUID.randomUUID();
URL url;
try {