aboutsummaryrefslogtreecommitdiffstats
path: root/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller
diff options
context:
space:
mode:
Diffstat (limited to 'POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller')
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java266
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java100
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java355
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java508
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java173
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java696
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java206
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java1139
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java932
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java165
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java420
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java262
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java292
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java421
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java367
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java122
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java163
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java661
18 files changed, 7248 insertions, 0 deletions
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java
new file mode 100644
index 000000000..2e555f254
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java
@@ -0,0 +1,266 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.bind.JAXBElement;
+
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+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;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+
+@Controller
+@RequestMapping({"/"})
+public class ActionPolicyController extends RestrictedBaseController{
+ private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class);
+
+ public ActionPolicyController(){}
+
+ private ArrayList<Object> attributeList;
+ protected LinkedList<Integer> ruleAlgoirthmTracker;
+ public static final String PERFORMER_ATTRIBUTEID = "performer";
+ protected Map<String, String> performer = new HashMap<String, String>();
+ private ArrayList<Object> ruleAlgorithmList;
+
+ public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ attributeList = new ArrayList<Object>();
+ ruleAlgorithmList = new ArrayList<Object>();
+ performer.put("PDP", "PDPAction");
+ performer.put("PEP", "PEPAction");
+
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy for Action.
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AntOfType we have AllOfType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOfType we have Mathch.
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attributevalue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // Component attributes are saved under Target here we are fetching them back.
+ // One row is default so we are not adding dynamic componet at index 0.
+ Map<String, String> attribute = new HashMap<String, String>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ }
+ }
+ policyAdapter.setAttributes(attributeList);
+ }
+ }
+ }
+ }
+
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ // Under rule we have Condition and obligation.
+ for (Object o : ruleList) {
+ if (o instanceof RuleType) {
+ ConditionType condition = ((RuleType) o).getCondition();
+ ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions();
+ if (condition != null) {
+ int index = 0;
+ ApplyType actionApply = (ApplyType) condition.getExpression().getValue();
+ ruleAlgoirthmTracker = new LinkedList<Integer>();
+ // Populating Rule Algorithms starting from compound.
+ prePopulateCompoundRuleAlgorithm(index, actionApply);
+ }
+ policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
+ // get the Obligation data under the rule for Form elements.
+ if (obligations != null) {
+ // Under the obligationExpressions we have obligationExpression.
+ List<ObligationExpressionType> obligationList = obligations.getObligationExpression();
+ if (obligationList != null) {
+ Iterator<ObligationExpressionType> iterObligation = obligationList.iterator();
+ while (iterObligation.hasNext()) {
+ ObligationExpressionType obligation = iterObligation.next();
+ policyAdapter.setActionAttributeValue(obligation.getObligationId());
+ // Under the obligationExpression we have attributeAssignmentExpression.
+ List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation.getAttributeAssignmentExpression();
+ if (attributeAssignmentExpressionList != null) {
+ Iterator<AttributeAssignmentExpressionType> iterAttributeAssignmentExpression = attributeAssignmentExpressionList.iterator();
+ while (iterAttributeAssignmentExpression.hasNext()) {
+ AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression.next();
+ String attributeID = attributeAssignmentExpression.getAttributeId();
+ AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression.getExpression().getValue();
+ if (attributeID.equals(PERFORMER_ATTRIBUTEID)) {
+ for (String key : performer.keySet()) {
+ String keyValue = performer.get(key);
+ if (keyValue.equals(attributeValue.getContent().get(0))) {
+ policyAdapter.setActionPerformer(key);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private int prePopulateCompoundRuleAlgorithm(int index, ApplyType actionApply) {
+ boolean isCompoundRule = true;
+ List<JAXBElement<?>> jaxbActionTypes = actionApply.getExpression();
+ for (JAXBElement<?> jaxbElement : jaxbActionTypes) {
+ // If There is Attribute Value under Action Type that means we came to the final child
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Prepopulating rule algoirthm: " + index);
+ }
+ // Check to see if Attribute Value exists, if yes then it is not a compound rule
+ if (jaxbElement.getValue() instanceof AttributeValueType) {
+ prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes);
+ ruleAlgoirthmTracker.addLast(index);
+ isCompoundRule = false;
+ index++;
+ }
+ }
+ if (isCompoundRule) {
+ // As it's compound rule, Get the Apply types
+ for (JAXBElement<?> jaxbElement : jaxbActionTypes) {
+ ApplyType innerActionApply = (ApplyType) jaxbElement.getValue();
+ index = prePopulateCompoundRuleAlgorithm(index, innerActionApply);
+ }
+ // Populate combo box
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Prepopulating Compound rule algorithm: " + index);
+ }
+ Map<String, String> rule = new HashMap<String, String>();
+ for (String key : PolicyController.getDropDownMap().keySet()) {
+ String keyValue = PolicyController.getDropDownMap().get(key);
+ if (keyValue.equals(actionApply.getFunctionId())) {
+ rule.put("dynamicRuleAlgorithmCombo", key);
+ }
+ }
+ rule.put("id", "A" + (index +1));
+ // Populate Key and values for Compound Rule
+ rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 ));
+ ruleAlgoirthmTracker.removeLast();
+ rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
+ ruleAlgoirthmTracker.removeLast();
+ ruleAlgoirthmTracker.addLast(index);
+ ruleAlgorithmList.add(rule);
+ index++;
+ }
+ return index;
+ }
+
+ private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List<JAXBElement<?>> jaxbActionTypes) {
+ Map<String, String> ruleMap = new HashMap<String, String>();
+ 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);
+ }
+ }
+ // Populate the key and value fields
+ // Rule Attribute added as key
+ if ((jaxbActionTypes.get(0).getValue()) instanceof ApplyType) {
+ // Get from Attribute Designator
+ ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue();
+ List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
+ AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
+ ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
+
+ // Get from Attribute Value
+ AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue();
+ String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
+ ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
+ }
+ // Rule Attribute added as value
+ else if (((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType)) {
+ AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue();
+ String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
+ ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
+
+ ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue();
+ List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
+ AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
+ ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
+ }
+ ruleAlgorithmList.add(ruleMap);
+ }
+
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java
new file mode 100644
index 000000000..ee5ed7279
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java
@@ -0,0 +1,100 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.GlobalRoleSettings;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping({"/"})
+public class AdminTabController extends RestrictedBaseController{
+
+ @Autowired
+ CommonClassDao commonClassDao;
+
+
+
+ @RequestMapping(value={"/get_LockDownData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+ @RequestMapping(value={"/adminTabController/save_LockDownValue.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ GlobalRoleSettings globalRole = mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class);
+ globalRole.setRole("super-admin");
+ commonClassDao.update(globalRole);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class));
+ JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
+
+ out.write(j.toString());
+
+ return null;
+ }
+ catch (Exception e){
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+}
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
new file mode 100644
index 000000000..77bcea6ef
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java
@@ -0,0 +1,355 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.model.PDPGroupContainer;
+import org.openecomp.policy.model.PDPPolicyContainer;
+import org.openecomp.policy.model.Roles;
+import org.openecomp.policy.rest.adapter.AutoPushTabAdapter;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.policy.rest.jpa.PolicyVersion;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
+import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
+import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.web.support.JsonMessage;
+import org.openecomp.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.api.pap.PDPPolicy;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+
+@Controller
+@RequestMapping({"/"})
+public class AutoPushController extends RestrictedBaseController{
+
+ private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
+
+ @Autowired
+ CommonClassDao commonClassDao;
+
+ private PDPGroupContainer container;
+ protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>());
+
+ private static PDPPolicyContainer policyContainer;
+ Set<PDPPolicy> selectedPolicies;
+
+ private List<Object> data;
+
+ public synchronized void refreshGroups() {
+ synchronized(this.groups) {
+ this.groups.clear();
+ try {
+ this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
+ } catch (PAPException e) {
+ String message = "Unable to retrieve Groups from server: " + e;
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
+ }
+
+ }
+ }
+
+ @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Set<String> scopes = null;
+ List<String> roles = null;
+ data = null;
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ List<Object> userRoles = PolicyController.getRoles(userId);
+ roles = new ArrayList<String>();
+ scopes = new HashSet<String>();
+ 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("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) {
+ data = commonClassDao.getData(PolicyVersion.class);
+ }else{
+ List<Object> 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);
+ }
+ }
+ }
+ model.put("policydatas", mapper.writeValueAsString(data));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+ @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ try {
+ ArrayList<Object> selectedPDPS = new ArrayList<Object>();
+ ArrayList<String> selectedPoliciesInUI = new ArrayList<String>();
+ this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
+ ObjectMapper mapper = new ObjectMapper();
+ this.container = new PDPGroupContainer(PolicyController.getPapEngine());
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ AutoPushTabAdapter adapter = (AutoPushTabAdapter) mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
+ for (Object pdpGroupId : adapter.getPdpDatas()) {
+ LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
+ for(EcompPDPGroup pdpGroup : this.groups){
+ if(pdpGroup.getId().equals(selectedPDP.get("id"))){
+ selectedPDPS.add(pdpGroup);
+ }
+ }
+ }
+
+ for (Object policyId : adapter.getPolicyDatas()) {
+ LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
+ String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
+ selectedPoliciesInUI.add(policyName);
+ }
+
+ for (Object pdpDestinationGroupId : selectedPDPS) {
+ Set<PDPPolicy> currentPoliciesInGroup = new HashSet<PDPPolicy>();
+ Set<PDPPolicy> selectedPolicies = new HashSet<PDPPolicy>();
+ for (String policyId : selectedPoliciesInUI) {
+ logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
+
+ //
+ // Get the current selection
+ String selectedItem = policyId;
+ //
+ assert (selectedItem != null);
+ // create the id of the target file
+ // Our standard for file naming is:
+ // <domain>.<filename>.<version>.xml
+ // since the file name usually has a ".xml", we need to strip
+ // that
+ // before adding the other parts
+ String name = selectedItem.replace(File.separator, ".");
+ String id = name;
+ if (id.endsWith(".xml")) {
+ id = id.replace(".xml", "");
+ id = id.substring(0, id.lastIndexOf("."));
+ }
+
+ // Default policy to be Root policy; user can change to deferred
+ // later
+
+ StdPDPPolicy selectedPolicy = null;
+ String dbCheckName = name;
+ if(dbCheckName.contains("Config_")){
+ dbCheckName = dbCheckName.replace(".Config_", ":Config_");
+ }else if(dbCheckName.contains("Action_")){
+ dbCheckName = dbCheckName.replace(".Action_", ":Action_");
+ }else if(dbCheckName.contains("Decision_")){
+ dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
+ }
+ PolicyController controller = new PolicyController();
+ String[] split = dbCheckName.split(":");
+ String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
+ System.out.println(query);
+ List<Object> queryData = controller.getDataByQuery(query);
+ PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
+ File temp = new File(name);
+ BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
+ bw.write(policyEntity.getPolicyData());
+ bw.close();
+ URI selectedURI = temp.toURI();
+ try {
+ //
+ // Create the policy
+ selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
+ } catch (IOException e) {
+ logger.error("Unable to create policy '" + name + "': "+ e.getMessage());
+ //AdminNotification.warn("Unable to create policy '" + id + "': " + e.getMessage());
+ }
+ StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
+ if (selectedPolicy != null) {
+ // Add Current policies from container
+ for (EcompPDPGroup group : container.getGroups()) {
+ if (group.getId().equals(selectedGroup.getId())) {
+ currentPoliciesInGroup.addAll(group.getPolicies());
+ }
+ }
+ // copy policy to PAP
+ try {
+ PolicyController.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
+ } catch (PAPException e) {
+ e.printStackTrace();
+ return null;
+ }
+ selectedPolicies.add(selectedPolicy);
+ }
+ temp.delete();
+ }
+ StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
+ StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
+ updatedGroupObject.setEcompPdps(pdpGroup.getEcompPdps());
+ updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
+ updatedGroupObject.setStatus(pdpGroup.getStatus());
+
+ // replace the original set of Policies with the set from the
+ // container (possibly modified by the user)
+ // do not allow multiple copies of same policy
+ Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
+ logger.debug("policyIterator....." + selectedPolicies);
+ while (policyIterator.hasNext()) {
+ PDPPolicy existingPolicy = policyIterator.next();
+ for (PDPPolicy selPolicy : selectedPolicies) {
+ if (selPolicy.getName().equals(existingPolicy.getName())) {
+ if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
+ if (selPolicy.getId().equals(existingPolicy.getId())) {
+ policyIterator.remove();
+ logger.debug("Removing policy: " + selPolicy);
+ break;
+ }
+ } else {
+ policyIterator.remove();
+ logger.debug("Removing Old Policy version: "+ selPolicy);
+ break;
+ }
+ }
+ }
+ }
+
+ currentPoliciesInGroup.addAll(selectedPolicies);
+ updatedGroupObject.setPolicies(currentPoliciesInGroup);
+ this.container.updateGroup(updatedGroupObject);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ refreshGroups();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ out.write(j.toString());
+ return null;
+ }
+ }
+ catch (Exception e){
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ try {
+ this.container = new PDPGroupContainer(PolicyController.getPapEngine());
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
+ JsonNode removePolicyData = root.get("data");
+ policyContainer = new PDPPolicyContainer(group);
+ if(removePolicyData.size() > 0){
+ for(int i = 0 ; i < removePolicyData.size(); i++){
+ String data = removePolicyData.get(i).toString();
+ AutoPushController.policyContainer.removeItem(data);
+ }
+ Set<PDPPolicy> changedPolicies = new HashSet<PDPPolicy>();
+ changedPolicies.addAll((Collection<PDPPolicy>) AutoPushController.policyContainer.getItemIds());
+ StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
+ updatedGroupObject.setPolicies(changedPolicies);
+ updatedGroupObject.setEcompPdps(group.getEcompPdps());
+ updatedGroupObject.setPipConfigs(group.getPipConfigs());
+ updatedGroupObject.setStatus(group.getStatus());
+ this.container.updateGroup(updatedGroupObject);
+ }
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ refreshGroups();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+
+ out.write(j.toString());
+
+ return null;
+ }
+ catch (Exception e){
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+
+} \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java
new file mode 100644
index 000000000..786e17a16
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java
@@ -0,0 +1,508 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.bind.JAXBElement;
+
+import org.json.JSONObject;
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.servlet.ModelAndView;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+
+@Controller
+@RequestMapping("/")
+public class CreateBRMSParamController extends RestrictedBaseController {
+ private static final Logger logger = FlexLogger.getLogger(CreateBRMSParamController.class);
+
+ private static CommonClassDao commonClassDao;
+
+ @Autowired
+ private CreateBRMSParamController(CommonClassDao commonClassDao){
+ CreateBRMSParamController.commonClassDao = commonClassDao;
+ }
+
+ public CreateBRMSParamController(){}
+ protected PolicyRestAdapter policyAdapter = null;
+ private ArrayList<Object> attributeList;
+
+ private HashMap<String, String> dynamicLayoutMap;
+
+
+ @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ dynamicLayoutMap = new HashMap<String, String>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ String rule = findRule(root.get("policyData").toString().replaceAll("^\"|\"$", ""));
+ generateUI(rule);
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(dynamicLayoutMap);
+ JSONObject j = new JSONObject("{policyData: " + responseString + "}");
+ out.write(j.toString());
+ return null;
+ }
+
+ protected String findRule(String ruleTemplate) {
+ List<Object> datas = commonClassDao.getData(BRMSParamTemplate.class);
+ for (Object data: datas){
+ BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) data;
+ if(bRMSParamTemplate.getRuleName().equals(ruleTemplate)){
+ return bRMSParamTemplate.getRule();
+ }
+ }
+ return null;
+ }
+
+ protected void generateUI(String rule) {
+ if(rule!=null){
+ try {
+ String params = "";
+ Boolean flag = false;
+ Boolean comment = false;
+ String lines[] = rule.split("\n");
+ for(String line : lines){
+ if (line.isEmpty() || line.startsWith("//")) {
+ continue;
+ }
+ if (line.startsWith("/*")) {
+ comment = true;
+ continue;
+ }
+ if (line.contains("//")) {
+ line = line.split("\\/\\/")[0];
+ }
+ if (line.contains("/*")) {
+ comment = true;
+ if (line.contains("*/")) {
+ try {
+ comment = false;
+ line = line.split("\\/\\*")[0]
+ + line.split("\\*\\/")[1].replace("*/", "");
+ } catch (Exception e) {
+ line = line.split("\\/\\*")[0];
+ }
+ } else {
+ line = line.split("\\/\\*")[0];
+ }
+ }
+ if (line.contains("*/")) {
+ comment = false;
+ try {
+ line = line.split("\\*\\/")[1].replace("*/", "");
+ } catch (Exception e) {
+ line = "";
+ }
+ }
+ if (comment) {
+ continue;
+ }
+ if (flag) {
+ params = params + line;
+ }
+ if (line.contains("declare Params")) {
+ params = params + line;
+ flag = true;
+ }
+ if (line.contains("end") && flag) {
+ break;
+ }
+ }
+ params = params.replace("declare Params", "").replace("end", "")
+ .replaceAll("\\s+", "");
+ String[] components = params.split(":");
+ String caption = "";
+ for (int i = 0; i < components.length; i++) {
+ String type = "";
+ if (i == 0) {
+ caption = components[i];
+ }
+ if(caption.equals("")){
+ break;
+ }
+ String nextComponent = "";
+ try {
+ nextComponent = components[i + 1];
+ } catch (Exception e) {
+ nextComponent = components[i];
+ }
+ if (nextComponent.startsWith("String")) {
+ type = "String";
+ createField(caption, type);
+ caption = nextComponent.replace("String", "");
+ } else if (nextComponent.startsWith("int")) {
+ type = "int";
+ createField(caption, type);
+ caption = nextComponent.replace("int", "");
+ }
+ }
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
+ }
+ }
+ }
+
+ private void createField(String caption, String type) {
+ dynamicLayoutMap.put(caption, type);
+ }
+
+
+ @SuppressWarnings("unchecked")
+ public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ attributeList = new ArrayList<Object>();
+ dynamicLayoutMap = new HashMap<String, String>();
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ // policy name value is the policy name without any prefix and
+ // Extensions.
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
+ if (logger.isDebugEnabled()) {
+ logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
+ }
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Set Attributes.
+ AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
+ for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
+ for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
+ if(attributeAssignment.getAttributeId().startsWith("key:")){
+ Map<String, String> attribute = new HashMap<String, String>();
+ String key = attributeAssignment.getAttributeId().replace("key:", "");
+ attribute.put("key", key);
+ JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
+ String value = (String) attributevalue.getValue().getContent().get(0);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){
+ ArrayList<String> dependencies = new ArrayList<String>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
+ if(dependencies.contains("")){
+ dependencies.remove("");
+ }
+ policyAdapter.setBrmsDependency(dependencies);
+ }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
+ policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
+ }
+ }
+ policyAdapter.setAttributes(attributeList);
+ }
+ paramUIGenerate(policyAdapter, entity);
+ // Get the target data under policy.
+ policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
+ if(policyAdapter.getDynamicLayoutMap().size() > 0){
+ LinkedHashMap<String,String> drlRule = new LinkedHashMap<String, String>();
+ for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
+ drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue).toString());
+ }
+ policyAdapter.setRuleData(drlRule);
+ }
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ int index = 0;
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attributevalue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+
+ if (index == 3){
+ policyAdapter.setRiskType(value);
+ }
+
+ if (index == 4){
+ policyAdapter.setRiskLevel(value);
+ }
+
+ if (index == 5){
+ policyAdapter.setGuard(value);
+ }
+ if (index == 6 && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+
+ index++;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private String convertDate(String dateTTL, boolean portalType) {
+ String formateDate = null;
+ String[] date;
+ String[] parts;
+
+ if (portalType){
+ parts = dateTTL.split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
+ } else {
+ date = dateTTL.split("T");
+ parts = date[0].split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
+ }
+ return formateDate;
+ }
+ // This method generates the UI from rule configuration
+ private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ String data = entity.getConfigurationData().getConfigBody();
+ if(data != null){
+ try {
+ String params = "";
+ Boolean flag = false;
+ Boolean comment = false;
+ for (String line : data.split("\n")) {
+ if (line.isEmpty() || line.startsWith("//")) {
+ continue;
+ }
+ if(line.contains("<$%BRMSParamTemplate=")){
+ String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
+ value = value.replace("<$%BRMSParamTemplate=", "");
+ policyAdapter.setRuleName(value);
+ }
+ if (line.startsWith("/*")) {
+ comment = true;
+ continue;
+ }
+ if (line.contains("//")) {
+ if(!(line.contains("http://") || line.contains("https://"))){
+ line = line.split("\\/\\/")[0];
+ }
+ }
+ if (line.contains("/*")) {
+ comment = true;
+ if (line.contains("*/")) {
+ try {
+ comment = false;
+ line = line.split("\\/\\*")[0]
+ + line.split("\\*\\/")[1].replace(
+ "*/", "");
+ } catch (Exception e) {
+ line = line.split("\\/\\*")[0];
+ }
+ } else {
+ line = line.split("\\/\\*")[0];
+ }
+ }
+ if (line.contains("*/")) {
+ comment = false;
+ try {
+ line = line.split("\\*\\/")[1]
+ .replace("*/", "");
+ } catch (Exception e) {
+ line = "";
+ }
+ }
+ if (comment) {
+ continue;
+ }
+ if (flag) {
+ params = params + line;
+ }
+ if (line.contains("rule") && line.contains(".Params\"")) {
+ params = params + line;
+ flag = true;
+ }
+ if (line.contains("end") && flag) {
+ break;
+ }
+ }
+ params = params.substring(params.indexOf(".Params\"")+ 8);
+ params = params.replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
+ .replace("insert(params);end", "")
+ .replace("params.set", "");
+ String[] components = params.split(";");
+ if(components!= null && components.length > 0){
+ for (int i = 0; i < components.length; i++) {
+ String value = null;
+ String caption = components[i].substring(0,
+ components[i].indexOf("("));
+ caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
+ if (components[i].contains("(\"")) {
+ value = components[i]
+ .substring(components[i].indexOf("(\""),
+ components[i].indexOf("\")"))
+ .replace("(\"", "").replace("\")", "");
+ } else {
+ value = components[i]
+ .substring(components[i].indexOf("("),
+ components[i].indexOf(")"))
+ .replace("(", "").replace(")", "");
+ }
+ dynamicLayoutMap.put(caption, value);
+
+ }
+ }
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage());
+ }
+ }
+
+ }
+
+ // set View Rule
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView setViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ 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;
+ }
+
+ String body = "";
+
+ body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
+ "<$%BRMSParamTemplate=" + policyData.getRuleName() + "%$> \n */ \n";
+ body = body + findRule((String) policyData.getRuleName()) + "\n";
+ String generatedRule = "rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();";
+
+ if(policyData.getRuleData().size() > 0){
+ for(Object keyValue: policyData.getRuleData().keySet()){
+ String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1);
+ if (keyValue.equals("String")) {
+ generatedRule = generatedRule + "\n\t\tparams.set"
+ + key + "(\""
+ + policyData.getRuleData().get(keyValue).toString() + "\");";
+ } else {
+ generatedRule = generatedRule + "\n\t\tparams.set"
+ + key + "("
+ + policyData.getRuleData().get(keyValue).toString() + ");";
+ }
+ }
+ }
+ generatedRule = generatedRule
+ + "\n\t\tinsert(params);\nend";
+ logger.info("New rule generated with :" + generatedRule);
+ body = body + generatedRule;
+ // Expand the body.
+ Map<String,String> copyMap=new HashMap<>();
+ copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
+ copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName());
+ copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
+ copyMap.put("policyVersion", "1");
+ //Finding all the keys in the Map data-structure.
+ Set<String> keySet= copyMap.keySet();
+ Iterator<String> iterator = keySet.iterator();
+ Pattern p;
+ Matcher m;
+ while(iterator.hasNext()) {
+ //Converting the first character of the key into a lower case.
+ String input= iterator.next();
+ String output = Character.toLowerCase(input.charAt(0)) +
+ (input.length() > 1 ? input.substring(1) : "");
+ //Searching for a pattern in the String using the key.
+ p=Pattern.compile("\\$\\{"+output+"\\}");
+ m=p.matcher(body);
+ //Replacing the value with the inputs provided by the user in the editor.
+ body=m.replaceAll(copyMap.get(input));
+ }
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(body);
+ JSONObject j = new JSONObject("{policyData: " + responseString + "}");
+ out.write(j.toString());
+ return null;
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ }
+ return null;
+ }
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java
new file mode 100644
index 000000000..381673ca5
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java
@@ -0,0 +1,173 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.bind.JAXBElement;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+import 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.jpa.PolicyEntity;
+
+public class CreateBRMSRawController{
+
+ private static final Logger logger = FlexLogger.getLogger(CreateBRMSRawController.class);
+
+ protected PolicyRestAdapter policyAdapter = null;
+ private ArrayList<Object> attributeList;
+
+
+ @SuppressWarnings("unchecked")
+ public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ attributeList = new ArrayList<Object>();
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ // policy name value is the policy name without any prefix and
+ // Extensions.
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9);
+ if (logger.isDebugEnabled()) {
+ logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
+ }
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Set Attributes.
+ AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
+ for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
+ for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
+ if(attributeAssignment.getAttributeId().startsWith("key:")){
+ Map<String, String> attribute = new HashMap<String, String>();
+ String key = attributeAssignment.getAttributeId().replace("key:", "");
+ attribute.put("key", key);
+ JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
+ String value = (String) attributevalue.getValue().getContent().get(0);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){
+ ArrayList<String> dependencies = new ArrayList<String>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
+ if(dependencies.contains("")){
+ dependencies.remove("");
+ }
+ policyAdapter.setBrmsDependency(dependencies);
+ }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
+ policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
+ }
+ }
+ policyAdapter.setAttributes(attributeList);
+ }
+ // Get the target data under policy.
+ policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ int index = 0;
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attributevalue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+
+ if (index == 3){
+ policyAdapter.setRiskType(value);
+ }
+
+ if (index == 4){
+ policyAdapter.setRiskLevel(value);
+ }
+
+ if (index == 5){
+ policyAdapter.setGuard(value);
+ }
+ if (index == 6 && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+
+ index++;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private String convertDate(String dateTTL, boolean portalType) {
+ String formateDate = null;
+ String[] date;
+ String[] parts;
+
+ if (portalType){
+ parts = dateTTL.split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
+ } else {
+ date = dateTTL.split("T");
+ parts = date[0].split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
+ }
+ return formateDate;
+ }
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java
new file mode 100644
index 000000000..d75231ef0
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java
@@ -0,0 +1,696 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.policy.rest.adapter.ClosedLoopFaultBody;
+import org.openecomp.policy.rest.adapter.ClosedLoopFaultTriggerUISignatures;
+import org.openecomp.policy.rest.adapter.ClosedLoopSignatures;
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.EcompName;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.policy.rest.jpa.VarbindDictionary;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectWriter;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+@Controller
+@RequestMapping("/")
+public class CreateClosedLoopFaultController extends RestrictedBaseController{
+
+ protected PolicyRestAdapter policyAdapter = null;
+
+
+ private static CommonClassDao commonclassdao;
+
+ @Autowired
+ private CreateClosedLoopFaultController(CommonClassDao commonclassdao){
+ CreateClosedLoopFaultController.commonclassdao = commonclassdao;
+ }
+
+ public CreateClosedLoopFaultController(){}
+
+ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) throws Exception{
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ TrapDatas trapDatas = mapper.readValue(root.get("trapData").toString(), TrapDatas.class);
+ TrapDatas faultDatas = mapper.readValue(root.get("faultData").toString(), TrapDatas.class);
+ ClosedLoopGridJSONData policyJsonData = mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class);
+ ClosedLoopFaultBody jsonBody = mapper.readValue(root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
+
+ ArrayList<Object> trapSignatureDatas = new ArrayList<Object>();
+ if(trapDatas.getTrap1() != null){
+ trapSignatureDatas.add(trapDatas);
+ }
+ ArrayList<Object> faultSignatureDatas = new ArrayList<Object>();
+ if(faultDatas.getTrap1() != null){
+ faultSignatureDatas.add(faultDatas);
+ }
+
+ String resultBody = "";
+ if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){
+ resultBody = resultBody + "(";
+ for(int i = policyJsonData.getConnecttriggerSignatures().size()-1; i>=0 ; i--){
+ String connectBody = connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(), trapSignatureDatas.get(0));
+ resultBody = resultBody + connectBody;
+ }
+ resultBody = resultBody + ")";
+ }else{
+ if(!trapSignatureDatas.isEmpty()){
+ resultBody = callTrap("nill", trapSignatureDatas.get(0));
+ }
+ }
+ ClosedLoopSignatures triggerSignatures = new ClosedLoopSignatures();
+ triggerSignatures.setSignatures(resultBody);
+ if(policyData.getClearTimeOut() != null){
+ triggerSignatures.setTimeWindow(Integer.parseInt(policyData.getClearTimeOut()));
+ triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge()));
+ ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures();
+ if(!trapSignatureDatas.isEmpty()){
+ uiTriggerSignatures.setSignatures(getUITriggerSignature("Trap", trapSignatureDatas.get(0)));
+ if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){
+ uiTriggerSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures()));
+ }
+ }
+ jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures);
+ jsonBody.setTriggerTimeWindowUsedForUI(Integer.parseInt(policyData.getClearTimeOut()));
+ jsonBody.setTrapMaxAgeUsedForUI(Integer.parseInt(policyData.getTrapMaxAge()));
+ }
+
+ jsonBody.setTriggerSignatures(triggerSignatures);
+ String faultBody = "";
+ if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){
+ faultBody = faultBody + "(";
+ for(int i = policyJsonData.getConnectVerificationSignatures().size()-1; i>=0 ; i--){
+ String connectBody = connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(), faultSignatureDatas.get(0));
+ faultBody = faultBody + connectBody;
+ }
+ faultBody = faultBody + ")";
+ }else{
+ if(!faultSignatureDatas.isEmpty()){
+ faultBody = callTrap("nill", faultSignatureDatas.get(0));
+ }
+ }
+ ClosedLoopSignatures faultSignatures = new ClosedLoopSignatures();
+ faultSignatures.setSignatures(faultBody);
+ if(policyData.getVerificationclearTimeOut() != null){
+ faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut()));
+ ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures();
+ if(!faultSignatureDatas.isEmpty()){
+ uifaultSignatures.setSignatures(getUITriggerSignature("Fault", faultSignatureDatas.get(0)));
+ if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){
+ uifaultSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnectVerificationSignatures()));
+ }
+ }
+
+ jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures);
+ jsonBody.setVerfificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut()));
+ }
+ jsonBody.setVerificationSignatures(faultSignatures);
+ ObjectWriter om = new ObjectMapper().writer();
+ String json = om.writeValueAsString(jsonBody);
+ policyData.setJsonBody(json);
+ return policyData;
+ }
+
+
+ @SuppressWarnings("unchecked")
+ private String connectTriggerSignature(int index, ArrayList<Object> triggerSignatures, Object object) {
+ String resultBody = "";
+ Map<String, String> connectTraps = (Map<String, String>) triggerSignatures.get(index);
+ try{
+ String notBox = "";
+ if(connectTraps.keySet().contains("notBox")){
+ notBox = connectTraps.get("notBox");
+ }
+ resultBody = resultBody + "(" + notBox;
+ }catch(NullPointerException e){
+ resultBody = resultBody + "(";
+ }
+ String connectTrap1 = connectTraps.get("connectTrap1");
+ if(connectTrap1.startsWith("Trap") || connectTrap1.startsWith("Fault")){
+ String trapBody = callTrap(connectTrap1, object);
+ if(trapBody!=null){
+ resultBody = resultBody + trapBody;
+ }
+ }else if(connectTrap1.startsWith("C")){
+ for(int i=0; i<= triggerSignatures.size(); i++){
+ Map<String,String> triggerSignature = (Map<String, String>) triggerSignatures.get(i);
+ if(triggerSignature.get("id").equals(connectTrap1)){
+ resultBody = resultBody + "(";
+ String connectBody = connectTriggerSignature(i, triggerSignatures, object);
+ resultBody = resultBody + connectBody + ")";
+ }else{
+ i++;
+ }
+ }
+ }
+ try{
+ String trapCount1 = connectTraps.get("trapCount1");
+ resultBody = resultBody + ", Time = " + trapCount1 + ")";
+ }catch(NullPointerException e){
+ }
+ try{
+ String operatorBox = connectTraps.get("operatorBox");
+ resultBody = resultBody + operatorBox +"(";
+ }catch (NullPointerException e){
+ }
+ try{
+ String connectTrap2 = connectTraps.get("connectTrap2");
+ if(connectTrap2.startsWith("Trap") || connectTrap2.startsWith("Fault")){
+ String trapBody = callTrap(connectTrap2, object);
+ if(trapBody!=null){
+ resultBody = resultBody + trapBody;
+ }
+ }else if(connectTrap2.startsWith("C")){
+ for(int i=0; i<= triggerSignatures.size(); i++){
+ Map<String,String> triggerSignature = (Map<String, String>) triggerSignatures.get(i);
+ if(triggerSignature.get("id").equals(connectTrap2)){
+ resultBody = resultBody + "(";
+ String connectBody = connectTriggerSignature(i, triggerSignatures, object);
+ resultBody = resultBody + connectBody + ")";
+ }else{
+ i++;
+ }
+ }
+ }
+ }catch(NullPointerException e){
+ }
+ try{
+ String trapCount2 = connectTraps.get("trapCount2");
+ resultBody = resultBody + ", Time = " + trapCount2 + ")";
+ }catch(NullPointerException e){
+ }
+ return resultBody;
+ }
+
+
+ private String callTrap(String trap, Object object) {
+ String signatureBody = "";
+ TrapDatas trapDatas = (TrapDatas) object;
+ ArrayList<Object> attributeList = new ArrayList<>();
+ // Read the Trap
+ if(!trap.equals("nill")){
+ try{
+ if(trap.startsWith("Trap")){
+ if(trap.equals("Trap1")){
+ attributeList = trapDatas.getTrap1();
+ }else if(trap.equals("Trap2")){
+ attributeList = trapDatas.getTrap2();
+ }else if(trap.equals("Trap3")){
+ attributeList = trapDatas.getTrap3();
+ }else if(trap.equals("Trap4")){
+ attributeList = trapDatas.getTrap4();
+ }else if(trap.equals("Trap5")){
+ attributeList = trapDatas.getTrap5();
+ }else if(trap.equals("Trap6")){
+ attributeList = trapDatas.getTrap6();
+ }
+ }else{
+ if(trap.startsWith("Fault")){
+ if(trap.equals("Fault1")){
+ attributeList = trapDatas.getTrap1();
+ }else if(trap.equals("Fault2")){
+ attributeList = trapDatas.getTrap2();
+ }else if(trap.equals("Fault3")){
+ attributeList = trapDatas.getTrap3();
+ }else if(trap.equals("Fault4")){
+ attributeList = trapDatas.getTrap4();
+ }else if(trap.equals("Fault5")){
+ attributeList = trapDatas.getTrap5();
+ }else if(trap.equals("Fault6")){
+ attributeList = trapDatas.getTrap6();
+ }
+ }
+ }
+ } catch(Exception e){
+ return "(" + trap + ")";
+ }
+ }else{
+ if(trapDatas.getTrap1()!=null){
+ attributeList = trapDatas.getTrap1();
+ }else{
+ return "";
+ }
+ }
+ signatureBody = signatureBody + "(" + readAttributes(attributeList, attributeList.size()-1) + ")";
+ return signatureBody;
+ }
+
+ @SuppressWarnings("unchecked")
+ private String readAttributes(ArrayList<Object> object, int index) {
+ String attributes = "";
+ Map<String, String> trapSignatures = (Map<String, String>) object.get(index);
+ // Read the Elements.
+ Object notBox = "";
+ if(trapSignatures.keySet().contains("notBox")){
+ notBox = trapSignatures.get("notBox");
+ }
+ if(notBox!=null){
+ attributes = attributes + notBox.toString();
+ }
+ Object trapName1 = trapSignatures.get("trigger1");
+ if(trapName1!=null){
+ String attrib = trapName1.toString();
+ if(attrib.startsWith("A")){
+ try{
+ int iy = Integer.parseInt(attrib.substring(1))-1;
+ attributes = attributes + "(" + readAttributes(object, iy) + ")";
+ }catch(NumberFormatException e){
+ try {
+ attrib = getVarbindOID(attrib);
+ attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")";
+ } catch (UnsupportedEncodingException e1) {
+ //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1);
+ }
+ }
+ }else{
+ try {
+ attrib = getVarbindOID(attrib);
+ attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")";
+ } catch (UnsupportedEncodingException e) {
+ //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e);
+ }
+ }
+ }else{
+ return "";
+ }
+ Object comboBox = trapSignatures.get("operatorBox");
+ if(comboBox!=null){
+ attributes = attributes + comboBox.toString();
+ }else{
+ return attributes;
+ }
+ Object trapName2 = trapSignatures.get("trigger2");
+ if(trapName2!=null){
+ String attrib = trapName2.toString();
+ if(attrib.startsWith("A")){
+ try{
+ int iy = Integer.parseInt(attrib.substring(1))-1;
+ attributes = attributes + "(" + readAttributes(object, iy) + ")";
+ }catch(NumberFormatException e){
+ try {
+ attrib = getVarbindOID(attrib);
+ attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")";
+ } catch (UnsupportedEncodingException e1) {
+ //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1);
+ }
+ }
+ }else{
+ try {
+ attrib = getVarbindOID(attrib);
+ attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")";
+ } catch (UnsupportedEncodingException e) {
+ //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e);
+ }
+ }
+ }
+ return attributes;
+ }
+
+ private String getVarbindOID(String attrib) {
+ VarbindDictionary varbindId = null;
+ try{
+ varbindId = (VarbindDictionary) commonclassdao.getEntityItem(VarbindDictionary.class, "varbindName", attrib);
+ return varbindId.getVarbindOID();
+ }catch(Exception e){
+ return attrib;
+ }
+ }
+
+
+ //connect traps data set to JSON Body as String
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ private String getUIConnectTraps(ArrayList<Object> connectTrapSignatures) {
+ String resultBody = "";
+ String connectMainBody = "";
+ for(int j = 0; j < connectTrapSignatures.size(); j++){
+ Map<String, String> connectTraps = (Map<String, String>)connectTrapSignatures.get(j);
+ String connectBody = "";
+ Object object = connectTraps;
+ if(object instanceof LinkedHashMap<?, ?>){
+ String notBox = "";
+ String connectTrap1 = "";
+ String trapCount1 = "";
+ String operatorBox = "";
+ String connectTrap2 = "";
+ String trapCount2 = "";
+ if(((LinkedHashMap) object).keySet().contains("notBox")){
+ notBox = ((LinkedHashMap) object).get("notBox").toString();
+ }
+ if(((LinkedHashMap) object).get("connectTrap1") != null){
+ connectTrap1 = ((LinkedHashMap) object).get("connectTrap1").toString();
+ }
+ if(((LinkedHashMap) object).get("trapCount1") != null){
+ trapCount1 = ((LinkedHashMap) object).get("trapCount1").toString();
+ }
+ if(((LinkedHashMap) object).get("operatorBox") != null){
+ operatorBox = ((LinkedHashMap) object).get("operatorBox").toString();
+ }
+ if(((LinkedHashMap) object).get("connectTrap2") != null){
+ connectTrap2 = ((LinkedHashMap) object).get("connectTrap2").toString();
+ }
+ if(((LinkedHashMap) object).get("trapCount2") != null){
+ trapCount2 = ((LinkedHashMap) object).get("trapCount2").toString();
+ }
+ connectBody = notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!" + connectTrap2 + "@!" + trapCount2 + "#!?!";
+ }
+ resultBody = resultBody + connectBody;
+ }
+ connectMainBody = connectMainBody + resultBody;
+ return connectMainBody;
+ }
+
+
+
+ // get Trigger signature from JSON body
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private String getUITriggerSignature(String trap, Object object2) {
+ String triggerBody = "";
+ TrapDatas trapDatas = (TrapDatas) object2;
+ ArrayList<Object> attributeList = new ArrayList<>();
+ // Read the Trap
+ if(trap.startsWith("Trap")){
+ if(trapDatas.getTrap1()!= null){
+ attributeList.add(trapDatas.getTrap1());
+ }
+ if(trapDatas.getTrap2()!= null){
+ attributeList.add(trapDatas.getTrap2());
+ }
+ if(trapDatas.getTrap3()!= null){
+ attributeList.add(trapDatas.getTrap3());
+ }
+ if(trapDatas.getTrap4()!= null){
+ attributeList.add(trapDatas.getTrap4());
+ }
+ if(trapDatas.getTrap5()!= null){
+ attributeList.add(trapDatas.getTrap5());
+ }
+ if(trapDatas.getTrap6()!= null){
+ attributeList.add(trapDatas.getTrap6());
+ }
+ }else{
+ if(trap.startsWith("Fault")){
+ if(trapDatas.getTrap1()!= null){
+ attributeList.add(trapDatas.getTrap1());
+ }
+ if(trapDatas.getTrap2()!= null){
+ attributeList.add(trapDatas.getTrap2());
+ }
+ if(trapDatas.getTrap3()!= null){
+ attributeList.add(trapDatas.getTrap3());
+ }
+ if(trapDatas.getTrap4()!= null){
+ attributeList.add(trapDatas.getTrap4());
+ }
+ if(trapDatas.getTrap5()!= null){
+ attributeList.add(trapDatas.getTrap5());
+ }
+ if(trapDatas.getTrap6()!= null){
+ attributeList.add(trapDatas.getTrap6());
+ }
+ }
+ }
+
+ for(int j = 0; j < attributeList.size(); j++){
+ String signatureBody = "";
+ ArrayList<Object> connectTraps = (ArrayList<Object>) attributeList.get(j);
+ for(int i =0 ; i < connectTraps.size(); i++){
+ String connectBody = "";
+ Object object = connectTraps.get(i);
+ if(object instanceof LinkedHashMap<?, ?>){
+ String notBox = "";
+ String trigger1 = "";
+ String operatorBox = "";
+ String trigger2 = "";
+ if(((LinkedHashMap) object).keySet().contains("notBox")){
+ notBox = ((LinkedHashMap) object).get("notBox").toString();
+ }
+ if(((LinkedHashMap) object).get("trigger1") != null){
+ trigger1 = ((LinkedHashMap) object).get("trigger1").toString();
+ }
+ if(((LinkedHashMap) object).get("operatorBox") != null){
+ operatorBox = ((LinkedHashMap) object).get("operatorBox").toString();
+ }
+ if(((LinkedHashMap) object).get("trigger2") != null){
+ trigger2 = ((LinkedHashMap) object).get("trigger2").toString();
+ }
+ connectBody = notBox + "@!" + trigger1 + "@!" + operatorBox + "@!" + trigger2 + "#!";
+ }
+ signatureBody = signatureBody + connectBody;
+ }
+ triggerBody = triggerBody + signatureBody + "?!";
+ }
+
+ return triggerBody;
+ }
+
+ public void prePopulateClosedLoopFaultPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("Fault_") +6);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ int index = 0;
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attributevalue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+
+ // First match in the target is EcompName, so set that value.
+ if (index == 1) {
+ policyAdapter.setEcompName(value);
+ EcompName ecompName = new EcompName();
+ ecompName.setEcompName(value);
+ policyAdapter.setEcompNameField(ecompName);
+ }
+ if (index == 2){
+ policyAdapter.setRiskType(value);
+ }
+
+ if (index == 3){
+ policyAdapter.setRiskLevel(value);
+ }
+
+ if (index == 4){
+ policyAdapter.setGuard(value);
+ }
+ if (index == 5 && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ index++;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ readClosedLoopJSONFile(policyAdapter, entity);
+ }
+
+ }
+
+ private String convertDate(String dateTTL, boolean portalType) {
+ String formateDate = null;
+ String[] date;
+ String[] parts;
+
+ if (portalType){
+ parts = dateTTL.split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
+ } else {
+ date = dateTTL.split("T");
+ parts = date[0].split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
+ }
+ return formateDate;
+ }
+
+ private String readClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ ClosedLoopFaultBody closedLoopBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class);
+ if(closedLoopBody.getClosedLoopPolicyStatus().equalsIgnoreCase("ACTIVE")){
+ closedLoopBody.setClosedLoopPolicyStatus("Active");
+ }else{
+ closedLoopBody.setClosedLoopPolicyStatus("InActive");
+ }
+ policyAdapter.setJsonBodyData(closedLoopBody);
+ if(closedLoopBody.getTrapMaxAgeUsedForUI() != null){
+ policyAdapter.setTrapMaxAge(closedLoopBody.getTrapMaxAgeUsedForUI().toString());
+ }
+ if(closedLoopBody.getTriggerTimeWindowUsedForUI() != null){
+ policyAdapter.setClearTimeOut(closedLoopBody.getTriggerTimeWindowUsedForUI().toString());
+ }
+ if(closedLoopBody.getVerfificationTimeWindowUsedForUI() != null){
+ policyAdapter.setVerificationclearTimeOut(closedLoopBody.getVerfificationTimeWindowUsedForUI().toString());
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+
+}
+
+class TrapDatas{
+ private ArrayList<Object> trap1;
+ private ArrayList<Object> trap2;
+ private ArrayList<Object> trap3;
+ private ArrayList<Object> trap4;
+ private ArrayList<Object> trap5;
+ private ArrayList<Object> trap6;
+ public ArrayList<Object> getTrap1() {
+ return trap1;
+ }
+ public void setTrap1(ArrayList<Object> trap1) {
+ this.trap1 = trap1;
+ }
+ public ArrayList<Object> getTrap2() {
+ return trap2;
+ }
+ public void setTrap2(ArrayList<Object> trap2) {
+ this.trap2 = trap2;
+ }
+ public ArrayList<Object> getTrap3() {
+ return trap3;
+ }
+ public void setTrap3(ArrayList<Object> trap3) {
+ this.trap3 = trap3;
+ }
+ public ArrayList<Object> getTrap4() {
+ return trap4;
+ }
+ public void setTrap4(ArrayList<Object> trap4) {
+ this.trap4 = trap4;
+ }
+ public ArrayList<Object> getTrap5() {
+ return trap5;
+ }
+ public void setTrap5(ArrayList<Object> trap5) {
+ this.trap5 = trap5;
+ }
+ public ArrayList<Object> getTrap6() {
+ return trap6;
+ }
+ public void setTrap6(ArrayList<Object> trap6) {
+ this.trap6 = trap6;
+ }
+}
+
+class ClosedLoopGridJSONData{
+
+ private String clearTimeOut;
+ private String trapMaxAge;
+ private String verificationclearTimeOut;
+ private ArrayList<Object> connecttriggerSignatures;
+ private ArrayList<Object> connectVerificationSignatures;
+
+ public String getClearTimeOut() {
+ return clearTimeOut;
+ }
+ public void setClearTimeOut(String clearTimeOut) {
+ this.clearTimeOut = clearTimeOut;
+ }
+ public String getTrapMaxAge() {
+ return trapMaxAge;
+ }
+ public void setTrapMaxAge(String trapMaxAge) {
+ this.trapMaxAge = trapMaxAge;
+ }
+ public String getVerificationclearTimeOut() {
+ return verificationclearTimeOut;
+ }
+ public void setVerificationclearTimeOut(String verificationclearTimeOut) {
+ this.verificationclearTimeOut = verificationclearTimeOut;
+ }
+
+
+ public ArrayList<Object> getConnecttriggerSignatures() {
+ return connecttriggerSignatures;
+ }
+ public void setConnecttriggerSignatures(ArrayList<Object> connecttriggerSignatures) {
+ this.connecttriggerSignatures = connecttriggerSignatures;
+ }
+ public ArrayList<Object> getConnectVerificationSignatures() {
+ return connectVerificationSignatures;
+ }
+ public void setConnectVerificationSignatures(ArrayList<Object> connectVerificationSignatures) {
+ this.connectVerificationSignatures = connectVerificationSignatures;
+ }
+} \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java
new file mode 100644
index 000000000..375866aa8
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java
@@ -0,0 +1,206 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+
+import javax.json.JsonArray;
+import javax.json.JsonObject;
+
+import org.openecomp.policy.admin.PolicyManagerServlet;
+import org.openecomp.policy.rest.adapter.ClosedLoopPMBody;
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+public class CreateClosedLoopPMController{
+
+ protected PolicyRestAdapter policyAdapter = null;
+
+ public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") +3);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ int index = 0;
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (matchList.size()>1 && iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attributevalue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+
+ // First match in the target is EcompName, so set that value.
+ if (index == 0) {
+ policyAdapter.setEcompName(value);
+ }
+
+ if (index == 1){
+ policyAdapter.setRiskType(value);
+ }
+
+ if (index == 2){
+ policyAdapter.setRiskLevel(value);
+ }
+
+ if (index == 3){
+ policyAdapter.setGuard(value);
+ }
+
+ if (index == 4 && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ if (index == 5){
+ LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>();
+ String key = "serviceTypePolicyName";
+ serviceTypePolicyName1.put(key, value);
+ policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1);
+ LinkedHashMap<String, String> vertica = new LinkedHashMap<>();
+ vertica.put("verticaMetrics", getVertica(value));
+ policyAdapter.setVerticaMetrics(vertica);
+ LinkedHashMap<String, String> desc = new LinkedHashMap<>();
+ desc.put("policyDescription", getDescription(value));
+ policyAdapter.setDescription(desc);
+ LinkedHashMap<String, Object> attributes = new LinkedHashMap<>();
+ attributes.put("attributes", getAttributes(value));
+ policyAdapter.setAttributeFields(attributes);
+ }
+ index++;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ readClosedLoopJSONFile(policyAdapter, entity);
+ }
+ }
+
+ private String convertDate(String dateTTL, boolean portalType) {
+ String formateDate = null;
+ String[] date;
+ String[] parts;
+
+ if (portalType){
+ parts = dateTTL.split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
+ } else {
+ date = dateTTL.split("T");
+ parts = date[0].split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
+ }
+ return formateDate;
+ }
+
+ protected void readClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ ClosedLoopPMBody closedLoopBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
+ policyAdapter.setJsonBodyData(closedLoopBody);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ //get vertica metrics data from the table
+ private String getVertica(String policyName){
+ String verticas = null;
+ JsonArray data = PolicyManagerServlet.getPolicyNames();
+ for(int i=0 ; i< data.size(); i++){
+ if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){
+ verticas = data.getJsonObject(i).getJsonString("verticaMetrics").getString();
+ return verticas;
+ }
+ }
+ return verticas;
+ }
+
+ //get policy description from the table
+ private String getDescription(String policyName){
+ String description = null;
+ JsonArray data = PolicyManagerServlet.getPolicyNames();
+ for(int i=0 ; i< data.size(); i++){
+ if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){
+ description = data.getJsonObject(i).getJsonString("policyDescription").getString();
+ return description;
+ }
+ }
+ return description;
+ }
+
+ //get Attributes
+ private JsonObject getAttributes(String policyName){
+ JsonObject attributes = null;
+ JsonArray data = PolicyManagerServlet.getPolicyNames();
+ for(int i=0 ; i< data.size(); i++){
+ if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){
+ attributes = data.getJsonObject(i).getJsonObject("attributes");
+ return attributes;
+ }
+ }
+ return attributes;
+ }
+
+}
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
new file mode 100644
index 000000000..570ceac31
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java
@@ -0,0 +1,1139 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.compress.utils.IOUtils;
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang.StringUtils;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.GroupPolicyScopeList;
+import org.openecomp.policy.rest.jpa.MicroServiceModels;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.policy.rest.util.MSAttributeObject;
+import org.openecomp.policy.rest.util.MSModelUtils;
+import org.openecomp.policy.rest.util.MSModelUtils.MODEL_TYPE;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectWriter;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.gson.Gson;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+@Controller
+@RequestMapping("/")
+public class CreateDcaeMicroServiceController extends RestrictedBaseController {
+ private static final Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
+
+ private static CommonClassDao commonClassDao;
+ private MicroServiceModels newModel;
+ private String newFile;
+ private String directory;
+ private List<String> modelList = new ArrayList<String>();
+ private List<String> dirDependencyList = new ArrayList<String>();
+ private HashMap<String,MSAttributeObject > classMap = new HashMap<String,MSAttributeObject>();
+
+ @Autowired
+ private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){
+ CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
+ }
+
+ public CreateDcaeMicroServiceController(){}
+
+ protected PolicyRestAdapter policyAdapter = null;
+ private int priorityCount;
+ private Map<String, String> attributesListRefMap = new HashMap<String, String>();
+ private Map<String, LinkedList<String>> arrayTextList = new HashMap<String, LinkedList<String>>();
+
+ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
+
+ String jsonContent = null;
+ try{
+ jsonContent = decodeContent(root.get("policyJSON")).toString();
+ constructJson(policyData, jsonContent);
+ }catch(Exception e){
+ logger.error("Error while decoding microservice content");
+ }
+
+ return policyData;
+ }
+
+ private GroupPolicyScopeList getPolicyObject(String policyScope) {
+ GroupPolicyScopeList groupList= (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
+ return groupList;
+ }
+
+ private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent) {
+ ObjectWriter om = new ObjectMapper().writer();
+ String json="";
+ DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
+ MicroServiceModels returnModel = new MicroServiceModels();
+ microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
+ if(policyAdapter.getServiceType() !=null){
+ microServiceObject.setService(policyAdapter.getServiceType());
+ microServiceObject.setVersion(policyAdapter.getVersion());
+ returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
+ }
+ if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){
+ if(policyAdapter.getUuid()!=null){
+ microServiceObject.setUuid(policyAdapter.getUuid());
+ }
+ if(policyAdapter.getLocation()!=null){
+ microServiceObject.setLocation(policyAdapter.getLocation());
+ }
+ if(policyAdapter.getConfigName()!=null){
+ microServiceObject.setConfigName(policyAdapter.getConfigName());
+ }
+ GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
+ if(policyScopeValue!=null){
+ microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
+ }
+ }
+
+ if(policyAdapter.getPolicyName()!=null){
+ microServiceObject.setPolicyName(policyAdapter.getPolicyName());
+ }
+ if(policyAdapter.getPolicyDescription()!=null){
+ microServiceObject.setDescription(policyAdapter.getPolicyDescription());
+ }
+ if (policyAdapter.getPriority()!=null){
+ microServiceObject.setPriority(policyAdapter.getPriority());
+ }else {
+ microServiceObject.setPriority("9999");
+ }
+
+ if (policyAdapter.getRiskLevel()!=null){
+ microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
+ }
+ if (policyAdapter.getRiskType()!=null){
+ microServiceObject.setRiskType(policyAdapter.getRiskType());
+ }
+ if (policyAdapter.getGuard()!=null){
+ microServiceObject.setGuard(policyAdapter.getGuard());
+ }
+ microServiceObject.setContent(jsonContent);
+
+ try {
+ json = om.writeValueAsString(microServiceObject);
+ } catch (JsonProcessingException e) {
+ logger.error("Error writing out the object");
+ }
+ System.out.println(json);
+ String cleanJson = cleanUPJson(json);
+ cleanJson = removeNullAttributes(cleanJson);
+ policyAdapter.setJsonBody(cleanJson);
+ return policyAdapter;
+ }
+
+ private String removeNullAttributes(String cleanJson) {
+ ObjectMapper mapper = new ObjectMapper();
+
+ try {
+ JsonNode rootNode = mapper.readTree(cleanJson);
+ JsonNode returnNode = mapper.readTree(cleanJson);
+ Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
+ boolean remove = false;
+ while (fieldsIterator.hasNext()) {
+ Map.Entry<String, JsonNode> field = fieldsIterator.next();
+ final String key = field.getKey();
+ final JsonNode value = field.getValue();
+ if (value==null || value.isNull()){
+ ((ObjectNode) returnNode).remove(key);
+ remove = true;
+ }
+ }
+ if (remove){
+ cleanJson = returnNode.toString();
+ }
+ } catch (IOException e) {
+ logger.error("Error writing out the JsonNode");
+ }
+ return cleanJson;
+ }
+
+
+ private String cleanUPJson(String json) {
+ String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
+
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
+ return cleanJson;
+ }
+
+ private JSONObject decodeContent(JsonNode jsonNode){
+ Iterator<JsonNode> jsonElements = jsonNode.elements();
+ Iterator<String> jsonKeys = jsonNode.fieldNames();
+ Map<String,String> element = new TreeMap<String,String>();
+ while(jsonElements.hasNext() && jsonKeys.hasNext()){
+ element.put(jsonKeys.next(), jsonElements.next().toString());
+ }
+ JSONObject jsonResult = new JSONObject();
+ JSONArray jsonArray = null;
+ String oldValue = null;
+ String nodeKey = null;
+ String arryKey = null;
+ Boolean isArray = false;
+ JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
+ ObjectNode node = nodeFactory.objectNode();
+ String prevKey = null;
+ String presKey = null;
+ for(String key: element.keySet()){
+ if(key.contains(".")){
+ presKey = key.substring(0,key.indexOf("."));
+ }else if(key.contains("@")){
+ presKey = key.substring(0,key.indexOf("@"));
+ }else{
+ presKey = key;
+ }
+ // first check if we are different from old.
+ System.out.println(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);
+ jsonArray = new JSONArray();
+ }
+ }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){
+ jsonResult.put(oldValue, jsonArray);
+ isArray = false;
+ jsonArray = new JSONArray();
+ }
+
+ prevKey = presKey;
+ //
+ if(key.contains(".")){
+ if(nodeKey==null){
+ nodeKey = key.substring(0,key.indexOf("."));
+ }
+ if(nodeKey.equals(key.substring(0,key.indexOf(".")))){
+ node.put(key.substring(key.indexOf(".")+1), element.get(key));
+ }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(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
+ jsonArray.put(decodeContent(node));
+ }
+ if(key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))){
+ jsonResult.put(arryKey, jsonArray);
+ jsonArray = new JSONArray();
+ }else if(!key.contains("@")){
+ jsonResult.put(arryKey, jsonArray);
+ jsonArray = new JSONArray();
+ }
+ arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
+ }else{
+ isArray = false;
+ jsonResult.put(nodeKey, decodeContent(node));
+ }
+ node = nodeFactory.objectNode();
+ }
+ nodeKey = key.substring(0,key.indexOf("."));
+ if(nodeKey.contains("@")){
+ arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
+ }
+ node.put(key.substring(key.indexOf(".")+1), element.get(key));
+ }
+ }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(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){
+ 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));
+ }else{
+ jsonResult.put(oldValue, jsonArray);
+ jsonArray = new JSONArray();
+ }
+ oldValue = key.substring(0,key.indexOf("@"));
+ }else{
+ jsonResult.put(key, element.get(key));
+ }
+ }else{
+ if(key.contains("@")){
+ isArray = true;
+ if(key.endsWith("@0")|| jsonArray==null){
+ 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));
+ }else{
+ jsonResult.put(oldValue, jsonArray);
+ jsonArray = new JSONArray();
+ }
+ oldValue = key.substring(0,key.indexOf("@"));
+ }else{
+ jsonResult.put(key, element.get(key));
+ }
+ }
+ }
+ if(node.size()>0){
+ if(nodeKey.contains("@")){
+ if(jsonArray==null){
+ jsonArray = new JSONArray();
+ }
+ if(arryKey==null){
+ arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
+ }
+ jsonArray.put(decodeContent(node));
+ jsonResult.put(arryKey, jsonArray);
+ isArray = false;;
+ }else{
+ jsonResult.put(nodeKey, decodeContent(node));
+ }
+ }
+ if(isArray && jsonArray.length() > 0){
+ jsonResult.put(oldValue, jsonArray);
+ }
+ return jsonResult;
+ }
+
+ @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+
+ String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
+ String servicename = value.toString().split("-v")[0];
+ String version = null;
+ if (value.toString().contains("-v")){
+ version = value.toString().split("-v")[1];
+ }
+ MicroServiceModels returnModel = getAttributeObject(servicename, version);
+
+ String jsonModel = createMicroSeriveJson(returnModel);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+ List<Object> list = new ArrayList<>();
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(returnModel);
+ JSONObject j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}");
+ list.add(j);
+ out.write(list.toString());
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ private String createMicroSeriveJson(MicroServiceModels returnModel) {
+ Map<String, String> attributeMap = new HashMap<String, String>();
+ Map<String, String> refAttributeMap = new HashMap<String, String>();
+ String attribute = returnModel.getAttributes();
+ if(attribute != null){
+ attribute = attribute.trim();
+ }
+ String refAttribute = returnModel.getRef_attributes();
+ if(refAttribute != null){
+ refAttribute = refAttribute.trim();
+ }
+ String enumAttribute = returnModel.getEnumValues();
+ if(enumAttribute != null){
+ enumAttribute = enumAttribute.trim();
+ }
+ if (!StringUtils.isEmpty(attribute)){
+ attributeMap = convert(attribute, ",");
+ }
+ if (!StringUtils.isEmpty(refAttribute)){
+ refAttributeMap = convert(refAttribute, ",");
+ }
+
+ Gson gson = new Gson();
+
+ String subAttributes = returnModel.getSub_attributes();
+ if(subAttributes != null){
+ subAttributes = subAttributes.trim();
+ }else{
+ subAttributes = "";
+ }
+ Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
+
+ JSONObject object = new JSONObject();
+ JSONArray array = new JSONArray();
+
+ for (Entry<String, String> keySet : attributeMap.entrySet()){
+ array = new JSONArray();
+ String value = keySet.getValue();
+ if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ array.put(value);
+ object.put(keySet.getKey().trim(), array);
+ }else {
+ object.put(keySet.getKey().trim(), value.trim());
+ }
+ }
+
+ for (Entry<String, String> keySet : refAttributeMap.entrySet()){
+ array = new JSONArray();
+ String value = keySet.getValue().split(":")[0];
+ if (gsonObject.containsKey(value)){
+ if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ 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")){
+ array.put(value.trim());
+ object.put(keySet.getKey().trim(), array);
+ }else {
+ object.put(keySet.getKey().trim(), value.trim());
+ }
+ }
+ }
+
+ return object.toString();
+ }
+
+ @SuppressWarnings("unchecked")
+ private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
+ JSONObject object = new JSONObject();
+ Map<String, String> map = new HashMap<String, String>();
+ Object returnClass = subAttributeMap.get(name);
+ map = (Map<String, String>) returnClass;
+ JSONArray array = new JSONArray();
+
+ for( Entry<String, String> m:map.entrySet()){
+ String[] splitValue = m.getValue().split(":");
+ array = new JSONArray();
+ if (subAttributeMap.containsKey(splitValue[0])){
+ if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){
+ 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")){
+ array.put(splitValue[0].trim());
+ object.put(m.getKey().trim(), array);
+ }else {
+ object.put(m.getKey().trim(), splitValue[0].trim());
+ }
+ }
+ }
+
+ return object;
+ }
+
+
+ @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+
+ String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
+ String servicename = value.toString().split("-v")[0];
+ Set<String> returnList = getVersionList(servicename);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+ List<Object> list = new ArrayList<>();
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(returnList);
+ JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}");
+ list.add(j);
+ out.write(list.toString());
+ return null;
+ }
+
+ private Set<String> getVersionList(String name) {
+ MicroServiceModels workingModel = new MicroServiceModels();
+ Set<String> list = new HashSet<String>();
+ List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
+ for (int i = 0; i < microServiceModelsData.size(); i++) {
+ workingModel = (MicroServiceModels) microServiceModelsData.get(i);
+ if (workingModel.getVersion()!=null){
+ list.add(workingModel.getVersion());
+ }else{
+ list.add("Default");
+ }
+ }
+ return list;
+ }
+
+ private MicroServiceModels getAttributeObject(String name, String version) {
+ MicroServiceModels workingModel = new MicroServiceModels();
+ List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
+ for (int i = 0; i < microServiceModelsData.size(); i++) {
+ workingModel = (MicroServiceModels) microServiceModelsData.get(i);
+ if(version != null){
+ if (workingModel.getVersion()!=null){
+ if (workingModel.getVersion().equals(version)){
+ return workingModel;
+ }
+ }else{
+ return workingModel;
+ }
+ }else{
+ return workingModel;
+ }
+
+ }
+ return workingModel;
+ }
+
+ @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ List<String> priorityList = new ArrayList<String>();
+ priorityCount = 10;
+ for (int i = 1; i < priorityCount; i++) {
+ priorityList.add(String.valueOf(i));
+ }
+ model.put("priorityDatas", mapper.writeValueAsString(priorityList));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+ public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ int index = 0;
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (matchList.size()>1 && iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attributevalue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+
+ // First match in the target is EcompName, so set that value.
+ if (index == 0) {
+ policyAdapter.setEcompName(value);
+ }
+ if (index == 1){
+ policyAdapter.setConfigName(value);
+ }
+ if (index == 2){
+ if(value != null){
+ readFile(policyAdapter, entity);
+ }
+ }
+ if (index == 3){
+ policyAdapter.setUuid(value);
+ }
+ if (index == 4){
+ policyAdapter.setLocation(value);
+ }
+ if (index == 5){
+ policyAdapter.setRiskType(value);
+ }
+
+ if (index == 6){
+ policyAdapter.setRiskLevel(value);
+ }
+
+ if (index == 7){
+ policyAdapter.setGuard(value);
+ }
+ if (index == 8 && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ index++;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private String convertDate(String dateTTL, boolean portalType) {
+ String formateDate = null;
+ String[] date = dateTTL.split("T");
+ String[] parts = date[0].split("-");
+
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
+ return formateDate;
+ }
+
+ public static Map<String, String> convert(String str, String split) {
+ Map<String, String> map = new HashMap<String, String>();
+ for(final String entry : str.split(split)) {
+ String[] parts = entry.split("=");
+ map.put(parts[0], parts[1]);
+ }
+ return map;
+ }
+
+
+ @SuppressWarnings("unchecked")
+ private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ String policyScopeName = null;
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
+ policyScopeName = getPolicyScope(msBody.getPolicyScope());
+ policyAdapter.setPolicyScope(policyScopeName);
+
+ policyAdapter.setPriority(msBody.getPriority());
+
+ if (msBody.getVersion()!= null){
+ policyAdapter.setServiceType(msBody.getService());
+ policyAdapter.setVersion(msBody.getVersion());
+ }else{
+ policyAdapter.setServiceType(msBody.getService());
+ }
+ if(msBody.getContent() != null){
+ LinkedHashMap<String, Object> data = new LinkedHashMap<String, Object>();
+ LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
+ readRecursivlyJSONContent(map, data);
+ policyAdapter.setRuleData(data);
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
+ for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
+ Object key = iterator.next();
+ Object value = map.get(key);
+ if(value instanceof LinkedHashMap<?, ?>){
+ LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<String, Object>();
+ readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
+ for(String objKey: secondObjec.keySet()){
+ data.put(key+"." +objKey, secondObjec.get(objKey));
+ }
+ }else if(value instanceof ArrayList){
+ ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
+ for(int i = 0; i < jsonArrayVal.size(); i++){
+ Object arrayvalue = jsonArrayVal.get(i);
+ if(arrayvalue instanceof LinkedHashMap<?, ?>){
+ LinkedHashMap<String, Object> newData = new LinkedHashMap<String, Object>();
+ readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
+ for(String objKey: newData.keySet()){
+ data.put(key+"@"+i+"." +objKey, newData.get(objKey));
+ }
+ }else if(arrayvalue instanceof ArrayList){
+ ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
+ for(int j = 0; j < jsonArrayVal1.size(); j++){
+ Object arrayvalue1 = jsonArrayVal1.get(i);
+ data.put(key+"@"+j, arrayvalue1.toString());
+ }
+ }else{
+ data.put(key+"@"+i, arrayvalue.toString());
+ }
+ }
+ }else{
+ data.put(key.toString(), value.toString());
+ }
+ }
+ }
+
+ private String getPolicyScope(String value) {
+ GroupPolicyScopeList pScope = new GroupPolicyScopeList();
+ List<Object> groupList= commonClassDao.getData(GroupPolicyScopeList.class);
+ if(groupList.size() > 0){
+ for(int i = 0 ; i < groupList.size() ; i ++){
+ pScope = (GroupPolicyScopeList) groupList.get(i);
+ if (pScope.getGroupList().equals(value)){
+ break;
+ }
+ }
+ }
+ return pScope.getGroupName();
+ }
+
+ //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<String, String>();
+ String temp = null;
+ String key;
+ String value;
+ for (Entry<String, String> entry : attributesMap.entrySet()) {
+ key = entry.getKey();
+ value = entry.getValue();
+ attribute.put(key, value);
+ }
+ for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
+ key = entryRef.getKey();
+ value = entryRef.getValue().toString();
+ attribute.put(key, value);
+ }
+ for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
+ key = entryList.getKey();
+ value = entryList.getValue().toString();
+ attribute.put(key, value);
+ }
+ for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
+ key = arrayList.getKey();
+ temp = null;
+ for (Object textList : arrayList.getValue()){
+ if (temp == null){
+ temp = "[" + textList;
+ }else{
+ temp = temp + "," + textList;
+ }
+ }
+ attribute.put(key, temp+ "]");
+ }
+
+ return attribute;
+ }
+
+ @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
+ boolean zip = false;
+ for (FileItem item : items) {
+ if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")){
+ this.newModel = new MicroServiceModels();
+ try{
+ File file = new File(item.getName());
+ OutputStream outputStream = new FileOutputStream(file);
+ IOUtils.copy(item.getInputStream(), outputStream);
+ 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 {
+ this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", ""));
+ }
+ }
+ }catch(Exception e){
+ logger.error("Upload error : " + e);
+ }
+ }
+ }
+ List<File> fileList = new ArrayList<File>();;
+ this.directory = "model";
+ if (zip){
+ extractFolder(this.newFile);
+ fileList = listModelFiles(this.directory);
+ }else {
+ File file = new File(this.newFile);
+ fileList.add(file);
+ }
+
+ //Process Main Model file first
+ classMap = new HashMap<String,MSAttributeObject>();
+ for (File file : fileList) {
+ if(!file.isDirectory() && file.getName().endsWith(".xmi")){
+ retreiveDependency(file.toString(), true);
+ }
+ }
+
+ modelList = createList();
+
+ cleanUp(this.newFile);
+ cleanUp(directory);
+
+ PrintWriter out = response.getWriter();
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ ObjectMapper mapper = new ObjectMapper();
+ JSONObject j = new JSONObject();
+ j.put("classListDatas", modelList);
+ j.put("modelDatas", mapper.writeValueAsString(classMap));
+ out.write(j.toString());
+ }
+
+ /*
+ * Unzip file and store in the model directory for processing
+ */
+ @SuppressWarnings("rawtypes")
+ private void extractFolder(String zipFile ) {
+ int BUFFER = 2048;
+ File file = new File(zipFile);
+
+ ZipFile zip;
+ try {
+ 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);
+ new File(newPath).mkdir();
+ Enumeration zipFileEntries = zip.entries();
+
+ // Process each entry
+ while (zipFileEntries.hasMoreElements()){
+ // grab a zip file entry
+ ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
+ String currentEntry = entry.getName();
+ File destFile = new File("model" + File.separator + currentEntry);
+ File destinationParent = destFile.getParentFile();
+
+ destinationParent.mkdirs();
+
+ 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);
+ }
+ dest.flush();
+ dest.close();
+ is.close();
+ }
+
+ if (currentEntry.endsWith(".zip")){
+ extractFolder(destFile.getAbsolutePath());
+ }
+ }
+ } catch (IOException e) {
+ logger.error("Failed to unzip model file " + zipFile);
+ }
+ }
+
+ private void retreiveDependency(String workingFile, Boolean modelClass) {
+
+ MSModelUtils utils = new MSModelUtils(PolicyController.msEcompName, PolicyController.msPolicyName);
+ HashMap<String, MSAttributeObject> tempMap = new HashMap<String, MSAttributeObject>();
+
+ tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
+
+ classMap.putAll(tempMap);
+ System.out.println(tempMap);
+
+ return;
+
+ }
+
+ private List<File> listModelFiles(String directoryName) {
+ File directory = new File(directoryName);
+ List<File> resultList = new ArrayList<File>();
+ File[] fList = directory.listFiles();
+ for (File file : fList) {
+ if (file.isFile()) {
+ resultList.add(file);
+ } else if (file.isDirectory()) {
+ dirDependencyList.add(file.getName());
+ resultList.addAll(listModelFiles(file.getAbsolutePath()));
+ }
+ }
+ return resultList;
+ }
+
+ private void cleanUp(String path) {
+ if (path!=null){
+ try {
+ FileUtils.forceDelete(new File(path));
+ } catch (IOException e) {
+ logger.error("Failed to delete folder " + path);
+ }
+ }
+ }
+
+ private void checkZipDirectory(String zipDirectory) {
+ Path path = Paths.get(zipDirectory);
+
+ if (Files.exists(path)) {
+ cleanUp(zipDirectory);
+ }
+ }
+
+ private List<String> createList() {
+ List<String> list = new ArrayList<String>();
+ for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
+ if (cMap.getValue().isPolicyTempalate()){
+ list.add(cMap.getKey());
+ }
+
+ }
+
+ if (list.isEmpty()){
+ if (classMap.containsKey(this.newModel.getModelName())){
+ list.add(this.newModel.getModelName());
+ }else {
+ list.add("EMPTY");
+ }
+ }
+ return list;
+ }
+
+}
+
+class DCAEMicroServiceObject {
+
+ public String service;
+ public String location;
+ public String uuid;
+ public String policyName;
+ public String description;
+ public String configName;
+ public String templateVersion;
+ public String version;
+ public String priority;
+ public String policyScope;
+ public String riskType;
+ public String riskLevel;
+ public String guard = null;
+
+ public String getGuard() {
+ return guard;
+ }
+ public void setGuard(String guard) {
+ this.guard = guard;
+ }
+ public String getRiskType() {
+ return riskType;
+ }
+ public void setRiskType(String riskType) {
+ this.riskType = riskType;
+ }
+ public String getRiskLevel() {
+ return riskLevel;
+ }
+ public void setRiskLevel(String riskLevel) {
+ this.riskLevel = riskLevel;
+ }
+ public String getPolicyScope() {
+ return policyScope;
+ }
+ public void setPolicyScope(String policyScope) {
+ this.policyScope = policyScope;
+ }
+
+ public String getPriority() {
+ return priority;
+ }
+ public void setPriority(String priority) {
+ this.priority = priority;
+ }
+ public String getVersion() {
+ return version;
+ }
+ public void setVersion(String version) {
+ this.version = version;
+ }
+ private Object content;
+
+
+ public String getPolicyName() {
+ return policyName;
+ }
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String description) {
+ this.description = description;
+ }
+ public String getConfigName() {
+ return configName;
+ }
+ public void setConfigName(String configName) {
+ this.configName = configName;
+ }
+ public Object getContent() {
+ return content;
+ }
+ public void setContent(Object content) {
+ this.content = content;
+ }
+
+ public String getService() {
+ return service;
+ }
+ public void setService(String service) {
+ this.service = service;
+ }
+ public String getLocation() {
+ return location;
+ }
+ public void setLocation(String location) {
+ this.location = location;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+ public String getTemplateVersion() {
+ return templateVersion;
+ }
+ public void setTemplateVersion(String templateVersion) {
+ this.templateVersion = templateVersion;
+ }
+
+} \ No newline at end of file
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
new file mode 100644
index 000000000..ecc39cdb6
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java
@@ -0,0 +1,932 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.hibernate.SessionFactory;
+import org.json.JSONObject;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.rest.adapter.AddressGroupJson;
+import org.openecomp.policy.rest.adapter.AddressJson;
+import org.openecomp.policy.rest.adapter.AddressMembers;
+import org.openecomp.policy.rest.adapter.DeployNowJson;
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+import org.openecomp.policy.rest.adapter.PrefixIPList;
+import org.openecomp.policy.rest.adapter.ServiceGroupJson;
+import org.openecomp.policy.rest.adapter.ServiceListJson;
+import org.openecomp.policy.rest.adapter.ServiceMembers;
+import org.openecomp.policy.rest.adapter.ServicesJson;
+import org.openecomp.policy.rest.adapter.TagDefines;
+import org.openecomp.policy.rest.adapter.Tags;
+import org.openecomp.policy.rest.adapter.Term;
+import org.openecomp.policy.rest.adapter.TermCollector;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.AddressGroup;
+import org.openecomp.policy.rest.jpa.FWTagPicker;
+import org.openecomp.policy.rest.jpa.GroupServiceList;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.policy.rest.jpa.PrefixList;
+import org.openecomp.policy.rest.jpa.SecurityZone;
+import org.openecomp.policy.rest.jpa.ServiceList;
+import org.openecomp.policy.rest.jpa.TermList;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.core.JsonGenerationException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectWriter;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+@Controller
+@RequestMapping("/")
+public class CreateFirewallController extends RestrictedBaseController {
+ private static Logger logger = FlexLogger.getLogger(CreateFirewallController.class);
+
+ @Autowired
+ SessionFactory sessionFactory;
+
+ private static CommonClassDao commonClassDao;
+
+ private List<String> tagCollectorList;
+ private String jsonBody;
+ List<String> expandablePrefixIPList = new ArrayList<String>();
+ List<String> expandableServicesList= new ArrayList<String>();
+ @Autowired
+ private CreateFirewallController(CommonClassDao commonClassDao){
+ CreateFirewallController.commonClassDao = commonClassDao;
+ }
+
+ public CreateFirewallController(){}
+ private List<String> termCollectorList;
+ private ArrayList<Object> attributeList;
+
+
+ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData){
+
+ termCollectorList = new ArrayList<String>();
+ tagCollectorList = new ArrayList<String>();
+ if(policyData.getAttributes().size() > 0){
+ for(Object attribute : policyData.getAttributes()){
+ if(attribute instanceof LinkedHashMap<?, ?>){
+ String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
+ termCollectorList.add(key);
+
+ String tag = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
+ tagCollectorList.add(tag);
+ }
+ }
+ }
+ jsonBody = constructJson(policyData);
+ if (jsonBody != null || jsonBody.equalsIgnoreCase("")) {
+ policyData.setJsonBody(jsonBody);
+
+ } else {
+ policyData.setJsonBody("{}");
+ }
+ policyData.setJsonBody(jsonBody);
+
+ return policyData;
+ }
+
+ private List<String> mapping(String expandableList) {
+ String value = new String();
+ String desc = new String();
+ List <String> valueDesc= new ArrayList<String>();
+ List<Object> prefixListData = commonClassDao.getData(PrefixList.class);
+ for (int i = 0; i< prefixListData.size(); i++) {
+ PrefixList prefixList = (PrefixList) prefixListData.get(i);
+ if (prefixList.getPrefixListName().equals(expandableList)) {
+ value = prefixList.getPrefixListValue();
+ valueDesc.add(value);
+ desc= prefixList.getDescription();
+ valueDesc.add(desc);
+ break;
+ }
+ }
+ return valueDesc;
+ }
+
+ private ServiceList mappingServiceList(String expandableList) {
+ ServiceList serviceList=null;
+ List<Object> serviceListData = commonClassDao.getData(ServiceList.class);
+ for (int i = 0; i< serviceListData.size(); i++) {
+ serviceList = (ServiceList) serviceListData.get(i);
+ if (serviceList.getServiceName().equals(expandableList)) {
+ break;
+ }
+ }
+ return serviceList;
+ }
+
+ private GroupServiceList mappingServiceGroup(String expandableList) {
+
+ GroupServiceList serviceGroup=null;
+ List<Object> serviceGroupData = commonClassDao.getData(GroupServiceList.class);
+ for (int i = 0; i< serviceGroupData.size(); i++) {
+ serviceGroup = (GroupServiceList) serviceGroupData.get(i);
+ if (serviceGroup.getGroupName().equals(expandableList)) {
+ break;
+ }
+ }
+ return serviceGroup;
+ }
+
+ private AddressGroup mappingAddressGroup(String expandableList) {
+
+ AddressGroup addressGroup=null;
+ List<Object> addressGroupData = commonClassDao.getData(AddressGroup.class);
+ for (int i = 0; i< addressGroupData.size(); i++) {
+ addressGroup = (AddressGroup) addressGroupData.get(i);
+ if (addressGroup.getGroupName().equals(expandableList)) {
+ break;
+ }
+ }
+ return addressGroup;
+ }
+
+ public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ attributeList = new ArrayList<Object>();
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ // policy name value is the policy name without any prefix and Extensions.
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") +3);
+ if (logger.isDebugEnabled()) {
+ logger.debug("Prepopulating form data for Config Policy selected:"+ policyAdapter.getPolicyName());
+ }
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ TermCollector tc1=null;
+ try {
+ //Json conversion.
+ String data=null;
+ SecurityZone jpaSecurityZone;
+ data = entity.getConfigurationData().getConfigBody();
+ tc1 = (TermCollector)mapper.readValue(data, TermCollector.class);
+ List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
+ for (int i = 0; i < securityZoneData.size() ; i++) {
+ jpaSecurityZone = (SecurityZone) securityZoneData.get(i);
+ if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())){
+ policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName());
+ break;
+ }
+ }
+ }
+ catch(Exception e) {
+ logger.error("Exception Caused while Retriving the JSON body data" +e);
+ }
+
+ Map<String, String> termTagMap=null;
+
+ for(int i=0;i<tc1.getFirewallRuleList().size();i++){
+ termTagMap = new HashMap<String, String>();
+ String ruleName= tc1.getFirewallRuleList().get(i).getRuleName();
+ String tagPickerName=tc1.getRuleToTag().get(i).getTagPickerName();
+ termTagMap.put("key", ruleName);
+ termTagMap.put("value", tagPickerName);
+ attributeList.add(termTagMap);
+ }
+ policyAdapter.setAttributes(attributeList);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ int index = 0;
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ if (index == 1) {
+ policyAdapter.setConfigName(value);
+ }
+ if (index == 2){
+ policyAdapter.setRiskType(value);
+ }
+
+ if (index == 3){
+ policyAdapter.setRiskLevel(value);
+ }
+
+ if (index == 4){
+ policyAdapter.setGuard(value);
+ }
+ if (index == 5 && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ index++;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private String convertDate(String dateTTL, boolean portalType) {
+ String formateDate = null;
+ String[] date;
+ String[] parts;
+
+ if (portalType){
+ parts = dateTTL.split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
+ } else {
+ date = dateTTL.split("T");
+ parts = date[0].split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
+ }
+ return formateDate;
+ }
+
+ @RequestMapping(value={"/policyController/ViewFWPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView setFWViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ try {
+ termCollectorList = new ArrayList<String>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
+ if(policyData.getAttributes().size() > 0){
+ for(Object attribute : policyData.getAttributes()){
+ if(attribute instanceof LinkedHashMap<?, ?>){
+ String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
+ termCollectorList.add(key);
+ }
+ }
+ }
+ TermList jpaTermList;
+ String ruleSrcList=null;
+ String ruleDestList=null;
+ String ruleSrcPort=null;
+ String ruleDestPort=null;
+ String ruleAction=null;
+ List <String> valueDesc= new ArrayList<String>();
+ StringBuffer displayString = new StringBuffer();
+ for (String id : termCollectorList) {
+ List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id);
+ jpaTermList = (TermList) tmList.get(0);
+ if (jpaTermList != null){
+ ruleSrcList= ((TermList) jpaTermList).getSrcIPList();
+ if ((ruleSrcList!= null) && (!ruleSrcList.isEmpty()) && !ruleSrcList.equals("null")){
+ displayString.append("Source IP List: " + ((TermList) jpaTermList).getSrcIPList());
+ displayString.append(" ; \t\n");
+ for(String srcList:ruleSrcList.split(",")){
+ if(srcList.startsWith("Group_")){
+ AddressGroup ag= new AddressGroup();
+ 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");
+ }
+ }else{
+ if(!srcList.equals("ANY")){
+ valueDesc=mapping(srcList);
+ displayString.append("\n\t"+"Name: "+srcList);
+ displayString.append("\n\t"+"Description: "+valueDesc.get(1));
+ displayString.append("\n\t"+"Value: "+valueDesc.get(0));
+ displayString.append("\n");
+ }
+ }
+ }
+ displayString.append("\n");
+ }
+ ruleDestList= ((TermList) jpaTermList).getDestIPList();
+ if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& !ruleDestList.equals("null")){
+ displayString.append("Destination IP List: " + ((TermList) jpaTermList).getDestIPList());
+ displayString.append(" ; \t\n");
+ for(String destList:ruleDestList.split(",")){
+ if(destList.startsWith("Group_")){
+ AddressGroup ag= new AddressGroup();
+ 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");
+ }
+ }else{
+ if(!destList.equals("ANY")){
+ valueDesc=mapping(destList);
+ displayString.append("\n\t"+"Name: "+destList);
+ displayString.append("\n\t"+"Description: "+valueDesc.get(1));
+ displayString.append("\n\t"+"Value: "+valueDesc.get(0));
+ displayString.append("\n\t");
+ }
+ }
+ }
+ displayString.append("\n");
+ }
+
+ ruleSrcPort=((TermList) jpaTermList).getSrcPortList();
+ if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !ruleSrcPort.equals("null")) {
+ displayString.append("\n"+"Source Port List:"
+ + ruleSrcPort);
+ displayString.append(" ; \t\n");
+ }
+
+ ruleDestPort= ((TermList) jpaTermList).getDestPortList();
+ if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !ruleDestPort.equals("null")) {
+ displayString.append("\n"+"Destination Port List:"
+ + ruleDestPort);
+ displayString.append(" ; \t\n");
+ for(String destServices:ruleDestPort.split(",")){
+ if(destServices.startsWith("Group_")){
+ GroupServiceList sg= new GroupServiceList();
+ sg= mappingServiceGroup(destServices);
+ displayString.append("\n\t"+"Service Group has :"+sg.getServiceList()+"\n");
+ for(String groupItems:sg.getServiceList().split(",")){
+ ServiceList sl= new ServiceList();
+ 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{
+ if(!destServices.equals("ANY")){
+ ServiceList sl= new ServiceList();
+ sl= mappingServiceList(destServices);
+ 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");
+ }
+
+ ruleAction=(jpaTermList).getAction();
+ if ( ruleAction!= null && (!ruleAction.isEmpty())) {
+ displayString.append("\n"+"Action List:"
+ + ruleAction);
+ displayString.append(" ; \t\n");
+ }
+ }
+ }
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(displayString);
+ JSONObject j = new JSONObject("{policyData: " + responseString + "}");
+ out.write(j.toString());
+ return null;
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ }
+ return null;
+ }
+
+ private String constructJson(PolicyRestAdapter policyData) {
+ int ruleCount=1;
+ //Maps to assosciate the values read from the TermList dictionary
+ Map<Integer, String> srcIP_map =null;
+ Map<Integer, String> destIP_map=null;
+ Map<Integer, String> srcPort_map =null;
+ Map<Integer, String> destPort_map =null;
+ Map<Integer, String> action_map=null;
+ Map<Integer, String> fromZone_map=null;
+ Map<Integer, String> toZone_map=null;
+
+ String ruleDesc=null;
+ String ruleFromZone=null;
+ String ruleToZone=null;
+ String ruleSrcPrefixList=null;
+ String ruleDestPrefixList=null;
+ String ruleSrcPort=null;
+ String ruleDestPort=null;
+ String ruleAction=null;
+
+ String json = null;
+
+
+ List<String> expandableList = new ArrayList<String>();
+ TermList jpaTermList;
+ TermCollector tc = new TermCollector();
+ SecurityZone jpaSecurityZone;
+ List<Term> termList = new ArrayList<Term>();
+
+ Tags tags=null;
+ List<Tags>tagsList= new ArrayList<Tags>();
+
+ TagDefines tagDefine= new TagDefines();
+ List<TagDefines> tagList=null;
+ ServiceListJson targetSl=null;
+ int i=0;
+ try{
+
+ for(String tag:tagCollectorList){
+ tags= new Tags();
+ List<Object> tagListData = commonClassDao.getData(FWTagPicker.class);
+ for(int tagCounter=0; tagCounter<tagListData.size(); tagCounter++){
+ FWTagPicker jpaTagPickerList=(FWTagPicker) tagListData.get(tagCounter);
+ if (jpaTagPickerList.getTagPickerName().equals(tag) ){
+ String tagValues=jpaTagPickerList.getTagValues();
+ tagList= new ArrayList<TagDefines>();
+ for(String val:tagValues.split("#")) {
+ int index=val.indexOf(":");
+ String keyToStore=val.substring(0,index);
+ String valueToStore=val.substring(index+1,val.length());
+
+ tagDefine= new TagDefines();
+ tagDefine.setKey(keyToStore);
+ tagDefine.setValue(valueToStore);
+ //Add to the collection.
+ tagList.add(tagDefine);
+
+ }
+
+ }
+ }
+ tags.setTags(tagList);
+ tags.setTagPickerName(tag);
+ tags.setRuleName(termCollectorList.get(i));
+ tagsList.add(tags);
+ i++;
+ }
+ tc.setRuleToTag(tagsList);
+
+ for (int tl = 0 ; tl< termCollectorList.size(); tl++) {
+ expandableList.add(termCollectorList.get(tl));
+ Term targetTerm = new Term();
+ //targetSl= new ServiceListJson();
+ targetTerm.setRuleName(termCollectorList.get(tl));
+ List<Object> termListData = commonClassDao.getData(TermList.class);
+ for (int j =0; j < termListData.size(); j++) {
+ jpaTermList = (TermList) termListData.get(j);
+ if (jpaTermList.getTermName().equals(termCollectorList.get(tl))){
+ ruleDesc=jpaTermList.getTermDescription();
+ if ((ruleDesc!=null)&& (!ruleDesc.isEmpty())){
+ targetTerm.setDescription(ruleDesc);
+ }
+ ruleFromZone=jpaTermList.getFromZone();
+
+ if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())){
+ fromZone_map = new HashMap<Integer, String>();
+ fromZone_map.put(tl, ruleFromZone);
+ }
+ ruleToZone=jpaTermList.getToZone();
+
+ if ((ruleToZone != null) && (!ruleToZone.isEmpty())){
+ toZone_map = new HashMap<Integer, String>();
+ toZone_map.put(tl, ruleToZone);
+ }
+ ruleSrcPrefixList=jpaTermList.getSrcIPList();
+
+ if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())){
+ srcIP_map = new HashMap<Integer, String>();
+ srcIP_map.put(tl, ruleSrcPrefixList);
+ }
+
+ ruleDestPrefixList= jpaTermList.getDestIPList();
+ if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())){
+ destIP_map = new HashMap<Integer, String>();
+ destIP_map.put(tl, ruleDestPrefixList);
+ }
+
+ ruleSrcPort=jpaTermList.getSrcPortList();
+
+ if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())){
+ srcPort_map = new HashMap<Integer, String>();
+ srcPort_map.put(tl, ruleSrcPort);
+ }
+
+ ruleDestPort= jpaTermList.getDestPortList();
+
+ if (ruleDestPort!= null && (!jpaTermList.getDestPortList().isEmpty())){
+ destPort_map = new HashMap<Integer, String>();
+ destPort_map.put(tl, ruleDestPort);
+ }
+
+ ruleAction=jpaTermList.getAction();
+
+ if (( ruleAction!= null) && (!ruleAction.isEmpty())){
+ action_map = new HashMap<Integer, String>();
+ action_map.put(tl, ruleAction);
+ }
+ }
+ }
+ targetTerm.setEnabled(true);
+ targetTerm.setLog(true);
+ targetTerm.setNegateSource(false);
+ targetTerm.setNegateDestination(false);
+
+ if(action_map!=null){
+ targetTerm.setAction(action_map.get(tl));
+ }
+
+ //FromZone arrays
+ if(fromZone_map!=null){
+ List<String> fromZone= new ArrayList<String>();
+ for(String fromZoneStr:fromZone_map.get(tl).split(",") ){
+ fromZone.add(fromZoneStr);
+ }
+ targetTerm.setFromZones(fromZone);
+ }
+
+ //ToZone arrays
+ if(toZone_map!=null){
+ List<String> toZone= new ArrayList<String>();
+ for(String toZoneStr:toZone_map.get(tl).split(",") ){
+ toZone.add(toZoneStr);
+ }
+ targetTerm.setToZones(toZone);
+ }
+
+ //Destination Services.
+ if(destPort_map!=null){
+ Set<ServicesJson> destServicesJsonList= new HashSet<ServicesJson>();
+ for(String destServices:destPort_map.get(tl).split(",") ){
+ ServicesJson destServicesJson= new ServicesJson();
+ destServicesJson.setType("REFERENCE");
+ if(destServices.equals("ANY")){
+ destServicesJson.setName("any");
+ destServicesJsonList.add(destServicesJson);
+ break;
+ }else{
+ if(destServices.startsWith("Group_")){
+ destServicesJson.setName(destServices.substring(6,destServices.length()));
+ } else{
+ destServicesJson.setName(destServices);
+ }
+ destServicesJsonList.add(destServicesJson);
+ }
+ }
+ targetTerm.setDestServices(destServicesJsonList);
+ }
+ //ExpandableServicesList
+ if((srcPort_map!=null) && (destPort_map!=null)){
+ String servicesCollateString = (srcPort_map.get(tl) + "," + destPort_map.get(tl));
+ expandableServicesList.add(servicesCollateString);
+ }else if (srcPort_map!=null){
+ expandableServicesList.add(srcPort_map.get(tl));
+ }else if (destPort_map!=null){
+ expandableServicesList.add(destPort_map.get(tl));
+ }
+
+ if(srcIP_map!=null){
+ //Source List
+ List<AddressJson> sourceListArrayJson= new ArrayList<AddressJson>();
+ for(String srcList:srcIP_map.get(tl).split(",") ){
+ AddressJson srcListJson= new AddressJson();
+ if(srcList.equals("ANY")){
+ srcListJson.setType("any");
+ sourceListArrayJson.add(srcListJson);
+ break;
+ }else{
+ srcListJson.setType("REFERENCE");
+ if(srcList.startsWith("Group_")){
+ srcListJson.setName(srcList.substring(6,srcList.length()));
+ }else{
+ srcListJson.setName(srcList);
+ }
+ sourceListArrayJson.add(srcListJson);
+ }
+ }
+ targetTerm.setSourceList(sourceListArrayJson);
+ }
+ if(destIP_map!=null){
+ //Destination List
+ List<AddressJson> destListArrayJson= new ArrayList<AddressJson>();
+ for(String destList:destIP_map.get(tl).split(",")){
+ AddressJson destListJson= new AddressJson();
+ if(destList.equals("ANY")){
+ destListJson.setType("any");
+ destListArrayJson.add(destListJson);
+ break;
+ }else{
+ destListJson.setType("REFERENCE");
+ if(destList.startsWith("Group_")){
+ destListJson.setName(destList.substring(6,destList.length()));
+ }else{
+ destListJson.setName(destList);
+ }
+ destListArrayJson.add(destListJson);
+ }
+ }
+ targetTerm.setDestinationList(destListArrayJson);
+ }
+ //ExpandablePrefixIPList
+ if ((srcIP_map!=null) && (destIP_map!=null))
+ {
+ String collateString = (srcIP_map.get(tl) + "," + destIP_map
+ .get(tl));
+ expandablePrefixIPList.add(collateString);
+ }
+ else if(srcIP_map!=null){
+ expandablePrefixIPList.add(srcIP_map.get(tl));
+ }
+ else if(destIP_map!=null){
+ expandablePrefixIPList.add(destIP_map.get(tl));
+ }
+ termList.add(targetTerm);
+ targetTerm.setPosition("" + (ruleCount++));
+ }
+
+ List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
+ for (int j =0 ; j< securityZoneData.size() ; j++){
+ jpaSecurityZone = (SecurityZone) securityZoneData.get(j);
+ if (jpaSecurityZone.getZoneName().equals(policyData.getSecurityZone())){
+ tc.setSecurityZoneId(jpaSecurityZone.getZoneValue());
+ //setParentSecurityZone(jpaSecurityZone.getZoneValue());//For storing the securityZone IDs to the DB
+ break;
+ }
+ }
+
+ tc.setServiceTypeId("/v0/firewall/pan");
+ tc.setConfigName(policyData.getConfigName());
+
+ //Astra is rejecting the packet when it sees a new JSON field, so removing it for now.
+ //tc.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_FW));
+
+ DeployNowJson deployNow= new DeployNowJson();
+ deployNow.setDeployNow(false);
+
+ tc.setDeploymentOption(deployNow);
+
+ Set<ServiceListJson> servListArray = new HashSet<ServiceListJson>();
+ Set<ServiceGroupJson> servGroupArray= new HashSet<ServiceGroupJson>();
+ Set<AddressGroupJson> addrGroupArray= new HashSet<AddressGroupJson>();
+
+ ServiceGroupJson targetSg= null;
+ AddressGroupJson addressSg=null;
+ ServiceListJson targetAny= null;
+ ServiceListJson targetAnyTcp=null;
+ ServiceListJson targetAnyUdp=null;
+
+ for(String serviceList:expandableServicesList){
+ for(String t: serviceList.split(",")){
+ if((!t.startsWith("Group_"))){
+ if(!t.equals("ANY")){
+ ServiceList sl = new ServiceList();
+ targetSl= new ServiceListJson();
+ sl= mappingServiceList(t);
+ targetSl.setName(sl.getServiceName());
+ targetSl.setDescription(sl.getServiceDescription());
+ targetSl.setTransportProtocol(sl.getServiceTransProtocol());
+ targetSl.setType(sl.getServiceType());
+ targetSl.setPorts(sl.getServicePorts());
+ servListArray.add(targetSl);
+ }else{
+ //Any for destinationServices.
+ //Add names any, any-tcp, any-udp to the serviceGroup object.
+ targetAny= new ServiceListJson();
+ targetAny.setName("any");
+ targetAny.setType("SERVICE");
+ targetAny.setTransportProtocol("any");
+ targetAny.setPorts("any");
+
+ servListArray.add(targetAny);
+
+ targetAnyTcp= new ServiceListJson();
+ targetAnyTcp.setName("any-tcp");
+ targetAnyTcp.setType("SERVICE");
+ targetAnyTcp.setTransportProtocol("tcp");
+ targetAnyTcp.setPorts("any");
+
+ servListArray.add(targetAnyTcp);
+
+ targetAnyUdp= new ServiceListJson();
+ targetAnyUdp.setName("any-udp");
+ targetAnyUdp.setType("SERVICE");
+ targetAnyUdp.setTransportProtocol("udp");
+ targetAnyUdp.setPorts("any");
+
+ servListArray.add(targetAnyUdp);
+ }
+ }else{//This is a group
+ GroupServiceList sg= new GroupServiceList();
+ targetSg= new ServiceGroupJson();
+ sg= mappingServiceGroup(t);
+
+ String name=sg.getGroupName();
+ //Removing the "Group_" prepending string before packing the JSON
+ targetSg.setName(name.substring(6,name.length()));
+ List<ServiceMembers> servMembersList= new ArrayList<ServiceMembers>();
+
+ for(String groupString: sg.getServiceList().split(",")){
+ ServiceMembers serviceMembers= new ServiceMembers();
+ serviceMembers.setType("REFERENCE");
+ serviceMembers.setName(groupString);
+ servMembersList.add(serviceMembers);
+ //Expand the group Name
+ ServiceList expandGroupSl = new ServiceList();
+ targetSl= new ServiceListJson();
+ expandGroupSl= mappingServiceList(groupString);
+
+ targetSl.setName(expandGroupSl.getServiceName());
+ targetSl.setDescription(expandGroupSl.getServiceDescription());
+ targetSl.setTransportProtocol(expandGroupSl.getServiceTransProtocol());
+ targetSl.setType(expandGroupSl.getServiceType());
+ targetSl.setPorts(expandGroupSl.getServicePorts());
+ servListArray.add(targetSl);
+ }
+
+ targetSg.setMembers(servMembersList);
+ servGroupArray.add(targetSg);
+
+ }
+ }
+ }
+
+ Set<PrefixIPList> prefixIPList = new HashSet<PrefixIPList>();
+ for(String prefixList:expandablePrefixIPList){
+ for(String prefixIP: prefixList.split(",")){
+ if((!prefixIP.startsWith("Group_"))){
+ if(!prefixIP.equals("ANY")){
+ List<AddressMembers> addMembersList= new ArrayList<AddressMembers>();
+ List<String> valueDesc= new ArrayList<String>();
+ PrefixIPList targetAddressList = new PrefixIPList();
+ AddressMembers addressMembers= new AddressMembers();
+ targetAddressList.setName(prefixIP);
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:"+prefixIP);
+ valueDesc = mapping(prefixIP);
+ if(!valueDesc.isEmpty()){
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList description:"+valueDesc.get(1));
+ targetAddressList.setDescription(valueDesc.get(1));
+ }
+
+
+ addressMembers.setType("SUBNET");
+ if(!valueDesc.isEmpty()) {
+ addressMembers.setValue(valueDesc.get(0));
+ }
+
+ addMembersList.add(addressMembers);
+
+ targetAddressList.setMembers(addMembersList);
+ prefixIPList.add(targetAddressList);
+ }
+ }
+ else{//This is a group
+ AddressGroup ag= new AddressGroup();
+ addressSg= new AddressGroupJson();
+ ag= mappingAddressGroup(prefixIP);
+
+ String name=ag.getGroupName();
+ //Removing the "Group_" prepending string before packing the JSON
+ addressSg.setName(name.substring(6,name.length()));
+
+ List<AddressMembers> addrMembersList= new ArrayList<AddressMembers>();
+ for(String groupString: ag.getPrefixList().split(",")){
+ List<String> valueDesc= new ArrayList<String>();
+ AddressMembers addressMembers= new AddressMembers();
+ valueDesc= mapping (groupString);
+ if(valueDesc.size() > 0){
+ addressMembers.setValue(valueDesc.get(0));
+ }
+ addressMembers.setType("SUBNET");
+ addrMembersList.add(addressMembers);
+ //Expand the group Name
+ }
+ addressSg.setMembers(addrMembersList);
+ addrGroupArray.add(addressSg);
+ }
+
+
+ }
+ }
+
+ Set<Object> serviceGroup= new HashSet<Object>();
+
+ for(Object obj1:servGroupArray){
+ serviceGroup.add(obj1);
+ }
+
+ for(Object obj:servListArray){
+ serviceGroup.add(obj);
+ }
+
+ Set<Object> addressGroup= new HashSet<Object>();
+
+ for(Object addObj:prefixIPList){
+ addressGroup.add(addObj);
+ }
+
+ for(Object addObj1:addrGroupArray){
+ addressGroup.add(addObj1);
+ }
+
+ tc.setServiceGroups(serviceGroup);
+ tc.setAddressGroups(addressGroup);
+ tc.setFirewallRuleList(termList);
+
+ ObjectWriter om = new ObjectMapper().writer();
+ try {
+ json = om.writeValueAsString(tc);
+ } catch (JsonGenerationException e) {
+ e.printStackTrace();
+ } catch (JsonMappingException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return json;
+ }
+
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java
new file mode 100644
index 000000000..9a31d7f72
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java
@@ -0,0 +1,165 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+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;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+@Controller
+@RequestMapping("/")
+public class CreatePolicyController extends RestrictedBaseController{
+
+ protected PolicyRestAdapter policyAdapter = null;
+ private ArrayList<Object> attributeList;
+ boolean isValidForm = false;
+
+ private String convertDate(String dateTTL, boolean portalType) {
+ String formateDate = null;
+ String[] date;
+ String[] parts;
+
+ if (portalType){
+ parts = dateTTL.split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
+ } else {
+ date = dateTTL.split("T");
+ parts = date[0].split("-");
+ formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
+ }
+ return formateDate;
+ }
+
+ public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ attributeList = new ArrayList<Object>();
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ policyAdapter.setConfigType(entity.getConfigurationData().getConfigType());
+ policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ int index = 0;
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attributevalue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is EcompName, so set that value.
+ if (index == 1) {
+ policyAdapter.setEcompName(value);
+ }
+ if (index == 2){
+ policyAdapter.setRiskType(value);
+ }
+
+ if (index == 3){
+ policyAdapter.setRiskLevel(value);
+ }
+
+ if (index == 4){
+ policyAdapter.setGuard(value);
+ }
+ if (index == 5 && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ if (index == 6){
+ policyAdapter.setConfigName(value);
+ }
+ // After Ecomp and Config it is optional to have attributes, so
+ // check weather dynamic values or there or not.
+ if (index >= 7) {
+ Map<String, String> attribute = new HashMap<String, String>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ }
+ index++;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ policyAdapter.setAttributes(attributeList);
+ }
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ for (Object o : ruleList) {
+ if (o instanceof RuleType) {
+ // get the condition data under the rule for rule Algorithms.
+ policyAdapter.setRuleID(((RuleType) o).getRuleId());
+ }
+ }
+ }
+ }
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java
new file mode 100644
index 000000000..fcde0f370
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java
@@ -0,0 +1,420 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.management.AttributeNotFoundException;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanException;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+import javax.management.ReflectionException;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.openecomp.policy.dao.SystemLogDbDao;
+import org.openecomp.policy.model.PDPGroupContainer;
+import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
+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 com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.api.pap.EcompPDP;
+import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
+
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.api.pap.PDP;
+import com.att.research.xacml.api.pap.PDPGroup;
+import com.att.research.xacml.api.pap.PDPPolicy;
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping({"/"})
+public class DashboardController extends RestrictedBaseController{
+ private static final Logger logger = FlexLogger.getLogger(DashboardController.class);
+ @Autowired
+ SystemLogDbDao systemDAO;
+
+ @Autowired
+ CommonClassDao commonClassDao;
+
+ private int pdpCount;
+ private PDPGroupContainer pdpConatiner;
+ private ArrayList<Object> pdpStatusData;
+ private ArrayList<Object> papStatusData;
+ private ArrayList<Object> policyActivityData;
+
+
+
+ @RequestMapping(value={"/get_DashboardLoggingData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData()));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+ @RequestMapping(value={"/get_DashboardSystemAlertData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData()));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+ @RequestMapping(value={"/get_DashboardPAPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
+ addPAPToTable();
+ model.put("papTableDatas", mapper.writeValueAsString(papStatusData));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+ @RequestMapping(value={"/get_DashboardPDPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
+ this.pdpConatiner = new PDPGroupContainer(PolicyController.getPapEngine());
+ addPDPToTable();
+ model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+ @RequestMapping(value={"/get_DashboardPolicyActivityData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
+ this.pdpConatiner = new PDPGroupContainer(PolicyController.getPapEngine());
+ addPolicyToTable();
+ model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+ /*
+ * Add the PAP information to the PAP Table
+ */
+ public void addPAPToTable(){
+ papStatusData = new ArrayList<Object>();
+ String papStatus = null;
+ try {
+ Set<EcompPDPGroup> groups = PolicyController.getPapEngine().getEcompPDPGroups();
+ if (groups == null) {
+ papStatus = "UNKNOWN";
+ throw new PAPException("PAP not running");
+ }else {
+ papStatus = "IS_OK";
+ }
+ } catch (PAPException | NullPointerException e1) {
+ papStatus = "CANNOT_CONNECT";
+ logger.error("Error getting PAP status, PAP not responding to requests");
+ }
+ String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ JSONObject object = new JSONObject();
+ object.put("system", papURL);
+ object.put("status", papStatus);
+ List<Object> data = commonClassDao.getDataByQuery("from PolicyEntity");
+ object.put("noOfPolicy", data.size());
+ object.put("noOfConnectedTrap", pdpCount);
+ papStatusData.add(0, object);
+ }
+
+ /**
+ * Add PDP Information to the PDP Table
+ *
+ */
+ public void addPDPToTable(){
+ pdpCount = 0;
+ pdpStatusData = new ArrayList<Object>();
+ long naCount;
+ long denyCount = 0;
+ long permitCount = 0;
+ for (PDPGroup group : this.pdpConatiner.getGroups()){
+ for (PDP pdp : group.getPdps()){
+ naCount = -1;
+ if (pdp.getStatus().getStatus().toString() == "UP_TO_DATE" && ((EcompPDP) pdp).getJmxPort() != 0){
+ String pdpIpAddress = parseIPSystem(pdp.getId());
+ int port = ((EcompPDP) pdp).getJmxPort();
+ if (port != 0)
+ logger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port);
+ naCount = getRequestCounts(pdpIpAddress, port, "pdpEvaluationNA");
+ permitCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationPermit");
+ denyCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationDeny");
+ }
+ if (naCount == -1){
+ JSONObject object = new JSONObject();
+ object.put("id", pdp.getId());
+ object.put("name", pdp.getName());
+ object.put("groupname", group.getName());
+ object.put("status", pdp.getStatus().getStatus().toString());
+ object.put("description", pdp.getDescription());
+ object.put("permitCount", "NA");
+ object.put("denyCount", "NA");
+ object.put("naCount", "NA");
+ pdpStatusData.add(object);
+ }else{
+ JSONObject object = new JSONObject();
+ object.put("id", pdp.getId());
+ object.put("name", pdp.getName());
+ object.put("groupname", group.getName());
+ object.put("status", pdp.getStatus().getStatus().toString());
+ object.put("description", pdp.getDescription());
+ object.put("permitCount", permitCount);
+ object.put("denyCount", denyCount);
+ object.put("naCount", naCount);
+ pdpStatusData.add(object);
+ }
+ pdpCount++;
+ }
+ }
+ }
+
+ private static String parseIPSystem(String line) {
+ Pattern pattern = Pattern.compile("://(.+?):");
+ Matcher ip = pattern.matcher(line);
+ if (ip.find())
+ {
+ return ip.group(1);
+ }
+ return null;
+ }
+
+ /*
+ * Contact JMX Connector Sever and return the value of the given jmxAttribute
+ */
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private long getRequestCounts(String host, int port, String jmxAttribute) {
+
+ logger.debug("Create an RMI connector client and connect it to the JMX connector server");
+ HashMap map = new HashMap();
+ map = null;
+ JMXConnector jmxConnection;
+ try {
+ jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
+ jmxConnection.connect();
+ Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
+ jmxConnection.close();
+ logger.debug("pdpEvaluationNA value retreived: " + o);
+ return (long) o;
+ } catch (MalformedURLException e) {
+ logger.error("MalformedURLException for JMX connection");
+ } catch (IOException e) {
+ logger.error("Error in reteriving" + jmxAttribute + " from JMX connection");
+ } catch (AttributeNotFoundException e) {
+ logger.error("AttributeNotFoundException " + jmxAttribute + " for JMX connection");
+ } catch (InstanceNotFoundException e) {
+ logger.error("InstanceNotFoundException " + host + " for JMX connection");
+ } catch (MalformedObjectNameException e) {
+ logger.error("MalformedObjectNameException for JMX connection");
+ } catch (MBeanException e) {
+ logger.error("MBeanException for JMX connection");
+ e.printStackTrace();
+ } catch (ReflectionException e) {
+ logger.error("ReflectionException for JMX connection");
+ }
+
+ return -1;
+ }
+
+ private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException{
+ return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
+ }
+
+
+ /*
+ * Add the information to the Policy Table
+ */
+ private void addPolicyToTable() {
+ policyActivityData = new ArrayList<Object>();
+ int i = 1;
+ String policyID = null;
+ int policyFireCount = 0;
+ Map<String, String> policyMap = new HashMap<>();
+ Object policyList = null;
+ //get list of policy
+
+ for (PDPGroup group : this.pdpConatiner.getGroups()){
+ for (PDPPolicy policy : group.getPolicies()){
+ try{
+ policyMap.put(policy.getPolicyId().replace(" ", ""), policy.getId());
+ }catch(Exception e){
+ logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+policy.getName() +e);
+ }
+ }
+
+ for (PDP pdp : group.getPdps()){
+ // Add rows to the Policy Table
+ policyList = null;
+ if (pdp.getStatus().getStatus().toString() == "UP_TO_DATE" && ((EcompPDP) pdp).getJmxPort() != 0){
+ String pdpIpAddress = parseIPSystem(pdp.getId());
+ policyList = getPolicy(pdpIpAddress, ((EcompPDP) pdp).getJmxPort(), "policyCount");
+ }
+ if (policyList != null && policyList.toString().length() > 3){
+ String[] splitPolicy = policyList.toString().split(",");
+ 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(i, object);
+ i++;
+ }
+ }
+ }
+ }else {
+ if (policyList != null){
+ JSONObject object = new JSONObject();
+ object.put("policyId", "Unable to retrieve policy information");
+ object.put("fireCount", "NA");
+ object.put("system", pdp.getId());
+ policyActivityData.add(i, object);
+ i++;
+ }else{
+ JSONObject object = new JSONObject();
+ object.put("policyId", "Unable to access PDP JMX Server");
+ object.put("fireCount", "NA");
+ object.put("system", pdp.getId());
+ policyActivityData.add(i, object);
+ i++;
+ }
+ }
+
+ }
+ }
+ }
+
+ /*
+ * Contact JMX Connector Sever and return the list of {policy id , count}
+ */
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private Object getPolicy(String host, int port, String jmxAttribute){
+ logger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
+ HashMap map = new HashMap();
+ map = null;
+ JMXConnector jmxConnection;
+ try {
+ jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
+ jmxConnection.connect();
+ Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
+ jmxConnection.close();
+ logger.debug("policyMap value retreived: " + o);
+ return o;
+ } catch (MalformedURLException e) {
+ logger.error("MalformedURLException for JMX connection");
+ } catch (IOException e) {
+ logger.error("AttributeNotFoundException for policyMap" );
+ } catch (AttributeNotFoundException e) {
+ logger.error("AttributeNotFoundException for JMX connection");
+ } catch (InstanceNotFoundException e) {
+ logger.error("InstanceNotFoundException " + host + " for JMX connection");
+ } catch (MalformedObjectNameException e) {
+ logger.error("MalformedObjectNameException for JMX connection");
+ } catch (MBeanException e) {
+ logger.error("MBeanException for JMX connection");
+ e.printStackTrace();
+ } catch (ReflectionException e) {
+ logger.error("ReflectionException for JMX connection");
+ }
+
+ return null;
+
+ }
+
+ private static String urnPolicyID(String line){
+ String[] splitLine = line.toString().split("=");
+ String removeSpaces = splitLine[0].replaceAll("\\s+", "");
+ return removeSpaces.replace("{", "");
+ }
+
+ private static Integer countPolicyID(String line){
+ String[] splitLine = line.toString().split("=");
+ String sCount = splitLine[1].replace("}", "");
+ int intCount = Integer.parseInt(sCount);
+ return intCount;
+ }
+
+}
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
new file mode 100644
index 000000000..d21788e90
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java
@@ -0,0 +1,262 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+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.jpa.PolicyEntity;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
+
+@Controller
+@RequestMapping("/")
+public class DecisionPolicyController extends RestrictedBaseController {
+ private static final Logger logger = FlexLogger.getLogger(DecisionPolicyController.class);
+
+ public DecisionPolicyController(){}
+
+ protected PolicyRestAdapter policyAdapter = null;
+ private ArrayList<Object> attributeList;
+ private ArrayList<Object> decisionList;
+ private ArrayList<Object> ruleAlgorithmList;
+ protected LinkedList<Integer> ruleAlgoirthmTracker;
+ public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
+
+ @SuppressWarnings("unchecked")
+ public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ attributeList = new ArrayList<Object>();
+ decisionList = new ArrayList<Object>();
+ ruleAlgorithmList = new ArrayList<Object>();
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy for Action.
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AntOfType we have AllOfType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOfType we have Mathch.
+ List<MatchType> matchList = allOf.getMatch();
+ int index = 0;
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attributevalue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is EcompName, so set that value.
+ if (index == 0) {
+ policyAdapter.setEcompName(value);
+ }
+ // Component attributes are saved under Target here we are fetching them back.
+ // One row is default so we are not adding dynamic componet at index 0.
+ if (index >= 1) {
+ Map<String, String> attribute = new HashMap<String, String>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ }
+ index++;
+ }
+ }
+ policyAdapter.setAttributes(attributeList);
+ }
+ }
+ }
+ }
+
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ int index = 0;
+ for (Object object : ruleList) {
+ if (object instanceof VariableDefinitionType) {
+ VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
+ Map<String, String> settings = new HashMap<String, String>();
+ settings.put("key", variableDefinitionType.getVariableId());
+ JAXBElement<AttributeValueType> attributeValueTypeElement = (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
+ if (attributeValueTypeElement != null) {
+ AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
+ settings.put("value", attributeValueType.getContent().get(0).toString());
+ }
+ decisionList.add(settings);
+ } else if (object instanceof RuleType) {
+ // get the condition data under the rule for rule Algorithms.
+ if (((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
+ ConditionType condition = ((RuleType) object).getCondition();
+ if (condition != null) {
+ ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
+ ruleAlgoirthmTracker = new LinkedList<Integer>();
+ // Populating Rule Algorithms starting from compound.
+ prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
+ policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
+ }
+ }else 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{
+ policyAdapter.setRuleProvider("Custom");
+ }
+ }
+ }
+ }
+ }
+ policyAdapter.setSettings(decisionList);
+ }
+
+ }
+
+ private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, List<JAXBElement<?>> jaxbDecisionTypes) {
+ Map<String, String> ruleMap = new HashMap<String, String>();
+ 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);
+ }
+ }
+ // Populate the key and value fields
+ 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) {
+ AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue();
+ ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
+
+ // Get from Attribute Value
+ AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(0).getValue();
+ String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
+ ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
+ }
+ } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) {
+ VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue();
+ ruleMap.put("dynamicRuleAlgorithmField1", "S_"+ variableReference.getVariableId());
+
+
+ // Get from Attribute Value
+ AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue();
+ String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
+ ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
+ }
+ ruleAlgorithmList.add(ruleMap);
+ }
+
+ private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) {
+ boolean isCompoundRule = true;
+ List<JAXBElement<?>> jaxbDecisionTypes = decisionApply.getExpression();
+ for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
+ // If There is Attribute Value under Decision Type that means we came to the final child
+ if (logger.isDebugEnabled()) {
+ logger.debug("Prepopulating rule algoirthm: " + index);
+ }
+ // Check to see if Attribute Value exists, if yes then it is not a compound rule
+ if(jaxbElement.getValue() instanceof AttributeValueType) {
+ prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes);
+ ruleAlgoirthmTracker.addLast(index);
+ isCompoundRule = false;
+ index++;
+ }
+ }
+ if (isCompoundRule) {
+ // As it's compound rule, Get the Apply types
+ for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
+ ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
+ index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
+ }
+ // Populate combo box
+ if (logger.isDebugEnabled()) {
+ logger.debug("Prepopulating Compound rule algorithm: " + index);
+ }
+ Map<String, String> rule = new HashMap<String, String>();
+ for (String key : PolicyController.getDropDownMap().keySet()) {
+ String keyValue = PolicyController.getDropDownMap().get(key);
+ if (keyValue.equals(decisionApply.getFunctionId())) {
+ rule.put("dynamicRuleAlgorithmCombo", key);
+ }
+ }
+
+ rule.put("id", "A" + (index +1));
+ // Populate Key and values for Compound Rule
+ rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 ));
+ ruleAlgoirthmTracker.removeLast();
+ rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
+ ruleAlgoirthmTracker.removeLast();
+ ruleAlgoirthmTracker.addLast(index);
+ ruleAlgorithmList.add(rule);
+ index++;
+ }
+ return index;
+ }
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java
new file mode 100644
index 000000000..2fcf7939b
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java
@@ -0,0 +1,292 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.openecomp.policy.model.PDPGroupContainer;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.web.support.JsonMessage;
+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.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
+
+import com.att.research.xacml.api.pap.PAPException;
+import org.openecomp.policy.xacml.std.pap.StdPDP;
+import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping({"/"})
+public class PDPController extends RestrictedBaseController {
+ private static final Logger logger = FlexLogger.getLogger(PDPController.class);
+
+ protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>());
+ private PDPGroupContainer container;
+
+ public synchronized void refreshGroups() {
+ synchronized(this.groups) {
+ this.groups.clear();
+ try {
+ this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
+ } catch (PAPException e) {
+ String message = "Unable to retrieve Groups from server: " + e;
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Pap Engine is Null" + message);
+ }
+
+ }
+ }
+
+ @RequestMapping(value={"/get_PDPGroupContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getPDPGroupContainerData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ ObjectMapper mapper = new ObjectMapper();
+ refreshGroups();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group Container data" + e);
+ }
+ }
+
+ @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ ObjectMapper mapper = new ObjectMapper();
+ refreshGroups();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group data" + e);
+ }
+ }
+
+ @RequestMapping(value={"/pdp_Group/save_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView savePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ this.container = new PDPGroupContainer(PolicyController.getPapEngine());
+ StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
+ try {
+ if(pdpGroupData.getId() == null){
+ this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription());
+ }else{
+ this.container.updateGroup(pdpGroupData);
+ }
+
+ } catch (Exception e) {
+ String message = "Unable to create Group. Reason:\n" + e.getMessage();
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message);
+ }
+
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ refreshGroups();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ out.write(j.toString());
+
+ return null;
+ }
+ catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+
+ @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ try{
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ this.container = new PDPGroupContainer(PolicyController.getPapEngine());
+ StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
+ if(pdpGroupData.getName().equals("Default")) {
+ throw new UnsupportedOperationException("You can't remove the Default Group.");
+ }else{
+ this.container.removeGroup(pdpGroupData, null);
+ }
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+
+ refreshGroups();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ out.write(j.toString());
+
+ return null;
+ }
+ catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+
+ @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView savePDPToGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ this.container = new PDPGroupContainer(PolicyController.getPapEngine());
+ String update = root.get("update").toString();
+ PdpData pdpGroupData = (PdpData)mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
+ StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
+ try {
+
+ if(update.contains("false")){
+ this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
+ }else{
+ this.container.updateGroup(activeGroupData);
+ }
+ } catch (Exception e) {
+ String message = "Unable to create Group. Reason:\n" + e.getMessage();
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message);
+ }
+
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ refreshGroups();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ out.write(j.toString());
+
+ return null;
+ }
+ catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+
+ @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ try{
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ this.container = new PDPGroupContainer(PolicyController.getPapEngine());
+ StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
+ StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
+
+ this.container.removePDP(deletePdp, activeGroupData);
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ refreshGroups();
+ String responseString = mapper.writeValueAsString(groups);
+ JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}");
+ out.write(j.toString());
+
+ return null;
+ }
+ catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+}
+
+class PdpData{
+ String id;
+ int jmxPort;
+ String name;
+ String description;
+ public String getId() {
+ return id;
+ }
+ public void setId(String id) {
+ this.id = id;
+ }
+ public int getJmxPort() {
+ return jmxPort;
+ }
+ public void setJmxPort(int jmxPort) {
+ this.jmxPort = jmxPort;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+}
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
new file mode 100644
index 000000000..72dfb164b
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java
@@ -0,0 +1,421 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.annotation.PostConstruct;
+import javax.mail.MessagingException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.openecomp.policy.admin.PolicyNotificationMail;
+import org.openecomp.policy.admin.RESTfulPAPEngine;
+import org.openecomp.policy.model.PDPGroupContainer;
+import org.openecomp.policy.model.Roles;
+import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.rest.XacmlAdminAuthorization;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.Datatype;
+import org.openecomp.policy.rest.jpa.FunctionDefinition;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.policy.rest.jpa.PolicyVersion;
+import org.openecomp.policy.rest.jpa.UserInfo;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.web.support.JsonMessage;
+import org.openecomp.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine;
+
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+
+
+@Controller
+@RequestMapping("/")
+public class PolicyController extends RestrictedBaseController {
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyController.class);
+
+ private static CommonClassDao commonClassDao;
+ // Our authorization object
+ //
+ XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization();
+ //
+ // The PAP Engine
+ //
+ private static PAPPolicyEngine papEngine;
+
+ public static String logTableLimit;
+ public static String systemAlertTableLimit;
+ protected static Map<String, String> dropDownMap = new HashMap<String, String>();
+ public static Map<String, String> getDropDownMap() {
+ return dropDownMap;
+ }
+
+ public static void setDropDownMap(Map<String, String> dropDownMap) {
+ PolicyController.dropDownMap = dropDownMap;
+ }
+
+ public static String getDomain() {
+ return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
+ }
+
+ private static final Object mapAccess = new Object();
+ private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
+ private static Map<String, FunctionDefinition> mapID2Function = null;
+
+
+ //Smtp Java Mail Properties
+ public static String smtpHost = null;
+ public static String smtpPort = null;
+ public static String smtpUsername = null;
+ public static String smtpPassword = null;
+ public static String smtpApplicationName = null;
+ public static String smtpEmailExtension = null;
+ //log db Properties
+ public static String logdbDriver = null;
+ public static String logdbUrl = null;
+ public static String logdbUserName = null;
+ public static String logdbPassword = null;
+ public static String logdbDialect = null;
+ //Xacml db properties
+ public static String xacmldbUrl = null;
+ public static String xacmldbUserName = null;
+ public static String xacmldbPassword = null;
+
+ //AutoPush feature.
+ public static String autoPushAvailable;
+ public static String autoPushDSClosedLoop;
+ public static String autoPushDSFirewall;
+ public static String autoPushDSMicroservice;
+ public static String autoPushPDPGroup;
+
+ //papURL
+ public static String papUrl;
+
+ //MicroService Model Properties
+ public static String msEcompName;
+ public static String msPolicyName;
+
+ @Autowired
+ private PolicyController(CommonClassDao commonClassDao){
+ PolicyController.commonClassDao = commonClassDao;
+ }
+
+ public PolicyController() {
+ }
+
+ @PostConstruct
+ public void init(){
+ Properties prop = new Properties();
+ InputStream input = null;
+ try {
+ input = new FileInputStream("xacml.admin.properties");
+ // load a properties file
+ prop.load(input);
+ //pap url
+ papUrl = prop.getProperty("xacml.rest.pap.url");
+ // get the property values
+ smtpHost = prop.getProperty("ecomp.smtp.host");
+ smtpPort = prop.getProperty("ecomp.smtp.port");
+ smtpUsername = prop.getProperty("ecomp.smtp.userName");
+ smtpPassword = prop.getProperty("ecomp.smtp.password");
+ smtpApplicationName = prop.getProperty("ecomp.application.name");
+ smtpEmailExtension = prop.getProperty("ecomp.smtp.emailExtension");
+ //Log Database Properties
+ logdbDriver = prop.getProperty("xacml.log.db.driver");
+ logdbUrl = prop.getProperty("xacml.log.db.url");
+ logdbUserName = prop.getProperty("xacml.log.db.user");
+ logdbPassword = prop.getProperty("xacml.log.db.password");
+ logdbDialect = prop.getProperty("ecomp.dialect");
+ //Xacml Database Properties
+ xacmldbUrl = prop.getProperty("javax.persistence.jdbc.url");
+ xacmldbUserName = prop.getProperty("javax.persistence.jdbc.user");
+ xacmldbPassword = prop.getProperty("javax.persistence.jdbc.password");
+ //AutoPuh
+ autoPushAvailable=prop.getProperty("xacml.automatic.push");
+ autoPushDSClosedLoop=prop.getProperty("xacml.autopush.closedloop");
+ autoPushDSFirewall=prop.getProperty("xacml.autopush.firewall");
+ autoPushDSMicroservice=prop.getProperty("xacml.autopush.microservice");
+ autoPushPDPGroup=prop.getProperty("xacml.autopush.pdpGroup");
+ //Micro Service Properties
+ msEcompName=prop.getProperty("xacml.policy.msEcompName");
+ msPolicyName=prop.getProperty("xacml.policy.msPolicyName");
+ //Get the Property Values for Dashboard tab Limit
+ try{
+ logTableLimit = prop.getProperty("xacml.ecomp.dashboard.logTableLimit");
+ systemAlertTableLimit = prop.getProperty("xacml.ecomp.dashboard.systemAlertTableLimit");
+ }catch(Exception e){
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
+ logTableLimit = "5000";
+ systemAlertTableLimit = "2000";
+ }
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
+ } catch (IOException ex) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex);
+ } finally {
+ if (input != null) {
+ try {
+ input.close();
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e);
+ }
+ }
+ }
+
+ //Initialize the FunctionDefinition table at Server Start up
+ Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
+ for (Datatype id : functionMap.keySet()) {
+ List<FunctionDefinition> functionDefinations = (List<FunctionDefinition>) functionMap.get(id);
+ for (FunctionDefinition functionDef : functionDefinations) {
+ dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
+ }
+ }
+
+ }
+
+ public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
+ synchronized(mapAccess) {
+ if (mapDatatype2Function == null) {
+ buildFunctionMaps();
+ }
+ }
+ return mapDatatype2Function;
+ }
+
+ public static Map<String, FunctionDefinition> getFunctionIDMap() {
+ synchronized(mapAccess) {
+ if (mapID2Function == null) {
+ buildFunctionMaps();
+ }
+ }
+ return mapID2Function;
+ }
+
+ private static void buildFunctionMaps() {
+ mapDatatype2Function = new HashMap<Datatype, List<FunctionDefinition>>();
+ mapID2Function = new HashMap<String, FunctionDefinition>();
+ List<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);
+ for (int i = 0; i < functiondefinitions.size(); i ++) {
+ FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
+ mapID2Function.put(value.getXacmlid(), value);
+ if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) {
+ mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
+ }
+ mapDatatype2Function.get(value.getDatatypeBean()).add(value);
+ }
+ }
+
+ @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("functionDefinitionDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ LOGGER.equals(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e);
+ }
+ }
+
+ public PolicyEntity getPolicyEntityData(String scope, String policyName){
+ String key = scope + ":" + policyName;
+ List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
+ PolicyEntity entity = (PolicyEntity) data.get(0);
+ return entity;
+ }
+
+ public static Map<String, Roles> getUserRoles(String userId) {
+ Map<String, Roles> scopes = new HashMap<String, Roles>();
+ List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
+ if (roles != null && roles.size() > 0) {
+ for (Object role : roles) {
+ scopes.put(((Roles) role).getScope(), (Roles) role);
+ }
+ }
+ return scopes;
+ }
+
+ public static List<String> getRolesOfUser(String userId) {
+ List<String> rolesList = new ArrayList<String>();
+ List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
+ for (Object role: roles) {
+ rolesList.add(((Roles) role).getRole());
+ }
+ return rolesList;
+ }
+
+ public static List<Object> getRoles(String userId) {
+ return commonClassDao.getDataById(Roles.class, "loginId", userId);
+ }
+
+ //Get List of User Roles
+ @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+ //Policy tabs Model and View
+ @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET)
+ public ModelAndView view(HttpServletRequest request){
+ String myRequestURL = request.getRequestURL().toString();
+ try {
+ //
+ // Set the URL for the RESTful PAP Engine
+ //
+ setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
+ new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e);
+ }
+ Map<String, Object> model = new HashMap<String, Object>();
+ return new ModelAndView("policy_Editor","model", model);
+ }
+
+ public static PAPPolicyEngine getPapEngine() {
+ return papEngine;
+ }
+
+ public void setPapEngine(PAPPolicyEngine papEngine) {
+ PolicyController.papEngine = papEngine;
+ }
+
+ public String getUserName(String createdBy) {
+ String loginId = createdBy;
+ List<Object> data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId);
+ return data.get(0).toString();
+ }
+
+ public static boolean getActivePolicy(String query) {
+ if(commonClassDao.getDataByQuery(query).size() > 0){
+ return true;
+ }else{
+ return false;
+ }
+ }
+
+ public void executeQuery(String query) {
+ commonClassDao.updateQuery(query);
+ }
+
+ public void saveData(Object cloneEntity) {
+ commonClassDao.save(cloneEntity);
+ }
+
+ public void updateData(Object entity) {
+ commonClassDao.update(entity);
+ }
+
+ public void deleteData(Object entity) {
+ commonClassDao.delete(entity);
+ }
+
+ public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
+ PolicyVersion policyVersionEntity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
+ return policyVersionEntity;
+ }
+
+ public List<Object> getDataByQuery(String query){
+ return commonClassDao.getDataByQuery(query);
+ }
+
+
+ @SuppressWarnings("rawtypes")
+ public Object getEntityItem(Class className, String columname, String key){
+ return commonClassDao.getEntityItem(className, columname, key);
+ }
+
+
+ public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){
+ PolicyNotificationMail email = new PolicyNotificationMail();
+ try {
+ email.sendMail(entity, policyName, mode, commonClassDao);
+ } catch (MessagingException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
+ }
+ }
+
+ //Switch Version
+ public JSONObject switchVersionPolicyContent(String policyName) {
+ String dbCheckName = policyName.replace("/", ".");
+ if(dbCheckName.contains("Config_")){
+ dbCheckName = dbCheckName.replace(".Config_", ":Config_");
+ }else if(dbCheckName.contains("Action_")){
+ dbCheckName = dbCheckName.replace(".Action_", ":Action_");
+ }else if(dbCheckName.contains("Decision_")){
+ dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
+ }
+ String[] splitDBCheckName = dbCheckName.split(":");
+ String query = "FROM PolicyEntity where policyName like'"+splitDBCheckName[1]+"%' and scope ='"+splitDBCheckName[0]+"'";
+ List<Object> policyEntity = commonClassDao.getDataByQuery(query);
+ List<String> av = new ArrayList<String>();
+ for(Object entity : policyEntity){
+ PolicyEntity pEntity = (PolicyEntity) entity;
+ String removeExtension = pEntity.getPolicyName().replace(".xml", "");
+ String version = removeExtension.substring(removeExtension.lastIndexOf(".")+1);
+ av.add(version);
+ }
+ if(policyName.contains("/")){
+ policyName = policyName.replace("/", File.separator);
+ }
+ PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
+ JSONObject el = new JSONObject();
+ el.put("activeVersion", entity.getActiveVersion());
+ el.put("availableVersions", av);
+ el.put("highestVersion", entity.getHigherVersion());
+ return el;
+ }
+}
+
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java
new file mode 100644
index 000000000..b6899e041
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java
@@ -0,0 +1,367 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.json.JSONObject;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.model.Roles;
+import org.openecomp.policy.rest.adapter.PolicyExportAdapter;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.ActionBodyEntity;
+import org.openecomp.policy.rest.jpa.ConfigurationDataEntity;
+import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.policy.rest.jpa.PolicyVersion;
+import org.openecomp.policy.rest.jpa.UserInfo;
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+
+@Controller
+@RequestMapping("/")
+public class PolicyExportAndImportController extends RestrictedBaseController {
+ private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class);
+
+ private ArrayList<String> selectedPolicy;
+ private Set<String> scopes = null;
+ private List<String> roles = null;
+ private static String SUPERADMIN = "super-admin";
+ private static String SUPEREDITOR = "super-editor";
+ private static String ADMIN = "admin";
+ private static String EDITOR = "editor";
+
+ private static CommonClassDao commonClassDao;
+
+ private PolicyEntity policyEntity;
+ private ConfigurationDataEntity configurationDataEntity;
+ private ActionBodyEntity actionBodyEntity;
+ private PolicyVersion policyVersion;
+
+ private Workbook workbook;
+
+ private HSSFWorkbook workBook2;
+
+ @Autowired
+ private PolicyExportAndImportController(CommonClassDao commonClassDao){
+ PolicyExportAndImportController.commonClassDao = commonClassDao;
+ }
+
+ public PolicyExportAndImportController(){}
+
+ @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void ExportPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ try{
+ String file = null;
+ selectedPolicy = new ArrayList<String>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyExportAdapter adapter = mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class);
+ for (Object policyId : adapter.getPolicyDatas()) {
+ LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
+ String policyWithScope = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
+ String scope = policyWithScope.substring(0 , policyWithScope.lastIndexOf(File.separator)).replace(File.separator, ".");
+ String policyName = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator)+1);
+ selectedPolicy.add(policyName+":"+scope);
+ }
+ List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope", selectedPolicy);
+
+ workBook2 = new HSSFWorkbook();
+ HSSFSheet sheet = workBook2.createSheet("PolicyEntity");
+
+ HSSFRow headingRow = sheet.createRow(0);
+ headingRow.createCell(0).setCellValue("policyName");
+ headingRow.createCell(1).setCellValue("scope");
+ headingRow.createCell(2).setCellValue("version");
+ headingRow.createCell(3).setCellValue("policyData");
+ headingRow.createCell(4).setCellValue("description");
+ headingRow.createCell(5).setCellValue("configurationbody");
+ headingRow.createCell(6).setCellValue("configurationName");
+
+ short rowNo = 1;
+ for (Object object : entityData) {
+ PolicyEntity policyEntity = (PolicyEntity) object;
+ HSSFRow row = sheet.createRow(rowNo);
+ row.createCell(0).setCellValue(policyEntity.getPolicyName());
+ row.createCell(1).setCellValue(policyEntity.getScope());
+ row.createCell(2).setCellValue(policyEntity.getVersion());
+ row.createCell(3).setCellValue(policyEntity.getPolicyData());
+ row.createCell(4).setCellValue(policyEntity.getDescription());
+ if(!policyEntity.getPolicyName().contains("Decision_")){
+ if(policyEntity.getConfigurationData() != null){
+ row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigBody());
+ row.createCell(6).setCellValue(policyEntity.getConfigurationData().getConfigurationName());
+ }
+ if(policyEntity.getActionBodyEntity() != null){
+ row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBody());
+ row.createCell(6).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName());
+ }
+ }else{
+ row.createCell(5).setCellValue("");
+ row.createCell(6).setCellValue("");
+ }
+ rowNo++;
+ }
+
+ String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
+ String deleteCheckPath = tmp + File.separator + "PolicyExport.xls";
+ File deleteCheck = new File(deleteCheckPath);
+ if(deleteCheck.exists()){
+ deleteCheck.delete();
+ }
+ File temPath = new File(tmp);
+ if(!temPath.exists()){
+ temPath.mkdir();
+ }
+
+ file = temPath + File.separator + "PolicyExport.xls";
+ File filepath = new File(file);
+ FileOutputStream fos = new FileOutputStream(filepath);
+ workBook2.write(fos);
+ fos.flush();
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String successMap = file.toString().substring(file.toString().lastIndexOf("webapps")+8);
+ String responseString = mapper.writeValueAsString(successMap);
+ JSONObject j = new JSONObject("{data: " + responseString + "}");
+ out.write(j.toString());
+ }catch(Exception e){
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e);
+ }
+ }
+
+ //Policy Import
+ public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws Exception{
+ boolean configExists = false;
+ boolean actionExists = false;
+ String configName = null;
+ String scope = null;
+ boolean finalColumn = false;
+ PolicyController controller = 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 = PolicyController.getRoles(userId);
+ roles = new ArrayList<String>();
+ scopes = new HashSet<String>();
+ 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());
+ }
+ }
+ }
+ FileInputStream excelFile = new FileInputStream(new File(file));
+ workbook = new HSSFWorkbook(excelFile);
+ Sheet datatypeSheet = workbook.getSheetAt(0);
+ Iterator<Row> rowIterator = datatypeSheet.iterator();
+
+ while (rowIterator.hasNext()) {
+ policyEntity = new PolicyEntity();
+ configurationDataEntity = new ConfigurationDataEntity();
+ actionBodyEntity = new ActionBodyEntity();
+ policyVersion = new PolicyVersion();
+ Row currentRow = rowIterator.next();
+ if (currentRow.getRowNum() == 0) {
+ continue;
+ }
+ Iterator<Cell> cellIterator = currentRow.cellIterator();
+ while (cellIterator.hasNext()) {
+ Cell cell = cellIterator.next();
+ if (getCellHeaderName(cell).equalsIgnoreCase("policyName")) {
+ policyEntity.setPolicyName(cell.getStringCellValue());
+ }
+ if (getCellHeaderName(cell).equalsIgnoreCase("scope")) {
+ policyEntity.setScope(cell.getStringCellValue());
+ }
+ if (getCellHeaderName(cell).equalsIgnoreCase("policyData")) {
+ policyEntity.setPolicyData(cell.getStringCellValue());
+ }
+ if (getCellHeaderName(cell).equalsIgnoreCase("description")) {
+ policyEntity.setDescription(cell.getStringCellValue());
+ }
+ if (getCellHeaderName(cell).equalsIgnoreCase("configurationbody")) {
+ if(policyEntity.getPolicyName().contains("Config_")){
+ configExists = true;
+ configurationDataEntity.setConfigBody(cell.getStringCellValue());
+ }else if(policyEntity.getPolicyName().contains("Action_")){
+ actionExists = true;
+ actionBodyEntity.setActionBody(cell.getStringCellValue());
+ }
+ }
+ if (getCellHeaderName(cell).equalsIgnoreCase("configurationName")) {
+ finalColumn = true;
+ configName = cell.getStringCellValue();
+ if(policyEntity.getPolicyName().contains("Config_")){
+ configurationDataEntity.setConfigurationName(cell.getStringCellValue());
+ }else if(policyEntity.getPolicyName().contains("Action_")){
+ actionBodyEntity.setActionBodyName(cell.getStringCellValue());
+ }
+ }
+
+ if(finalColumn){
+ scope = policyEntity.getScope().replace(".", File.separator);
+ String query = "FROM PolicyEntity where policyName = '"+policyEntity.getPolicyName()+"' and scope ='"+policyEntity.getScope()+"'";
+ List<Object> queryData = controller.getDataByQuery(query);
+ if(!queryData.isEmpty()){
+ continue;
+ }
+ if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR)) {
+ //1. if Role contains super admin create scope.
+ //2. if Role contains super editor don't create new scope and add to list to show to user.
+
+ PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope);
+ if(policyEditorScope == null){
+ if(roles.contains(SUPERADMIN)){
+ PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
+ policyEditorScopeEntity.setScopeName(scope);
+ policyEditorScopeEntity.setUserCreatedBy(userInfo);
+ policyEditorScopeEntity.setUserModifiedBy(userInfo);
+ commonClassDao.save(policyEditorScopeEntity);
+ }else{
+ //Add Error Message a new Scope Exists, contact super-admin to create a new scope
+ continue;
+ }
+ }
+ }
+ if (roles.contains(ADMIN) || roles.contains(EDITOR)) {
+ if(scopes.isEmpty()){
+ //return 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)){
+ String scopeCheck = scope.substring(0, scope.lastIndexOf("."));
+ if(scopes.contains(scopeCheck)){
+ PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
+ policyEditorScopeEntity.setScopeName(scope);
+ policyEditorScopeEntity.setUserCreatedBy(userInfo);
+ policyEditorScopeEntity.setUserModifiedBy(userInfo);
+ commonClassDao.save(policyEditorScopeEntity);
+ }else{
+ continue;
+ }
+ }else{
+ continue;
+ }
+ }
+ }
+
+ if(configExists){
+ if(configName.endsWith("json")){
+ configurationDataEntity.setConfigType("JSON");
+ }else if(configName.endsWith("txt")){
+ configurationDataEntity.setConfigType("OTHER");
+ }else if(configName.endsWith("xml")){
+ configurationDataEntity.setConfigType("XML");
+ }else if(configName.endsWith("properties")){
+ configurationDataEntity.setConfigType("PROPERTIES");
+ }
+ configurationDataEntity.setDeleted(false);
+ configurationDataEntity.setCreatedBy(userId);
+ configurationDataEntity.setModifiedBy(userId);
+ commonClassDao.save(configurationDataEntity);
+ }
+ if(actionExists){
+ actionBodyEntity.setDeleted(false);
+ actionBodyEntity.setCreatedBy(userId);
+ actionBodyEntity.setModifiedBy(userId);
+ commonClassDao.save(actionBodyEntity);
+ }
+ if(configName != null){
+ if(configName.contains("Config_")){
+ ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", configName);
+ policyEntity.setConfigurationData(configuration);
+ }else{
+ ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", configName);
+ policyEntity.setActionBodyEntity(actionBody);
+ }
+ }
+ policyEntity.setCreatedBy(userId);
+ policyEntity.setModifiedBy(userId);
+ policyEntity.setDeleted(false);
+ commonClassDao.save(policyEntity);
+
+ policyVersion = new PolicyVersion();
+ String policyName = policyEntity.getPolicyName().replace(".xml", "");
+ int version = Integer.parseInt(policyName.substring(policyName.lastIndexOf(".")+1));
+ policyName = policyName.substring(0, policyName.lastIndexOf("."));
+
+ policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyName);
+ policyVersion.setActiveVersion(version);
+ policyVersion.setHigherVersion(version);
+ policyVersion.setCreatedBy(userId);
+ policyVersion.setModifiedBy(userId);
+ commonClassDao.save(policyVersion);
+ }
+ }
+ }
+ return null;
+ }
+
+ //return the column header name value
+ private String getCellHeaderName(Cell cell){
+ String cellHeaderName = cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();
+ return cellHeaderName;
+ }
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java
new file mode 100644
index 000000000..768158453
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java
@@ -0,0 +1,122 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+/*
+ *
+ * */
+import java.io.File;
+import java.io.PrintWriter;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.WatchPolicyNotificationTable;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+
+@Controller
+@RequestMapping({"/"})
+public class PolicyNotificationController extends RestrictedBaseController {
+
+ @Autowired
+ CommonClassDao commonClassDao;
+
+ @RequestMapping(value={"/watchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ String path = "";
+ String responseValue = "";
+ try {
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ System.out.println(userId);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ String name = root.get("watchData").get("name").toString();
+ JsonNode pathList = root.get("watchData").get("path");
+ String finalName = "";
+ if(pathList.isArray()){
+ ArrayNode arrayNode = (ArrayNode) pathList;
+ for (int i = 0; i < arrayNode.size(); i++) {
+ JsonNode individualElement = arrayNode.get(i);
+ if(i == 0){
+ path = path + individualElement.toString().replace("\"", "").trim();
+ }else{
+ path = path + File.separator + individualElement.toString().replace("\"", "").trim();
+ }
+ }
+ }
+
+ if(pathList.size() > 0){
+ finalName = path + File.separator + name.replace("\"", "").trim();
+ }else{
+ finalName = name.replace("\"", "").trim();
+ }
+ if(finalName.contains("\\")){
+ finalName = finalName.replace("\\", "\\\\");
+ }
+ String query = "from WatchPolicyNotificationTable where POLICYNAME = '"+finalName+"' and LOGINIDS = '"+userId+"'";
+ List<Object> watchList = commonClassDao.getDataByQuery(query);
+ if(watchList.isEmpty()){
+ if(finalName.contains("\\\\")){
+ finalName = finalName.replace("\\\\", File.separator);
+ }
+ WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
+ watch.setPolicyName(finalName);
+ watch.setLoginIds(userId);
+ commonClassDao.save(watch);
+ responseValue = "You have Subscribed Successfully";
+ }else{
+ commonClassDao.delete(watchList.get(0));
+ responseValue = "You have UnSubscribed Successfully";
+ }
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(responseValue);
+ JSONObject j = new JSONObject("{watchData: " + responseString + "}");
+ out.write(j.toString());
+ return null;
+ }catch(Exception e){
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java
new file mode 100644
index 000000000..82090773c
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java
@@ -0,0 +1,163 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
+import org.openecomp.policy.rest.jpa.PolicyRoles;
+import org.openecomp.policy.rest.jpa.UserInfo;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class PolicyRolesController extends RestrictedBaseController{
+
+ @Autowired
+ CommonClassDao commonClassDao;
+
+ List<String> scopelist;
+
+ @RequestMapping(value={"/get_RolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles()));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+ @RequestMapping(value={"/save_NonSuperRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ String scopeName = null;
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class);
+ for(int i = 0; i < adapter.getScope().size(); i++){
+ if(i == 0){
+ scopeName = adapter.getScope().get(0);
+ }else{
+ scopeName = scopeName + "," + adapter.getScope().get(i);
+ }
+ }
+ PolicyRoles roles = new PolicyRoles();
+ roles.setId(adapter.getId());
+ roles.setLoginId(adapter.getLoginId());
+ roles.setRole(adapter.getRole());
+ roles.setScope(scopeName);
+ commonClassDao.update(roles);
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles());
+ JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}");
+
+ out.write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ @RequestMapping(value={"/get_PolicyRolesScopeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ scopelist = new ArrayList<String>();
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
+ List<String> scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName");
+ model.put("scopeDatas", mapper.writeValueAsString(scopesData));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+}
+
+class ReadScopes{
+ private int id;
+ private UserInfo loginId;
+ private String role;
+ private ArrayList<String> scope;
+
+ public int getId() {
+ return id;
+ }
+ public void setId(int id) {
+ this.id = id;
+ }
+ public UserInfo getLoginId() {
+ return loginId;
+ }
+ public void setLoginId(UserInfo loginId) {
+ this.loginId = loginId;
+ }
+ public String getRole() {
+ return role;
+ }
+ public void setRole(String role) {
+ this.role = role;
+ }
+ public ArrayList<String> getScope() {
+ return scope;
+ }
+ public void setScope(ArrayList<String> scope) {
+ this.scope = scope;
+ }
+
+}
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
new file mode 100644
index 000000000..55bff24a0
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java
@@ -0,0 +1,661 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.openecomp.policy.controller;
+
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Scanner;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.json.Json;
+import javax.json.JsonReader;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
+import org.apache.commons.lang.StringUtils;
+import org.dom4j.util.XMLErrorHandler;
+import org.json.JSONObject;
+import org.openecomp.policy.rest.adapter.ClosedLoopFaultBody;
+import org.openecomp.policy.rest.adapter.ClosedLoopPMBody;
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.MicroServiceModels;
+import org.openecomp.policy.rest.jpa.SafePolicyWarning;
+import org.openecomp.policy.utils.PolicyUtils;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.servlet.ModelAndView;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Splitter;
+import com.google.common.base.Strings;
+
+@Controller
+@RequestMapping("/")
+public class PolicyValidationController extends RestrictedBaseController {
+
+ public static final String CONFIG_POLICY = "Config";
+ public static final String ACTION_POLICY = "Action";
+ public static final String DECISION_POLICY = "Decision";
+ public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
+ public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
+ public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
+ public static final String MICROSERVICES="Micro Service";
+ private Pattern pattern;
+ private Matcher matcher;
+
+ private static Map<String, String> rangeMap = new HashMap<String,String>();
+ private static Map<String, String> mapAttribute = new HashMap<String,String>();
+
+ private static final String EMAIL_PATTERN =
+ "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
+
+ @Autowired
+ CommonClassDao commonClassDao;
+
+ @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ try{
+ boolean valid = true;
+ String responseString = "";
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
+ if(policyData.getPolicyName() != null){
+ String policyNameValidate = emptyValidator(policyData.getPolicyName());
+ if(!policyNameValidate.contains("success")){
+ responseString = responseString + "PolicyName:" + policyNameValidate + "<br>";
+ valid = false;
+ };
+ }else{
+ responseString = responseString + "PolicyName: PolicyName Should not be empty" + "<br>";
+ valid = false;
+ }
+ if(policyData.getPolicyDescription() != null){
+ String descriptionValidate = descriptionValidator(policyData.getPolicyDescription());
+ if(!descriptionValidate.contains("success")){
+ responseString = responseString + "Description:" + descriptionValidate + "<br>";
+ valid = false;
+ }
+ }
+
+ if(policyData.getPolicyType().equals(CONFIG_POLICY)){
+ if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY)
+ || policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) {
+ if(policyData.getEcompName() != null){
+ String ecompNameValidate = emptyValidator(policyData.getEcompName());
+ if(!ecompNameValidate.contains("success")){
+ responseString = responseString + "EcompName:" + ecompNameValidate + "<br>";
+ valid = false;
+ }
+ }else{
+ responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "<br>";
+ valid = false;
+ }
+ }
+
+ if(policyData.getRiskType() != null){
+ String riskTypeValidate = emptyValidator(policyData.getRiskType());
+ if(!riskTypeValidate.contains("success")){
+ responseString = responseString + "RiskType:" + riskTypeValidate + "<br>";
+ valid = false;
+ }
+ }else {
+ responseString = responseString + "Risk Type: Risk Type Should not be Empty" + "<br>";
+ valid = false;
+ }
+
+ if(policyData.getRiskLevel() != null){
+ String validateRiskLevel = emptyValidator(policyData.getRiskLevel());
+ if(!validateRiskLevel.contains("success")){
+ responseString = responseString + "RiskLevel:" + validateRiskLevel + "<br>";
+ valid = false;
+ }
+ }else {
+ responseString = responseString + "Risk Level: Risk Level Should not be Empty" + "<br>";
+ valid = false;
+ }
+
+ if(policyData.getGuard() != null){
+ String validateGuard = emptyValidator(policyData.getGuard());
+ if(!validateGuard.contains("success")){
+ responseString = responseString + "Guard:" + validateGuard + "<br>";
+ valid = false;
+ }
+ }else {
+ responseString = responseString + "Guard: Guard Value Should not be Empty" + "<br>";
+ valid = false;
+ }
+
+ if(policyData.getConfigPolicyType().equals("Base")){
+ if(policyData.getConfigName() != null){
+ String configNameValidate = emptyValidator(policyData.getConfigName());
+ if(!configNameValidate.contains("success")){
+ responseString = responseString + "ConfigName:" + configNameValidate + "<br>";
+ valid = false;
+ }
+ }else{
+ responseString = responseString + "Config Name: Config Name Should not be Empty" + "<br>";
+ valid = false;
+ }
+ if(policyData.getConfigType() != null){
+ String configTypeValidate = emptyValidator(policyData.getConfigType());
+ if(!configTypeValidate.contains("success")){
+ responseString = responseString + "ConfigType:" + configTypeValidate + "<br>";
+ valid = false;
+ }
+ }else{
+ responseString = responseString + "Config Type: Config Type Should not be Empty" + "<br>";
+ valid = false;
+ }
+ if(policyData.getConfigBodyData() != null){
+ String configBodyData = policyData.getConfigBodyData();
+ String policyType = policyData.getConfigType();
+ if (policyType != null) {
+ if (policyType.equals("JSON")) {
+ if (!isJSONValid(configBodyData)) {
+ responseString = responseString + "Config Body: JSON Content is not valid" + "<br>";
+ valid = false;
+ }
+ } else if (policyType.equals("XML")) {
+ if (!isXMLValid(configBodyData)) {
+ responseString = responseString + "Config Body: XML Content data is not valid" + "<br>";
+ valid = false;
+ }
+ } else if (policyType.equals("PROPERTIES")) {
+ if (!isPropValid(configBodyData)||configBodyData.equals("")) {
+ responseString = responseString + "Config Body: Property data is not valid" + "<br>";
+ valid = false;
+ }
+ } else if (policyType.equals("OTHER")) {
+ if (configBodyData.equals("")) {
+ responseString = responseString + "Config Body: Config Body Should not be Empty" + "<br>";
+ valid = false;
+ }
+ }
+ }
+ }else{
+ responseString = responseString + "Config Body: Config Body Should not be Empty" + "<br>";
+ valid = false;
+ }
+ }
+
+ if(policyData.getConfigPolicyType().equals("Firewall Config")){
+ if(policyData.getConfigName() != null){
+ String configNameValidate = PolicyUtils.emptyPolicyValidator(policyData.getConfigName());
+ if(!configNameValidate.contains("success")){
+ responseString = responseString + "<b>ConfigName</b>:<i>" + configNameValidate + "</i><br>";
+ valid = false;
+ }
+ }else{
+ responseString = responseString + "<b>Config Name</b>:<i> Config Name is required" + "</i><br>";
+ valid = false;
+ }
+ if(policyData.getSecurityZone() == null){
+ responseString = responseString + "<b>Security Zone</b>:<i> Security Zone is required" + "</i><br>";
+ valid = false;
+ }
+ }
+ if(policyData.getConfigPolicyType().equals("BRMS_Param")){
+ if(policyData.getRuleName() == null){
+ responseString = responseString + "<b>BRMS Template</b>:<i>BRMS Template is required</i><br>";
+ valid = false;
+ }
+ }
+ if(policyData.getConfigPolicyType().equals("BRMS_Raw")){
+ if(policyData.getConfigBodyData() != null){
+ String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
+ // If there are any error other than Annotations then this is not Valid
+ if(message.contains("[ERR")){
+ responseString = responseString + "<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>";
+ valid = false;
+ }
+ }else{
+ responseString = responseString + "<b>Raw Rule</b>:<i>Raw Rule is required</i><br>";
+ valid = false;
+ }
+ }
+ if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){
+ try{
+ if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){
+ responseString = responseString + "<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>";
+ valid = false;
+ }
+ }catch(Exception e){
+ responseString = responseString + "<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>";
+ valid = false;
+ }
+
+ if(root.get("policyData").get("jsonBodyData") != null){
+ ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class);
+ if(pmBody.getEmailAddress() != null){
+ String result = emailValidation(pmBody.getEmailAddress(), responseString);
+ if(result != "success"){
+ responseString = result + "<br>";
+ valid = false;
+ }
+ }
+ if(pmBody.getGeoLink() != null){
+ String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink());
+ if(!result.contains("success")){
+ responseString = responseString + "<b>GeoLink</b>:<i>" + result + "</i><br>";
+ valid = false;
+ };
+ }
+ if(pmBody.getAttributes() != null){
+ for(Entry<String, String> entry : pmBody.getAttributes().entrySet()){
+ String key = entry.getKey();
+ String value = entry.getValue();
+ if(!key.contains("Message")){
+ String attributeValidate = PolicyUtils.emptyPolicyValidator(value);
+ if(!attributeValidate.contains("success")){
+ responseString = responseString + "<b>Attributes</b>:<i>" + key + " : value has spaces</i><br>";
+ valid = false;
+ };
+ }
+ }
+ }
+ }else{
+ responseString = responseString + "<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>";
+ valid = false;
+ }
+ }
+ if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){
+ if(root.get("policyData").get("jsonBodyData") != null){
+ ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
+ if(faultBody.getEmailAddress() != null){
+ String result = emailValidation(faultBody.getEmailAddress(), responseString);
+ if(result != "success"){
+ responseString = result+ "<br>";
+ valid = false;
+ }
+ }
+ if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
+ responseString = responseString + "<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>";
+ valid = false;
+ }
+ if(faultBody.getActions() == null){
+ responseString = responseString + "<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>";
+ valid = false;
+ }
+ if(faultBody.getAgingWindow() == 0){
+ responseString = responseString + "<b>Aging Window</b>:<i>Aging Window is required</i><br>";
+ valid = false;
+ }
+ if(faultBody.getClosedLoopPolicyStatus() == null){
+ responseString = responseString + "<b>Policy Status</b>:<i>Policy Status is required</i><br>";
+ valid = false;
+ }
+ if(faultBody.getConditions() == null){
+ responseString = responseString + "<b>Conditions</b>:<i>Select Atleast one Condition</i><br>";
+ valid = false;
+ }
+ if(faultBody.getGeoLink() != null){
+ String result = PolicyUtils.emptyPolicyValidator(faultBody.getGeoLink());
+ if(!result.contains("success")){
+ responseString = responseString + "<b>GeoLink</b>:<i>" + result + "</i><br>";
+ valid = false;
+ };
+ }
+
+ if(faultBody.getTimeInterval() == 0){
+ responseString = responseString + "<b>Time Interval</b>:<i>Time Interval is required</i><br>";
+ valid = false;
+ }
+ if(faultBody.getRetrys() == 0){
+ responseString = responseString + "<b>Number of Retries</b>:<i>Number of Retries is required</i><br>";
+ valid = false;
+ }
+ if(faultBody.getTimeOutvPRO() == 0){
+ responseString = responseString + "<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>";
+ valid = false;
+ }
+ if(faultBody.getTimeOutRuby() == 0){
+ responseString = responseString + "<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>";
+ valid = false;
+ }
+ if(faultBody.getVnfType() == null){
+ responseString = responseString + "<b>Vnf Type</b>:<i>Vnf Type is required</i><br>";
+ valid = false;
+ }
+ }else{
+ responseString = responseString + "<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>";
+ responseString = responseString + "<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>";
+ responseString = responseString + "<b>Aging Window</b>:<i>Aging Window is required</i><br>";
+ responseString = responseString + "<b>Policy Status</b>:<i>Policy Status is required</i><br>";
+ responseString = responseString + "<b>Conditions</b>:<i>Select Atleast one Condition</i><br>";
+ responseString = responseString + "<b>PEP Name</b>:<i>PEP Name is required</i><br>";
+ responseString = responseString + "<b>PEP Action</b>:<i>PEP Action is required</i><br>";
+ responseString = responseString + "<b>Time Interval</b>:<i>Time Interval is required</i><br>";
+ responseString = responseString + "<b>Number of Retries</b>:<i>Number of Retries is required</i><br>";
+ responseString = responseString + "<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>";
+ responseString = responseString + "<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>";
+ responseString = responseString + "<b>Vnf Type</b>:<i>Vnf Type is required</i><br>";
+ valid = false;
+ }
+ }
+
+ if (policyData.getConfigPolicyType().contains("Micro Service")){
+ if(policyData.getServiceType() != null){
+ pullJsonKeyPairs(root.get("policyJSON"));
+ MicroServiceModels returnModel = new MicroServiceModels();
+ String service = null;
+ String version = null;
+ if (policyData.getServiceType().contains("-v")){
+ service = policyData.getServiceType().split("-v")[0];
+ version = policyData.getServiceType().split("-v")[1];
+ }else {
+ service = policyData.getServiceType();
+ version = policyData.getVersion();
+ }
+ returnModel = getAttributeObject(service, version);
+ String annoation = returnModel.getAnnotation();
+ if (!Strings.isNullOrEmpty(annoation)){
+ rangeMap = new HashMap<String,String>();
+ rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation);
+ for (Entry<String, String> rMap : rangeMap.entrySet()){
+ if (rMap.getValue().contains("range::")){
+ String value = mapAttribute.get(rMap.getKey().trim());
+ String[] tempString = rMap.getValue().split("::")[1].split("-");
+ int startNum = Integer.parseInt(tempString[0]);
+ int endNum = Integer.parseInt(tempString[1]);
+ String returnString = "Invalid Range:" + rMap.getKey() + " must be between "
+ + startNum + " - " + endNum + ",";
+ if (isType(value.replace("\"", ""))){
+ int result = Integer.parseInt(value.replace("\"", ""));
+
+
+ if (result < startNum || result > endNum){
+ responseString = responseString + returnString;
+ valid = false;
+ }
+ }else {
+ responseString = responseString + returnString;
+ valid = false;
+ }
+ }
+ }
+ }
+ //for continue testing for Dkat, just blocked this validation until fixing it. gw1218 on 3/30/17
+ //if (!checkAttributeValues()){
+ //responseString = responseString + "<b>Micro Service</b>:<i> Attribute Values Missing" + "</i><br>";
+ //valid = false;
+ //}
+
+ }else{
+ responseString = responseString + "<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>";
+ valid = false;
+ }
+
+ if(policyData.getPriority() == null){
+ responseString = responseString + "<b>Priority</b>:<i> Priority is required" + "</i><br>";
+ valid = false;
+ }
+ }
+ }
+ if (policyData.getPolicyType().equals(DECISION_POLICY)){
+ if(policyData.getEcompName() != null){
+ String ecompNameValidate = emptyValidator(policyData.getEcompName());
+ if(!ecompNameValidate.contains("success")){
+ responseString = responseString + "EcompName:" + ecompNameValidate + "<br>";
+ valid = false;
+ }
+ }else{
+ responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "<br>";
+ valid = false;
+ }
+
+ }
+
+ if(policyData.getPolicyType().equals(ACTION_POLICY)){
+ if(policyData.getActionPerformer() != null){
+ String actionPerformer = emptyValidator(policyData.getActionPerformer());
+ if(!actionPerformer.contains("success")){
+ responseString = responseString + "ActionPerformer:" + actionPerformer + "<br>";
+ valid = false;
+ };
+ }else{
+ responseString = responseString + "ActionPerformer: ActionPerformer Should not be empty" + "<br>";
+ valid = false;
+ }
+ if(policyData.getActionAttributeValue() != null){
+ String actionAttribute = emptyValidator(policyData.getActionAttributeValue());
+ if(!actionAttribute.contains("success")){
+ responseString = responseString + "ActionAttribute:" + actionAttribute + "<br>";
+ valid = false;
+ };
+ }else{
+ responseString = responseString + "ActionAttribute: ActionAttribute Should not be empty" + "<br>";
+ valid = false;
+ }
+ }
+
+ if(policyData.getPolicyType().equals(CONFIG_POLICY)){
+ if(valid){
+ List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
+ if (!spData.isEmpty()){
+ SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0);
+ safePolicyWarningData.getMessage();
+ responseString = responseString + "Messaage:" + safePolicyWarningData.getMessage();
+ }
+ responseString = "success" + "@#"+ responseString;
+ }
+ }else{
+ if(valid){
+ responseString = "success";
+ }
+ }
+
+ PrintWriter out = response.getWriter();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString));
+ JSONObject j = new JSONObject(msg);
+ out.write(j.toString());
+
+ return null;
+ }
+ catch (Exception e){
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+
+ protected String emptyValidator(String field){
+ String error = "success";
+ if (field.equals("") || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
+ error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
+ return error;
+ } else {
+ if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
+ error = "success";
+ }else{
+ error = "The Value Contains Non ASCII Characters";
+ return error;
+ }
+ }
+ return error;
+ }
+
+ protected String descriptionValidator(String field) {
+ String error = "success";
+ if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
+ error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
+ return error;
+ } else {
+ error = "success";
+ }
+ return error;
+ }
+
+ public String validateEmailAddress(String emailAddressValue) {
+ String error = "success";
+ List<String> emailList = Arrays.asList(emailAddressValue.toString().split(","));
+ for(int i =0 ; i < emailList.size() ; i++){
+ pattern = Pattern.compile(EMAIL_PATTERN);
+ matcher = pattern.matcher(emailList.get(i).trim());
+ if(!matcher.matches()){
+ error = "Please check the Following Email Address is not Valid .... " +emailList.get(i).toString();
+ return error;
+ }else{
+ error = "success";
+ }
+ }
+ return error;
+ }
+
+ protected String emailValidation(String email, String responseString){
+ if(email != null){
+ String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
+ if(!validateEmail.contains("success")){
+ responseString = responseString + "<b>Email</b>:<i>" + validateEmail+ "</i><br>";
+ }else{
+ return "success";
+ }
+ }
+ return responseString;
+ }
+
+ private MicroServiceModels getAttributeObject(String name, String version) {
+ MicroServiceModels workingModel = new MicroServiceModels();
+ List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
+ if(microServiceModelsData != null){
+ workingModel = (MicroServiceModels) microServiceModelsData.get(0);
+ }
+ return workingModel;
+ }
+
+ private void pullJsonKeyPairs(JsonNode rootNode) {
+ Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
+
+ while (fieldsIterator.hasNext()) {
+ Map.Entry<String, JsonNode> field = fieldsIterator.next();
+ final String key = field.getKey();
+ final JsonNode value = field.getValue();
+ if (value.isContainerNode() && !value.isArray()) {
+ pullJsonKeyPairs(value); // RECURSIVE CALL
+ } else {
+ if (value.isArray()){
+ String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
+ mapAttribute.put(key, newValue);
+ }else {
+ mapAttribute.put(key, value.toString().trim());
+ }
+ }
+ }
+ }
+
+ private Boolean isType(String testStr) {
+ try {
+ Integer.parseInt(testStr);
+ return true;
+ } catch(Exception e) {
+ return false;
+ }
+ }
+
+ // Validation for json.
+ protected static boolean isJSONValid(String data) {
+ try {
+ new JSONObject(data);
+ InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
+ JsonReader jsonReader = Json.createReader(stream);
+ System.out.println("Json Value is: " + jsonReader.read().toString() );
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
+ return true;
+ }
+
+ // Validation for XML.
+ private boolean isXMLValid(String data) {
+ SAXParserFactory factory = SAXParserFactory.newInstance();
+ factory.setValidating(false);
+ factory.setNamespaceAware(true);
+ try {
+ SAXParser parser = factory.newSAXParser();
+ XMLReader reader = parser.getXMLReader();
+ reader.setErrorHandler(new XMLErrorHandler());
+ reader.parse(new InputSource(new StringReader(data)));
+ } catch (ParserConfigurationException e) {
+ return false;
+ } catch (SAXException e) {
+ return false;
+ } catch (IOException e) {
+ return false;
+ }
+ return true;
+ }
+
+ // Validation for Properties file.
+ public boolean isPropValid(String prop) {
+ Scanner scanner = new Scanner(prop);
+ while (scanner.hasNextLine()) {
+ String line = scanner.nextLine();
+ line.replaceAll("\\s+", "");
+ if (line.startsWith("#")) {
+ continue;
+ } else {
+ if (line.contains("=")) {
+ String[] parts = line.split("=");
+ if (parts.length < 2) {
+ scanner.close();
+ return false;
+ }
+ } else {
+ scanner.close();
+ return false;
+ }
+ }
+ }
+ scanner.close();
+ return true;
+ }
+
+}