From dda032f8bb161d54eb1f59de2b4a3efb774fc4d1 Mon Sep 17 00:00:00 2001 From: "ITSERVICES\\rb7147" Date: Mon, 8 May 2017 22:20:44 -0400 Subject: Policy 1707 Second commit Change-Id: I18f5b142238733d17280cf17c3d1dd28204d34e9 Signed-off-by: ITSERVICES\rb7147 --- .../policy/admin/PolicyManagerServlet.java | 221 +++++++--- .../policy/admin/PolicyRestController.java | 54 ++- .../policy/controller/AutoPushController.java | 27 +- .../CreateDcaeMicroServiceController.java | 446 ++++++++++++++++++++- .../controller/CreateFirewallController.java | 8 +- .../controller/DecisionPolicyController.java | 52 ++- .../policy/controller/PolicyController.java | 4 + .../controller/PolicyValidationController.java | 39 +- .../policy/daoImp/CommonClassDaoImpl.java | 3 - 9 files changed, 736 insertions(+), 118 deletions(-) (limited to 'POLICY-SDK-APP/src/main/java') diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java index 86210cdef..6c60c58c2 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java @@ -18,11 +18,6 @@ * ============LICENSE_END========================================================= */ -/* - * - * - * - * */ package org.openecomp.policy.admin; import java.io.BufferedReader; @@ -63,6 +58,7 @@ import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.http.HttpStatus; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; @@ -96,7 +92,7 @@ public class PolicyManagerServlet extends HttpServlet { private static final long serialVersionUID = -8453502699403909016L; private enum Mode { - LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT + LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST } private static String CONTENTTYPE = "application/json"; @@ -120,6 +116,7 @@ public class PolicyManagerServlet extends HttpServlet { } private static List serviceTypeNamesList = new ArrayList(); + private List policyData; public static List getServiceTypeNamesList() { return serviceTypeNamesList; @@ -276,6 +273,9 @@ public class PolicyManagerServlet extends HttpServlet { case SWITCHVERSION: responseJsonObject = switchVersion(params, request); break; + case SEARCHLIST: + responseJsonObject = searchPolicyList(params, request); + break; default: throw new ServletException("not implemented"); } @@ -292,6 +292,101 @@ public class PolicyManagerServlet extends HttpServlet { out.flush(); } + private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) { + Set scopes = null; + List roles = null; + policyData = null; + JSONArray policyList = null; + if(params.has("policyList")){ + policyList = (JSONArray) params.get("policyList"); + } + PolicyController controller = new PolicyController(); + List resultList = new ArrayList(); + 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 userRoles = PolicyController.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()); + } + } + } + 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"); + } + } + if(policyList!= null){ + for(int i = 0; i < policyList.length(); i++){ + String policyName = policyList.get(i).toString().replace(".xml", ""); + String version = policyName.substring(policyName.lastIndexOf(".")+1); + policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator); + if(policyName.contains("\\")){ + policyName = policyName.replace("\\", "\\\\"); + } + String policyVersionQuery = "From PolicyVersion where policy_name ='"+policyName+"' and active_version = '"+version+"'and id >0"; + List activeData = controller.getDataByQuery(policyVersionQuery); + if(!activeData.isEmpty()){ + PolicyVersion policy = (PolicyVersion) activeData.get(0); + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().replace(File.separator, "/")); + el.put("date", policy.getModifiedDate()); + el.put("version", policy.getActiveVersion()); + el.put("size", ""); + el.put("type", "file"); + el.put("createdBy", getUserName(policy.getCreatedBy())); + el.put("modifiedBy", getUserName(policy.getModifiedBy())); + resultList.add(el); + } + } + }else{ + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ){ + policyData = controller.getData(PolicyVersion.class); + }else{ + List filterdatas = controller.getData(PolicyVersion.class); + for(Object filter : filterdatas){ + PolicyVersion filterdata = (PolicyVersion) filter; + String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); + if(scopes.contains(scopeName)){ + policyData.add(filterdata); + } + } + } + + if(!policyData.isEmpty()){ + for(int i =0; i < policyData.size(); i++){ + PolicyVersion policy = (PolicyVersion) policyData.get(i); + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().replace(File.separator, "/")); + el.put("date", policy.getModifiedDate()); + el.put("version", policy.getActiveVersion()); + el.put("size", ""); + el.put("type", "file"); + el.put("createdBy", getUserName(policy.getCreatedBy())); + el.put("modifiedBy", getUserName(policy.getModifiedBy())); + resultList.add(el); + } + } + } + }catch(Exception e){ + LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e); + } + + return new JSONObject().put(RESULT, resultList); + } + //Switch Version Functionality private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{ String path = params.getString("path"); @@ -387,7 +482,7 @@ public class PolicyManagerServlet extends HttpServlet { String[] split = path.split(":"); String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; List queryData = controller.getDataByQuery(query); - if(queryData != null){ + if(!queryData.isEmpty()){ PolicyEntity entity = (PolicyEntity) queryData.get(0); File temp = null; try { @@ -731,7 +826,7 @@ public class PolicyManagerServlet extends HttpServlet { //Check Policy Group Entity table if policy has been pushed or not String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'"; List object = controller.getDataByQuery(query); - if(object == null){ + if(object.isEmpty()){ String oldPolicyNameWithoutExtension = removeoldPolicyExtension; String newPolicyNameWithoutExtension = removenewPolicyExtension; if(removeoldPolicyExtension.endsWith(".xml")){ @@ -926,7 +1021,7 @@ public class PolicyManagerServlet extends HttpServlet { controller.saveData(entityItem); } - LOGGER.debug("copy from: {} to: {}" + oldPath +newPath); + LOGGER.debug("copy from: {} to: {}" + oldPath +newPath); return success(); } catch (Exception e) { @@ -972,7 +1067,8 @@ public class PolicyManagerServlet extends HttpServlet { } List policyEntityobjects = controller.getDataByQuery(query); - boolean pdpCheck = true; + String activePolicyName = null; + boolean pdpCheck = false; if(path.endsWith(".xml")){ policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator); int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1)); @@ -982,38 +1078,43 @@ public class PolicyManagerServlet extends HttpServlet { policyEntity = (PolicyEntity) object; String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; List groupobject = controller.getDataByQuery(groupEntityquery); - if(groupobject != null){ - pdpCheck = false; - break; + if(!groupobject.isEmpty()){ + pdpCheck = true; + activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName(); + }else{ + //Delete the entity from Elastic Search Database + String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + restController.deleteElasticData(searchFileName); + //Delete the entity from Policy Entity table + controller.deleteData(policyEntity); + if(policyNamewithoutExtension.contains("Config_")){ + controller.deleteData(policyEntity.getConfigurationData()); + }else if(policyNamewithoutExtension.contains("Action_")){ + controller.deleteData(policyEntity.getActionBodyEntity()); + } } } } + //Policy Notification + PolicyVersion versionEntity = new PolicyVersion(); + versionEntity.setPolicyName(policyNamewithoutExtension); + versionEntity.setModifiedBy(userId); + controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll"); if(pdpCheck){ - for(Object object : policyEntityobjects){ - policyEntity = (PolicyEntity) object; - //Delete the entity from Elastic Search Database - String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - restController.deleteElasticData(searchFileName); - //Delete the entity from Policy Entity table - controller.deleteData(policyEntity); - if(policyNamewithoutExtension.contains("Config_")){ - controller.deleteData(policyEntity.getConfigurationData()); - }else if(policyNamewithoutExtension.contains("Action_")){ - controller.deleteData(policyEntity.getActionBodyEntity()); - } - } - //Policy Notification - PolicyVersion versionEntity = new PolicyVersion(); - versionEntity.setPolicyName(policyNamewithoutExtension); - versionEntity.setModifiedBy(userId); - controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll"); //Delete from policyVersion table - String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + String getActivePDPPolicyVersion = activePolicyName.replace(".xml", ""); + getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1); + String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; if(policyVersionQuery != null){ controller.executeQuery(policyVersionQuery); } + return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName); }else{ - return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'"); + //No Active Policy in PDP. So, deleting all entries from policyVersion table + String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + controller.executeQuery(policyVersionQuery); + } } }else if("CURRENT".equals(deleteVersion)){ String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1); @@ -1024,9 +1125,9 @@ public class PolicyManagerServlet extends HttpServlet { policyEntity = (PolicyEntity) policyEntitys.get(0); } if(policyEntity != null){ - String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; + String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0"; List groupobject = controller.getDataByQuery(groupEntityquery); - if(groupobject == null){ + if(groupobject.isEmpty()){ //Delete the entity from Elastic Search Database String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); restController.deleteElasticData(searchFileName); @@ -1040,7 +1141,7 @@ public class PolicyManagerServlet extends HttpServlet { if(version > 1){ int highestVersion = 0; - if(policyEntityobjects.isEmpty()){ + if(!policyEntityobjects.isEmpty()){ for(Object object : policyEntityobjects){ policyEntity = (PolicyEntity) object; String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); @@ -1072,18 +1173,16 @@ public class PolicyManagerServlet extends HttpServlet { } } }else{ + List activePoliciesInPDP = new ArrayList(); if(!policyEntityobjects.isEmpty()){ for(Object object : policyEntityobjects){ policyEntity = (PolicyEntity) object; String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; List groupobject = controller.getDataByQuery(groupEntityquery); - if(groupobject != null){ - pdpCheck = false; - } - } - if(pdpCheck){ - for(Object object : policyEntityobjects){ - policyEntity = (PolicyEntity) object; + if(!groupobject.isEmpty()){ + pdpCheck = true; + activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName()); + }else{ //Delete the entity from Elastic Search Database String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); restController.deleteElasticData(searchFileName); @@ -1096,17 +1195,35 @@ public class PolicyManagerServlet extends HttpServlet { controller.deleteData(policyEntity.getActionBodyEntity()); } } + } + //Delete from policyVersion and policyEditor Scope table + String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + controller.executeQuery(policyVersionQuery); + + //Policy Notification + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(path); + entity.setModifiedBy(userId); + controller.watchPolicyFunction(entity, path, "DeleteScope"); + if(pdpCheck){ + //Add Active Policies List to PolicyVersionTable + for(int i =0; i < activePoliciesInPDP.size(); i++){ + String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", ""); + int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1)); + activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator); + PolicyVersion insertactivePDPVersion = new PolicyVersion(); + insertactivePDPVersion.setPolicyName(activePDPPolicyName); + insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion); + insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion); + insertactivePDPVersion.setCreatedBy(userId); + insertactivePDPVersion.setModifiedBy(userId); + controller.saveData(insertactivePDPVersion); + } - //Delete from policyVersion and policyEditor Scope table - String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP); + }else{ String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; - controller.executeQuery(policyVersionQuery); - controller.executeQuery(policyScopeQuery); - //Policy Notification - PolicyVersion entity = new PolicyVersion(); - entity.setPolicyName(path); - entity.setModifiedBy(userId); - controller.watchPolicyFunction(entity, path, "DeleteScope"); + controller.executeQuery(policyScopeQuery); } } } diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java index 2a1129cf6..c40f0da0c 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java @@ -92,10 +92,29 @@ public class PolicyRestController extends RestrictedBaseController{ JsonNode root = mapper.readTree(request.getReader()); PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); - policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ policyData.isEditPolicy = true; } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + if(policyData.isEditPolicy){ + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + }else{ + String domain = root.get("policyData").get("model").get("name").toString(); + if(domain.contains("/")){ + domain = domain.substring(0, domain.lastIndexOf("/")).replace("/", File.separator); + } + domain = domain.replace("\"", ""); + policyData.setDomainDir(domain); + } + if(policyData.getConfigPolicyType() != null){ if(policyData.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")){ CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController(); @@ -111,19 +130,6 @@ public class PolicyRestController extends RestrictedBaseController{ policyData.setUserId(userId); - if(root.get("policyData").get("model").get("path").size() != 0){ - String dirName = ""; - for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ - dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; - } - if(policyData.isEditPolicy){ - policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); - }else{ - policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", "")); - } - }else{ - policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); - } String result; String body = PolicyUtils.objectToJsonString(policyData); String uri = request.getRequestURI(); @@ -253,7 +259,8 @@ public class PolicyRestController extends RestrictedBaseController{ connection.setDoOutput(true); connection.setDoInput(true); - if(!uri.contains("searchPolicy")){ + if(!uri.contains("searchPolicy?action=delete&")){ + if(!(uri.endsWith("set_BRMSParamData") || uri.contains("import_dictionary"))){ connection.setRequestProperty("Content-Type","application/json"); ObjectMapper mapper = new ObjectMapper(); @@ -371,6 +378,23 @@ public class PolicyRestController extends RestrictedBaseController{ return null; } + @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST}) + public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String uri = request.getRequestURI()+"?action=search"; + String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim()); + JSONObject json = new JSONObject(body); + Object resultList = json.get("policyresult"); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{result: " + resultList + "}"); + out.write(j.toString()); + return null; + } + public void deleteElasticData(String fileName){ String uri = "searchPolicy?action=delete&policyName='"+fileName+"'"; callPAP(null, null, "POST", uri.trim()); diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java index 77bcea6ef..86d9920d9 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java @@ -106,7 +106,7 @@ public class AutoPushController extends RestrictedBaseController{ try{ Set scopes = null; List roles = null; - data = null; + data = new ArrayList(); String userId = UserUtils.getUserSession(request).getOrgUserId(); Map model = new HashMap(); ObjectMapper mapper = new ObjectMapper(); @@ -123,20 +123,29 @@ public class AutoPushController extends RestrictedBaseController{ scopes.add(multipleScopes[i]); } }else{ - scopes.add(userRole.getScope()); + if(!userRole.getScope().equals("")){ + scopes.add(userRole.getScope()); + } } } } - if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) { + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { data = commonClassDao.getData(PolicyVersion.class); }else{ - List filterdatas = commonClassDao.getData(PolicyVersion.class); - for(Object filter : filterdatas){ - PolicyVersion filterdata = (PolicyVersion) filter; - String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); - if(scopes.contains(scopeName)){ - data.add(filterdata); + if(!scopes.isEmpty()){ + for(String scope : scopes){ + String query = "From PolicyVersion where policy_name like '"+scope+"%' and id > 0"; + List filterdatas = commonClassDao.getDataByQuery(query); + if(filterdatas != null){ + for(int i =0; i < filterdatas.size(); i++){ + data.add(filterdatas.get(i)); + } + } } + }else{ + PolicyVersion emptyPolicyName = new PolicyVersion(); + emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); + data.add(emptyPolicyName); } } model.put("policydatas", mapper.writeValueAsString(data)); diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java index 570ceac31..aeb5266c5 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java @@ -24,8 +24,11 @@ package org.openecomp.policy.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.file.Files; @@ -75,6 +78,7 @@ import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; +import org.yaml.snakeyaml.Yaml; import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.core.JsonProcessingException; @@ -105,6 +109,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private List modelList = new ArrayList(); private List dirDependencyList = new ArrayList(); private HashMap classMap = new HashMap(); + //Tosca Model related Datastructure. + String referenceAttributes; + String attributeString; + String listConstraints; + String subAttributeString; + HashMap retmap = new HashMap(); + Set uniqueKeys= new HashSet(); + Set uniqueDataKeys= new HashSet(); @Autowired private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){ @@ -191,7 +203,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } catch (JsonProcessingException e) { logger.error("Error writing out the object"); } - System.out.println(json); + logger.info(json); String cleanJson = cleanUPJson(json); cleanJson = removeNullAttributes(cleanJson); policyAdapter.setJsonBody(cleanJson); @@ -223,8 +235,360 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } return cleanJson; } + + // Second index of dot should be returned. + public void stringBetweenDots(String str,String value){ + String stringToSearch=str; + String[]ss=stringToSearch.split("\\."); + if(ss!=null){ + int len= ss.length; + if(len>2){ + uniqueKeys.add(ss[2]); + } + } + } + + public void stringBetweenDotsForDataFields(String str,String value){ + String stringToSearch=str; + String[]ss=stringToSearch.split("\\."); + if(ss!=null){ + int len= ss.length; + if(len>2){ + uniqueDataKeys.add(ss[0]+"%"+ss[2]); + } + } + } + + public Map load(String fileName) throws IOException { + File newConfiguration = new File(fileName); + InputStream is = null; + try { + is = new FileInputStream(newConfiguration); + } catch (FileNotFoundException e) { + logger.error(e); + } + + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map yamlMap = (Map) yaml.load(is); + StringBuilder sb = new StringBuilder(); + Map settings = new HashMap(); + if (yamlMap == null) { + return settings; + } + List path = new ArrayList(); + serializeMap(settings, sb, path, yamlMap); + return settings; + } + + public Map load(byte[] source) throws IOException { + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map yamlMap = (Map) yaml.load(source.toString()); + StringBuilder sb = new StringBuilder(); + Map settings = new HashMap(); + if (yamlMap == null) { + return settings; + } + List path = new ArrayList(); + serializeMap(settings, sb, path, yamlMap); + return settings; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void serializeMap(Map settings, StringBuilder sb, List path, Map yamlMap) { + for (Map.Entry entry : yamlMap.entrySet()) { + if (entry.getValue() instanceof Map) { + path.add((String) entry.getKey()); + serializeMap(settings, sb, path, (Map) entry.getValue()); + path.remove(path.size() - 1); + } else if (entry.getValue() instanceof List) { + path.add((String) entry.getKey()); + serializeList(settings, sb, path, (List) entry.getValue()); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue()); + } + } + } + + @SuppressWarnings("unchecked") + private void serializeList(Map settings, StringBuilder sb, List path, List yamlList) { + int counter = 0; + for (Object listEle : yamlList) { + if (listEle instanceof Map) { + path.add(Integer.toString(counter)); + serializeMap(settings, sb, path, (Map) listEle); + path.remove(path.size() - 1); + } else if (listEle instanceof List) { + path.add(Integer.toString(counter)); + serializeList(settings, sb, path, (List) listEle); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, Integer.toString(counter), listEle); + } + counter++; + } + } + + private void serializeValue(Map settings, StringBuilder sb, List path, String name, Object value) { + if (value == null) { + return; + } + sb.setLength(0); + for (String pathEle : path) { + sb.append(pathEle).append('.'); + } + sb.append(name); + settings.put(sb.toString(), value.toString()); + } + + + public void parseTosca (String fileName){ + Map map= new HashMap(); + try { + map=load(fileName); + for(String key:map.keySet()){ + if(key.contains("policy.nodes.Root")) + { + continue; + } + else if(key.contains("policy.nodes")){ + String wordToFind = "policy.nodes."; + int indexForPolicyNode=key.indexOf(wordToFind); + String subNodeString= key.substring(indexForPolicyNode+13, key.length()); + + stringBetweenDots(subNodeString,map.get(key)); + } + else if(key.contains("policy.data")){ + String wordToFind="policy.data."; + int indexForPolicyNode=key.indexOf(wordToFind); + String subNodeString= key.substring(indexForPolicyNode+12, key.length()); + + stringBetweenDotsForDataFields(subNodeString,map.get(key)); + Iterator itr= uniqueDataKeys.iterator(); + while(itr.hasNext()){ + logger.info(itr.next()); + } + } + } + + String attributeIndividualString=""; + String userDefinedIndividualString=""; + String referenceIndividualAttributes=""; + + String attributeString=""; + String userDefinedString=""; + String referenceAttributes=""; + String listConstraints=""; + + for(String uniqueDataKey: uniqueDataKeys){ + String[] uniqueDataKeySplit= uniqueDataKey.split("%"); + userDefinedIndividualString=userDefinedIndividualString+uniqueDataKey+"="; + userDefinedIndividualString=userDefinedIndividualString+"#A:defaultValue-#B:required-#C:MANY-false"; + for(String key:map.keySet()){ + if(key.contains("policy.data")){ + String containsKey= uniqueDataKeySplit[1]+".type"; + if(key.contains(uniqueDataKeySplit[0])){ + if(key.contains("default")){ + userDefinedIndividualString=userDefinedIndividualString.replace("#B", map.get(key)); + } + else if(key.contains("required")){ + userDefinedIndividualString=userDefinedIndividualString.replace("#C", map.get(key)); + } + else if(key.contains(containsKey)){ + String typeValue= map.get(key); + userDefinedIndividualString=userDefinedIndividualString.replace("#A", typeValue); + } + } + } + + } + if(userDefinedString!=""){ + userDefinedString=userDefinedString+","+userDefinedIndividualString; + }else{ + userDefinedString=userDefinedString+userDefinedIndividualString; + } + userDefinedIndividualString=""; + } + logger.info("userDefinedString :"+userDefinedString); + + HashMap> mapKey= new HashMap>(); + String secondPartString=""; + String firstPartString=""; + for(String value: userDefinedString.split(",")){ + String[] splitWithEquals= value.split("="); + secondPartString=splitWithEquals[0].substring(splitWithEquals[0].indexOf("%")+1); + firstPartString=splitWithEquals[0].substring(0, splitWithEquals[0].indexOf("%")); + ArrayList list; + if(mapKey.containsKey(firstPartString)){ + list = mapKey.get(firstPartString); + list.add(secondPartString+"<"+splitWithEquals[1]); + } else { + list = new ArrayList(); + list.add(secondPartString+"<"+splitWithEquals[1]); + mapKey.put(firstPartString, list); + } + } + + JSONObject mainObject= new JSONObject();; + JSONObject json; + for(String s: mapKey.keySet()){ + json= new JSONObject(); + List value=mapKey.get(s); + for(String listValue:value){ + String[] splitValue=listValue.split("<"); + json.put(splitValue[0], splitValue[1]); + } + mainObject.put(s,json); + } + + logger.info(mainObject); + + Iterator keysItr = mainObject.keys(); + while(keysItr.hasNext()) { + String key = keysItr.next(); + String value = mainObject.get(key).toString(); + retmap.put(key, value); + } + + for(String str:retmap.keySet()){ + logger.info(str+":"+retmap.get(str)); + } + + String typeValueFromKey=""; + boolean userDefinedDataType=false; + boolean isList=false; + for(String uniqueKey: uniqueKeys){ + List constraints= new ArrayList(); + logger.info("===================="); + attributeIndividualString=attributeIndividualString+uniqueKey+"="; + attributeIndividualString=attributeIndividualString+"#A:defaultValue-#B:required-#C:MANY-false"; + + logger.info("UniqueStrings: "+uniqueKey); + for(String key:map.keySet()){ + if(key.contains("policy.nodes.Root")|| + key.contains("policy.data")) + { + continue; + } + else if(key.contains("policy.nodes")){ + if(key.contains(uniqueKey)){ + int p=key.lastIndexOf("."); + String firstLastOccurance=key.substring(0,p); + int p1=firstLastOccurance.lastIndexOf("."); + String secondLastOccurance= firstLastOccurance.substring(p1+1,firstLastOccurance.length()); + if(secondLastOccurance.equals(uniqueKey)){ + String checkTypeString= firstLastOccurance+".type"; + typeValueFromKey= map.get(checkTypeString); + }//Its a list. + else if (key.contains("entry_schema")){ + if(key.contains("constraints")){ + constraints.add(map.get(key)); + } + if(key.contains("type")){ + isList=true; + String value= map.get(key); + if(! (value.contains("string")) || + (value.contains("integer")) || + (value.contains("boolean")) ) + { + if(!key.contains("valid_values")){ + String trimValue=value.substring(value.lastIndexOf(".")+1); + referenceIndividualAttributes=referenceIndividualAttributes+uniqueKey+"="+trimValue+":MANY-true"; + attributeIndividualString=""; + } + + } + } + } + + if(!(typeValueFromKey.equals("string")|| + typeValueFromKey.equals("integer") || + typeValueFromKey.equals("boolean"))) + { + if(typeValueFromKey.equals("list")){ + isList=true; + userDefinedDataType=false; + } + else{ + userDefinedDataType=true; + } + } + if(userDefinedDataType==false && isList==false){ + if(key.contains("default")){ + attributeIndividualString=attributeIndividualString.replace("#B", map.get(key)); + } + else if(key.contains("required")){ + attributeIndividualString=attributeIndividualString.replace("#C", map.get(key)); + } + else if(key.contains("type")){ + String typeValue= map.get(key); + attributeIndividualString=attributeIndividualString.replace("#A", typeValue); + } + } + else if(userDefinedDataType==true){ + String checkTypeAndUpdate=key.substring(p+1); + if(checkTypeAndUpdate.equals("type")){ + String value=map.get(key); + String trimValue=value.substring(value.lastIndexOf(".")+1); + referenceIndividualAttributes=referenceIndividualAttributes+uniqueKey+"="+trimValue+":MANY-false"; + } + attributeIndividualString=""; + } + } + } + } + + if(constraints!=null &&constraints.isEmpty()==false){ + //List handling. + listConstraints=uniqueKey.toUpperCase()+"=["; + isList=true; + for(String str:constraints){ + listConstraints=listConstraints+str+","; + } + listConstraints+="],"; + logger.info(listConstraints); + attributeIndividualString=""; + referenceIndividualAttributes=referenceIndividualAttributes+uniqueKey+"="+uniqueKey.toUpperCase()+":MANY-false"; + constraints=null; + + } + if(userDefinedDataType==false && isList==false){ + if(attributeString!=""){ + attributeString=attributeString+","+attributeIndividualString; + }else{ + attributeString=attributeString+attributeIndividualString; + } + } + if(isList==true || userDefinedDataType==true){ + if(referenceAttributes!=""){ + referenceAttributes=referenceAttributes+","+referenceIndividualAttributes; + }else{ + referenceAttributes=referenceAttributes+referenceIndividualAttributes; + } + logger.info("ReferenceAttributes: "+referenceAttributes); + } + + logger.info("AttributeString: "+ attributeString); + logger.info("ListConstraints is: "+listConstraints); + + attributeIndividualString=""; + referenceIndividualAttributes=""; + userDefinedDataType=false; + isList=false; + + } + this.listConstraints=listConstraints; + this.referenceAttributes=referenceAttributes; + this.attributeString=attributeString; + } catch (IOException e) { + logger.error(e); + } + } + private String cleanUPJson(String json) { String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"}); cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"}); @@ -269,7 +633,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { presKey = key; } // first check if we are different from old. - System.out.println(key+"\n"); + logger.info(key+"\n"); if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){ if(!oldValue.equals(key.substring(0,key.indexOf("@")))){ jsonResult.put(oldValue, jsonArray); @@ -444,7 +808,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return null; } - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) private String createMicroSeriveJson(MicroServiceModels returnModel) { Map attributeMap = new HashMap(); Map refAttributeMap = new HashMap(); @@ -620,7 +984,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { response.getWriter().write(j.toString()); } catch (Exception e){ - e.printStackTrace(); + logger.error(e); } } @@ -755,7 +1119,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } catch (Exception e) { - e.printStackTrace(); + logger.error(e); } } @@ -852,8 +1216,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws Exception{ List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); boolean zip = false; + boolean yml= false; for (FileItem item : items) { - if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")){ + if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){ this.newModel = new MicroServiceModels(); try{ File file = new File(item.getName()); @@ -862,41 +1227,81 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { outputStream.close(); this.newFile = file.toString(); this.newModel.setModelName(this.newFile.toString().split("-v")[0]); + if (this.newFile.toString().contains("-v")){ if (item.getName().endsWith(".zip")){ this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", "")); zip = true; - }else { + }else if(item.getName().endsWith(".yml")){ + this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", "")); + yml = true; + } + else { this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", "")); } } + }catch(Exception e){ logger.error("Upload error : " + e); } } + } List fileList = new ArrayList();; this.directory = "model"; if (zip){ extractFolder(this.newFile); fileList = listModelFiles(this.directory); + }else if (yml==true){ + parseTosca(this.newFile); }else { File file = new File(this.newFile); fileList.add(file); } - - //Process Main Model file first - classMap = new HashMap(); - for (File file : fileList) { - if(!file.isDirectory() && file.getName().endsWith(".xmi")){ - retreiveDependency(file.toString(), true); - } + String modelType= ""; + if(yml==false){ + modelType="xmi"; + //Process Main Model file first + classMap = new HashMap(); + for (File file : fileList) { + if(!file.isDirectory() && file.getName().endsWith(".xmi")){ + retreiveDependency(file.toString(), true); + } + } + + modelList = createList(); + + cleanUp(this.newFile); + cleanUp(directory); + }else{ + modelType="yml"; + modelList.add(this.newModel.getModelName()); + String className=this.newModel.getModelName(); + MSAttributeObject msAttributes= new MSAttributeObject(); + msAttributes.setClassName(className); + + HashMap returnAttributeList =new HashMap(); + returnAttributeList.put(className, this.attributeString); + msAttributes.setAttribute(returnAttributeList); + + msAttributes.setSubClass(this.retmap); + + HashMap returnReferenceList =new HashMap(); + //String[] referenceArray=this.referenceAttributes.split("="); + returnReferenceList.put(className, this.referenceAttributes); + msAttributes.setRefAttribute(returnReferenceList); + + if(this.listConstraints!=""){ + HashMap enumList =new HashMap(); + String[] listArray=this.listConstraints.split("="); + enumList.put(listArray[0], listArray[1]); + msAttributes.setEnumType(enumList); + } + + classMap=new HashMap(); + classMap.put(className, msAttributes); + } - - modelList = createList(); - - cleanUp(this.newFile); - cleanUp(directory); PrintWriter out = response.getWriter(); @@ -908,6 +1313,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { JSONObject j = new JSONObject(); j.put("classListDatas", modelList); j.put("modelDatas", mapper.writeValueAsString(classMap)); + j.put("modelType", modelType); out.write(j.toString()); } @@ -969,7 +1375,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); classMap.putAll(tempMap); - System.out.println(tempMap); + logger.info(tempMap); return; diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java index ecc39cdb6..41c960680 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java @@ -19,8 +19,6 @@ */ package org.openecomp.policy.controller; - - import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; @@ -514,7 +512,7 @@ public class CreateFirewallController extends RestrictedBaseController { ServiceListJson targetSl=null; int i=0; try{ - + String networkRole=""; for(String tag:tagCollectorList){ tags= new Tags(); List tagListData = commonClassDao.getData(FWTagPicker.class); @@ -535,12 +533,14 @@ public class CreateFirewallController extends RestrictedBaseController { tagList.add(tagDefine); } - + networkRole=jpaTagPickerList.getNetworkRole(); + break; } } tags.setTags(tagList); tags.setTagPickerName(tag); tags.setRuleName(termCollectorList.get(i)); + tags.setNetworkRole(networkRole); tagsList.add(tags); i++; } diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java index d21788e90..57e8821f4 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java @@ -29,14 +29,14 @@ import java.util.Map; import javax.xml.bind.JAXBElement; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.adapter.YAMLParams; import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; @@ -150,24 +150,47 @@ public class DecisionPolicyController extends RestrictedBaseController { decisionList.add(settings); } else if (object instanceof RuleType) { // get the condition data under the rule for rule Algorithms. - if (((RuleType) object).getEffect().equals(EffectType.PERMIT)) { - ConditionType condition = ((RuleType) object).getCondition(); - if (condition != null) { - ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); - ruleAlgoirthmTracker = new LinkedList(); - // Populating Rule Algorithms starting from compound. - prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); - } - }else if(((RuleType) object).getEffect().equals(EffectType.DENY)) { + if(((RuleType) object).getEffect().equals(EffectType.DENY)) { if(((RuleType) object).getAdviceExpressions()!=null){ if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("AAF")){ policyAdapter.setRuleProvider("AAF"); break; + }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_YAML")){ + policyAdapter.setRuleProvider("GUARD_YAML"); } }else{ policyAdapter.setRuleProvider("Custom"); } + ConditionType condition = ((RuleType) object).getCondition(); + if (condition != null) { + ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); + decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue(); + ruleAlgoirthmTracker = new LinkedList(); + if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("GUARD_YAML")){ + YAMLParams yamlParams = new YAMLParams(); + for(int i=0; i map = (Map)attributeList.get(i); + if(map.get("key").equals("actor")){ + yamlParams.setActor(map.get("value")); + }else if(map.get("key").equals("recipe")){ + yamlParams.setRecipe(map.get("value")); + } + } + ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue()); + yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString()); + yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString()); + yamlParams.setLimit(((AttributeValueType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(1).getValue()).getContent().get(0).toString()); + String timeWindow = ((AttributeDesignatorType)((ApplyType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer(); + yamlParams.setTimeWindow(timeWindow.substring(timeWindow.lastIndexOf(":")+1)); + policyAdapter.setYamlparams(yamlParams); + policyAdapter.setAttributes(new ArrayList()); + policyAdapter.setRuleAlgorithmschoices(new ArrayList()); + break; + } + // Populating Rule Algorithms starting from compound. + prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } } } } @@ -244,6 +267,7 @@ public class DecisionPolicyController extends RestrictedBaseController { String keyValue = PolicyController.getDropDownMap().get(key); if (keyValue.equals(decisionApply.getFunctionId())) { rule.put("dynamicRuleAlgorithmCombo", key); + break; } } diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java index 72dfb164b..7d8701ef4 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java @@ -361,6 +361,10 @@ public class PolicyController extends RestrictedBaseController { public void deleteData(Object entity) { commonClassDao.delete(entity); } + + public List getData(@SuppressWarnings("rawtypes") Class className){ + return commonClassDao.getData(className); + } public PolicyVersion getPolicyEntityFromPolicyVersion(String query){ PolicyVersion policyVersionEntity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query); diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java index 55bff24a0..eb144cc18 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java @@ -448,7 +448,44 @@ public class PolicyValidationController extends RestrictedBaseController { responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "
"; valid = false; } - + if(policyData.getRuleProvider().equals("GUARD_YAML")){ + if(policyData.getYamlparams()==null){ + responseString = responseString + " Guard Params are Required " + "
"; + valid = false; + }else{ + if(policyData.getYamlparams().getActor()==null){ + responseString = responseString + "Guard Params Actor is Required " + "
"; + valid = false; + } + if(policyData.getYamlparams().getRecipe()==null){ + responseString = responseString + "Guard Params Recipe is Required " + "
"; + valid = false; + } + if(policyData.getYamlparams().getLimit()==null){ + responseString = responseString + " Guard Params Limit is Required " + "
"; + valid = false; + }else{ + try{ + Integer.parseInt(policyData.getYamlparams().getLimit()); + }catch(NumberFormatException e){ + responseString = responseString + " Guard Params Limit Should be Integer " + "
"; + valid = false; + } + } + if(policyData.getYamlparams().getTimeWindow()==null){ + responseString = responseString + "Guard Params Time Window is Required" + "
"; + valid = false; + } + if(policyData.getYamlparams().getGuardActiveStart()==null){ + responseString = responseString + "Guard Params Guard Active Start/b>is Required " + "
"; + valid = false; + } + if(policyData.getYamlparams().getGuardActiveEnd()==null){ + responseString = responseString + "Guard Params Guard Active Endis Required " + "
"; + valid = false; + } + } + } } if(policyData.getPolicyType().equals(ACTION_POLICY)){ diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java index 6ac4afbcf..9cb41eeab 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java @@ -264,8 +264,6 @@ public class CommonClassDaoImpl implements CommonClassDao{ @SuppressWarnings("rawtypes") @Override public Object getEntityItem(Class className, String columnName, String key) { - System.out.println(columnName); - System.out.println(key); Session session = sessionfactory.openSession(); Transaction tx = session.beginTransaction(); Object data = null; @@ -281,7 +279,6 @@ public class CommonClassDaoImpl implements CommonClassDao{ cr.add(Restrictions.eq(columnName, key)); } data = cr.list().get(0); - System.out.println(data); tx.commit(); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); -- cgit 1.2.3-korg