aboutsummaryrefslogtreecommitdiffstats
path: root/POLICY-SDK-APP/src/main/java/org/onap/policy/controller
diff options
context:
space:
mode:
Diffstat (limited to 'POLICY-SDK-APP/src/main/java/org/onap/policy/controller')
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java268
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java119
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java377
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java551
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java172
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java709
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java208
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java1622
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java929
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java163
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java430
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java361
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java394
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java696
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java384
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java122
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java167
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java776
18 files changed, 8448 insertions, 0 deletions
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
new file mode 100644
index 000000000..0a985045d
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
@@ -0,0 +1,268 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+
+@Controller
+@RequestMapping({"/"})
+public class ActionPolicyController extends RestrictedBaseController{
+ private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class);
+
+ public ActionPolicyController(){
+ //Default Constructor
+ }
+
+ private ArrayList<Object> attributeList;
+ protected LinkedList<Integer> ruleAlgoirthmTracker;
+ public static final String PERFORMER_ATTRIBUTEID = "performer";
+ protected Map<String, String> performer = new HashMap<>();
+ private ArrayList<Object> ruleAlgorithmList;
+
+ public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ attributeList = new ArrayList<>();
+ ruleAlgorithmList = new ArrayList<>();
+ 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 component at index 0.
+ Map<String, String> attribute = new HashMap<>();
+ 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<>();
+ // 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/onap/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java
new file mode 100644
index 000000000..820a1ebd9
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java
@@ -0,0 +1,119 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.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{
+
+ private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class);
+
+ private static CommonClassDao commonClassDao;
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ AdminTabController.commonClassDao = commonClassDao;
+ }
+
+ @Autowired
+ private AdminTabController(CommonClassDao commonClassDao){
+ AdminTabController.commonClassDao = commonClassDao;
+ }
+
+ public AdminTabController() {
+ //default constructor
+ }
+
+ @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<>();
+ 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){
+ LOGGER.error("Exception Occured"+e);
+ }
+ }
+
+ @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){
+ LOGGER.error("Exception Occured"+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/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java
new file mode 100644
index 000000000..f78a79c9c
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java
@@ -0,0 +1,377 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.model.PDPGroupContainer;
+import org.onap.policy.model.PDPPolicyContainer;
+import org.onap.policy.model.Roles;
+import org.onap.policy.rest.adapter.AutoPushTabAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.policy.rest.jpa.PolicyVersion;
+import org.onap.policy.xacml.api.XACMLErrorConstants;
+import org.onap.policy.xacml.api.pap.OnapPDPGroup;
+import org.onap.policy.xacml.std.pap.StdPDPGroup;
+import org.onap.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<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
+
+ private PDPPolicyContainer policyContainer;
+
+ private PolicyController policyController;
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
+
+ private List<Object> data;
+
+ public synchronized void refreshGroups() {
+ synchronized(this.groups) {
+ this.groups.clear();
+ try {
+ PolicyController controller = getPolicyControllerInstance();
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ } catch (PAPException e) {
+ String message = "Unable to retrieve Groups from server: " + e;
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
+ }
+
+ }
+ }
+
+ private PolicyController getPolicyControllerInstance(){
+ return policyController != null ? getPolicyController() : new PolicyController();
+ }
+
+ @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 = new ArrayList<Object>();
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ Map<String, Object> model = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
+ List<Object> userRoles = controller.getRoles(userId);
+ roles = new ArrayList<>();
+ scopes = new HashSet<>();
+ for(Object role: userRoles){
+ Roles userRole = (Roles) role;
+ roles.add(userRole.getRole());
+ if(userRole.getScope() != null){
+ if(userRole.getScope().contains(",")){
+ String[] multipleScopes = userRole.getScope().split(",");
+ for(int i =0; i < multipleScopes.length; i++){
+ scopes.add(multipleScopes[i]);
+ }
+ }else{
+ if(!userRole.getScope().equals("")){
+ scopes.add(userRole.getScope());
+ }
+ }
+ }
+ }
+ if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
+ data = commonClassDao.getData(PolicyVersion.class);
+ }else{
+ if(!scopes.isEmpty()){
+ for(String scope : scopes){
+ String query = "From PolicyVersion where policy_name like '"+scope+"%' and id > 0";
+ List<Object> filterdatas = commonClassDao.getDataByQuery(query);
+ if(filterdatas != null){
+ for(int i =0; i < filterdatas.size(); i++){
+ data.add(filterdatas.get(i));
+ }
+ }
+ }
+ }else{
+ PolicyVersion emptyPolicyName = new PolicyVersion();
+ emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
+ data.add(emptyPolicyName);
+ }
+ }
+ model.put("policydatas", mapper.writeValueAsString(data));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ logger.error("Exception Occured"+e);
+ }
+ }
+
+ @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<>();
+ ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
+ PolicyController controller = getPolicyControllerInstance();
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ ObjectMapper mapper = new ObjectMapper();
+ this.container = new PDPGroupContainer(controller.getPapEngine());
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
+ for (Object pdpGroupId : adapter.getPdpDatas()) {
+ LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
+ for(OnapPDPGroup 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<>();
+ Set<PDPPolicy> selectedPolicies = new HashSet<>();
+ 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_");
+ }
+ String[] split = dbCheckName.split(":");
+ String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
+ 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());
+ }
+ StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
+ if (selectedPolicy != null) {
+ // Add Current policies from container
+ for (OnapPDPGroup group : container.getGroups()) {
+ if (group.getId().equals(selectedGroup.getId())) {
+ currentPoliciesInGroup.addAll(group.getPolicies());
+ }
+ }
+ // copy policy to PAP
+ try {
+ controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
+ } catch (PAPException e) {
+ logger.error("Exception Occured"+e);
+ 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.setOnapPdps(pdpGroup.getOnapPdps());
+ 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 {
+ PolicyController controller = getPolicyControllerInstance();
+ this.container = new PDPGroupContainer(controller.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();
+ this.policyContainer.removeItem(data);
+ }
+ Set<PDPPolicy> changedPolicies = new HashSet<>();
+ changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds());
+ StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
+ updatedGroupObject.setPolicies(changedPolicies);
+ updatedGroupObject.setOnapPdps(group.getOnapPdps());
+ 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/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
new file mode 100644
index 000000000..3107950c9
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
@@ -0,0 +1,551 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.policy.controller;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.PrintWriter;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.BRMSParamTemplate;
+import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.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 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.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 CreateBRMSParamController extends RestrictedBaseController {
+ private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class);
+
+ private static CommonClassDao commonClassDao;
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ CreateBRMSParamController.commonClassDao = commonClassDao;
+ }
+
+ @Autowired
+ private CreateBRMSParamController(CommonClassDao commonClassDao){
+ CreateBRMSParamController.commonClassDao = commonClassDao;
+ }
+
+ public CreateBRMSParamController(){}
+ protected PolicyRestAdapter policyAdapter = null;
+
+ private HashMap<String, String> dynamicLayoutMap;
+
+ private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
+ private static String string = "String";
+
+
+ @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ dynamicLayoutMap = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", ""));
+ generateUI(rule);
+ response.setCharacterEncoding(PolicyController.getCharacterencoding());
+ response.setContentType(PolicyController.getContenttype());
+ request.setCharacterEncoding(PolicyController.getCharacterencoding());
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(dynamicLayoutMap);
+ JSONObject j = new JSONObject("{policyData: " + responseString + "}");
+ out.write(j.toString());
+ }catch(Exception e){
+ policyLogger.error("Exception Occured while getting BRMS Rule data" , e);
+ }
+ }
+
+ protected String findRule(String ruleTemplate) {
+ List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate);
+ if(datas != null && !datas.isEmpty()){
+ BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0);
+ return bRMSParamTemplate.getRule();
+ }
+ return null;
+ }
+
+ protected void generateUI(String rule) {
+ if(rule!=null){
+ try {
+ StringBuilder params = new StringBuilder("");
+ 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) {
+ policyLogger.info("Just for Logging"+e);
+ line = line.split("\\/\\*")[0];
+ }
+ } else {
+ line = line.split("\\/\\*")[0];
+ }
+ }
+ if (line.contains("*/")) {
+ comment = false;
+ try {
+ line = line.split("\\*\\/")[1].replace("*/", "");
+ } catch (Exception e) {
+ policyLogger.info("Just for Logging"+e);
+ line = "";
+ }
+ }
+ if (comment) {
+ continue;
+ }
+ if (flag) {
+ params.append(line);
+ }
+ if (line.contains("declare Params")) {
+ params.append(line);
+ flag = true;
+ }
+ if (line.contains("end") && flag) {
+ break;
+ }
+ }
+ params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
+ String[] components = params.toString().split(":");
+ String caption = "";
+ for (int i = 0; i < components.length; i++) {
+ String type = "";
+ if (i == 0) {
+ caption = components[i];
+ }
+ if("".equals(caption)){
+ break;
+ }
+ String nextComponent = "";
+ try {
+ nextComponent = components[i + 1];
+ } catch (Exception e) {
+ policyLogger.info("Just for Logging"+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) {
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
+ }
+ }
+ }
+
+ private void createField(String caption, String type) {
+ dynamicLayoutMap.put(caption, type);
+ }
+
+ /*
+ * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter.
+ * Which is used to bind the data in GUI
+ */
+ public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ dynamicLayoutMap = new HashMap<>();
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ // policy name value is the policy name without any prefix and
+ // Extensions.
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
+ if (policyLogger.isDebugEnabled()) {
+ policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
+ }
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ policyLogger.info("Just for Logging"+e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ setDataAdapterFromAdviceExpressions(policy, policyAdapter);
+ paramUIGenerate(policyAdapter, entity);
+ // Get the target data under policy.
+ policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
+ if(policyAdapter.getDynamicLayoutMap().size() > 0){
+ LinkedHashMap<String,String> drlRule = new LinkedHashMap<>();
+ for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
+ drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue));
+ }
+ policyAdapter.setRuleData(drlRule);
+ }
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ setDataToAdapterFromTarget(target, policyAdapter);
+ }
+ }
+ }
+
+ private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){
+ ArrayList<Object> attributeList = new ArrayList<>();
+ // 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 key = attributeAssignment.getAttributeId().replace("key:", "");
+ attribute.put("key", key);
+ @SuppressWarnings("unchecked")
+ 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<>(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);
+ }
+ }
+
+ private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){
+ // 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) {
+ setDataToAdapterFromMatchList(matchList, policyAdapter);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter){
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+
+ if ("RiskType".equals(attributeId)){
+ policyAdapter.setRiskType(value);
+ }
+ if ("RiskLevel".equals(attributeId)){
+ policyAdapter.setRiskLevel(value);
+ }
+ if ("guard".equals(attributeId)){
+ policyAdapter.setGuard(value);
+ }
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ }
+ }
+
+ 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
+ public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ String data = entity.getConfigurationData().getConfigBody();
+ if(data != null){
+ File file = new File(PolicyController.getConfigHome() +File.separator+ entity.getConfigurationData().getConfigurationName());
+ if(file.exists()){
+ try (BufferedReader br = new BufferedReader(new FileReader(file))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append("\n");
+ line = br.readLine();
+ }
+ }catch(Exception e){
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage() + e);
+ }
+ }
+ try {
+ StringBuilder params = new StringBuilder("");
+ Boolean flag = false;
+ Boolean comment = false;
+ for (String line : Files.readAllLines(Paths.get(file.toString()))) {
+ if (line.isEmpty() || line.startsWith("//")) {
+ continue;
+ }
+ if(line.contains(brmsTemplateVlaue)){
+ String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
+ value = value.replace(brmsTemplateVlaue, "");
+ policyAdapter.setRuleName(value);
+ }
+ if (line.startsWith("/*")) {
+ comment = true;
+ continue;
+ }
+ if ((line.contains("//"))&&(!(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) {
+ policyLogger.info("Just for Logging"+e);
+ line = line.split("\\/\\*")[0];
+ }
+ } else {
+ line = line.split("\\/\\*")[0];
+ }
+ }
+ if (line.contains("*/")) {
+ comment = false;
+ try {
+ line = line.split("\\*\\/")[1]
+ .replace("*/", "");
+ } catch (Exception e) {
+ policyLogger.info("Just for Logging"+e);
+ line = "";
+ }
+ }
+ if (comment) {
+ continue;
+ }
+ if (flag) {
+ params.append(line);
+ }
+ if (line.contains("rule") && line.contains(".Params\"")) {
+ params.append(line);
+ flag = true;
+ }
+ if (line.contains("end") && flag) {
+ break;
+ }
+ }
+ params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8));
+ params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
+ .replace("insert(params);end", "")
+ .replace("params.set", ""));
+ String[] components = params.toString().split("\\);");
+ if(components!= null && components.length > 0){
+ for (int i = 0; i < components.length; i++) {
+ String value = null;
+ components[i] = components[i]+")";
+ 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) {
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
+ }
+ }
+
+ }
+
+ // set View Rule
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void setViewRule(HttpServletRequest request, HttpServletResponse response){
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
+ policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
+ if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){
+ policyData.setEditPolicy(true);
+ }
+
+ String body = "";
+
+ body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
+ brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
+ body = body + findRule((String) policyData.getRuleName()) + "\n";
+ StringBuilder generatedRule = new StringBuilder();
+ generatedRule.append("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 (string.equals(keyValue)) {
+ generatedRule.append("\n\t\tparams.set"
+ + key + "(\""
+ + policyData.getRuleData().get(keyValue).toString() + "\");");
+ } else {
+ generatedRule.append("\n\t\tparams.set"
+ + key + "("
+ + policyData.getRuleData().get(keyValue).toString() + ");");
+ }
+ }
+ }
+ generatedRule.append("\n\t\tinsert(params);\nend");
+ policyLogger.info("New rule generated with :" + generatedRule.toString());
+ body = body + generatedRule.toString();
+ // 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());
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ }
+ }
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
new file mode 100644
index 000000000..9851d3165
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
@@ -0,0 +1,172 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.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){
+ logger.info("Not able to see the createdby in description. So, add generic description", 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 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();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+
+ if (attributeId.equals("RiskType")){
+ policyAdapter.setRiskType(value);
+ }
+ if (attributeId.equals("RiskLevel")){
+ policyAdapter.setRiskLevel(value);
+ }
+ if (attributeId.equals("guard")){
+ policyAdapter.setGuard(value);
+ }
+ if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ 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/onap/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
new file mode 100644
index 000000000..a7ce45ec4
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
@@ -0,0 +1,709 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
+import org.onap.policy.rest.adapter.ClosedLoopFaultTriggerUISignatures;
+import org.onap.policy.rest.adapter.ClosedLoopSignatures;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.OnapName;
+import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.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.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.TargetType;
+
+@Controller
+@RequestMapping("/")
+public class CreateClosedLoopFaultController extends RestrictedBaseController{
+
+ private static final Logger policyLogger = FlexLogger.getLogger(CreateClosedLoopFaultController.class);
+
+ 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){
+ try{
+ 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<>();
+ if(trapDatas.getTrap1() != null){
+ trapSignatureDatas.add(trapDatas);
+ }
+ ArrayList<Object> faultSignatureDatas = new ArrayList<>();
+ 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);
+
+ }catch(Exception e){
+ policyLogger.error("Exception Occured while setting data to Adapter" , e);
+ }
+ 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){
+ policyLogger.info("General error" , 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){
+ policyLogger.info("General error" , e);
+ }
+ try{
+ String operatorBox = connectTraps.get("operatorBox");
+ resultBody = resultBody + operatorBox +"(";
+ }catch (NullPointerException e){
+ policyLogger.info("General error" , 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){
+ policyLogger.info("General error" , e);
+ }
+ try{
+ String trapCount2 = connectTraps.get("trapCount2");
+ resultBody = resultBody + ", Time = " + trapCount2 + ")";
+ }catch(NullPointerException e){
+ policyLogger.info("General error" , 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();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+
+ // First match in the target is OnapName, so set that value.
+ if (attributeId.equals("ONAPName")) {
+ policyAdapter.setOnapName(value);
+ OnapName onapName = new OnapName();
+ onapName.setOnapName(value);
+ policyAdapter.setOnapNameField(onapName);
+ }
+ if (attributeId.equals("RiskType")){
+ policyAdapter.setRiskType(value);
+ }
+ if (attributeId.equals("RiskLevel")){
+ policyAdapter.setRiskLevel(value);
+ }
+ if (attributeId.equals("guard")){
+ policyAdapter.setGuard(value);
+ }
+ if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ 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) {
+ policyLogger.error("Exception Occured"+e);
+ }
+
+ 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/onap/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java
new file mode 100644
index 000000000..a4d6014c9
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java
@@ -0,0 +1,208 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.onap.policy.admin.PolicyManagerServlet;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.ClosedLoopPMBody;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.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.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.TargetType;
+
+public class CreateClosedLoopPMController{
+
+ private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPMController.class);
+
+ 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){
+ LOGGER.info("General error" , e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (matchList.size()>1 && iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+
+ // First match in the target is OnapName, so set that value.
+ if (attributeId.equals("ONAPName")) {
+ policyAdapter.setOnapName(value);
+ }
+ if (attributeId.equals("RiskType")){
+ policyAdapter.setRiskType(value);
+ }
+ if (attributeId.equals("RiskLevel")){
+ policyAdapter.setRiskLevel(value);
+ }
+ if (attributeId.equals("guard")){
+ policyAdapter.setGuard(value);
+ }
+ if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ if (attributeId.equals("ServiceType")){
+ 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);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ 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) {
+ LOGGER.error("Exception Occured"+e);
+ }
+ }
+
+ //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/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
new file mode 100644
index 000000000..609a45c20
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
@@ -0,0 +1,1622 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.policy.controller;
+
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.GroupPolicyScopeList;
+import org.onap.policy.rest.jpa.MicroServiceModels;
+import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.policy.rest.util.MSAttributeObject;
+import org.onap.policy.rest.util.MSModelUtils;
+import org.onap.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 org.yaml.snakeyaml.Yaml;
+
+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.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.TargetType;
+
+@Controller
+@RequestMapping("/")
+public class CreateDcaeMicroServiceController extends RestrictedBaseController {
+ private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
+
+ private static CommonClassDao commonClassDao;
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
+ }
+
+ private MicroServiceModels newModel;
+ private String newFile;
+ private String directory;
+ private List<String> modelList = new ArrayList<>();
+ private List<String> dirDependencyList = new ArrayList<>();
+ private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
+ //Tosca Model related Datastructure.
+ String referenceAttributes;
+ String attributeString;
+ String listConstraints;
+ String subAttributeString;
+ HashMap<String, Object> retmap = new HashMap<>();
+ Set<String> uniqueKeys= new HashSet<>();
+ Set<String> uniqueDataKeys= new HashSet<>();
+ StringBuilder dataListBuffer=new StringBuilder();
+ List<String> dataConstraints= new ArrayList <>();
+
+ public static final String DATATYPE = "data_types.policy.data.";
+ public static final String PROPERTIES=".properties.";
+ public static final String TYPE=".type";
+ public static final String STRING="string";
+ public static final String INTEGER="integer";
+ public static final String LIST="list";
+ public static final String DEFAULT=".default";
+ public static final String REQUIRED=".required";
+ public static final String MANYFALSE=":MANY-false";
+
+
+ @Autowired
+ private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){
+ CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
+ }
+
+ public CreateDcaeMicroServiceController(){}
+
+ protected PolicyRestAdapter policyAdapter = null;
+ private int priorityCount;
+ private Map<String, String> attributesListRefMap = new HashMap<>();
+ private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
+
+ 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", e);
+ }
+
+ 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", e);
+ }
+ LOGGER.info(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",e);
+ }
+ return cleanJson;
+ }
+
+ // Second index of dot should be returned.
+ public int stringBetweenDots(String str){
+ String stringToSearch=str;
+ String[]ss=stringToSearch.split("\\.");
+ if(ss!=null){
+ int len= ss.length;
+ if(len>2){
+ uniqueKeys.add(ss[2]);
+ }
+ }
+
+ return uniqueKeys.size();
+ }
+
+ public void stringBetweenDotsForDataFields(String str){
+ String stringToSearch=str;
+ String[]ss=stringToSearch.split("\\.");
+ if(ss!=null){
+ int len= ss.length;
+
+ if(len>2){
+ uniqueDataKeys.add(ss[0]+"%"+ss[2]);
+ }
+ }
+ }
+
+
+ public Map<String, String> load(String fileName) throws IOException {
+ File newConfiguration = new File(fileName);
+ InputStream is = null;
+ try {
+ is = new FileInputStream(newConfiguration);
+ } catch (FileNotFoundException e) {
+ LOGGER.error(e);
+ }
+
+ Yaml yaml = new Yaml();
+ @SuppressWarnings("unchecked")
+ Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(is);
+ StringBuilder sb = new StringBuilder();
+ Map<String, String> settings = new HashMap<>();
+ if (yamlMap == null) {
+ return settings;
+ }
+ List<String> path = new ArrayList <>();
+ serializeMap(settings, sb, path, yamlMap);
+ return settings;
+ }
+
+ public Map<String, String> load(byte[] source) throws IOException {
+ Yaml yaml = new Yaml();
+ @SuppressWarnings("unchecked")
+ Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(Arrays.toString(source));
+ StringBuilder sb = new StringBuilder();
+ Map<String, String> settings = new HashMap <>();
+ if (yamlMap == null) {
+ return settings;
+ }
+ List<String> path = new ArrayList <>();
+ serializeMap(settings, sb, path, yamlMap);
+ return settings;
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ private void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) {
+ for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
+ if (entry.getValue() instanceof Map) {
+ path.add((String) entry.getKey());
+ serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
+ path.remove(path.size() - 1);
+ } else if (entry.getValue() instanceof List) {
+ path.add((String) entry.getKey());
+ serializeList(settings, sb, path, (List) entry.getValue());
+ path.remove(path.size() - 1);
+ } else {
+ serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) {
+ int counter = 0;
+ for (Object listEle : yamlList) {
+ if (listEle instanceof Map) {
+ path.add(Integer.toString(counter));
+ serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
+ path.remove(path.size() - 1);
+ } else if (listEle instanceof List) {
+ path.add(Integer.toString(counter));
+ serializeList(settings, sb, path, (List<String>) listEle);
+ path.remove(path.size() - 1);
+ } else {
+ serializeValue(settings, sb, path, Integer.toString(counter), listEle);
+ }
+ counter++;
+ }
+ }
+
+ private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) {
+ if (value == null) {
+ return;
+ }
+ sb.setLength(0);
+ for (String pathEle : path) {
+ sb.append(pathEle).append('.');
+ }
+ sb.append(name);
+ settings.put(sb.toString(), value.toString());
+ }
+
+ void parseDataAndPolicyNodes(Map<String,String> map){
+ for(String key:map.keySet()){
+ if(key.contains("policy.nodes.Root"))
+ {
+ continue;
+ }
+ else if(key.contains("policy.nodes")){
+ String wordToFind = "policy.nodes.";
+ int indexForPolicyNode=key.indexOf(wordToFind);
+ String subNodeString= key.substring(indexForPolicyNode+13, key.length());
+
+ stringBetweenDots(subNodeString);
+ }
+ else if(key.contains("policy.data")){
+ String wordToFind="policy.data.";
+ int indexForPolicyNode=key.indexOf(wordToFind);
+ String subNodeString= key.substring(indexForPolicyNode+12, key.length());
+
+ stringBetweenDotsForDataFields(subNodeString);
+ }
+ }
+ }
+
+ HashMap<String,String> parseDataNodes(Map<String,String> map){
+ HashMap<String,String> dataMapForJson=new HashMap <>();
+ for(String uniqueDataKey: uniqueDataKeys){
+ if(uniqueDataKey.contains("%")){
+ String[] uniqueDataKeySplit= uniqueDataKey.split("%");
+ String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE;
+ String typeValue=map.get(findType);
+ LOGGER.info(typeValue);
+ if(typeValue.equalsIgnoreCase(STRING)||
+ typeValue.equalsIgnoreCase(INTEGER)
+ )
+ {
+ String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT;
+ String defaultValue= map.get(findDefault);
+ LOGGER.info("defaultValue is:"+ defaultValue);
+
+ String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED;
+ String requiredValue= map.get(findRequired);
+ LOGGER.info("requiredValue is:"+ requiredValue);
+
+ StringBuilder attributeIndividualStringBuilder= new StringBuilder();
+ attributeIndividualStringBuilder.append(typeValue+":defaultValue-");
+ attributeIndividualStringBuilder.append(defaultValue+":required-");
+ attributeIndividualStringBuilder.append(requiredValue+MANYFALSE);
+ dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());
+ }
+ else if(typeValue.equalsIgnoreCase(LIST)){
+ String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type";
+ String listValue=map.get(findList);
+ if(listValue!=null){
+ LOGGER.info("Type of list is:"+ listValue);
+ //Its userdefined
+ if(listValue.contains(".")){
+ String trimValue=listValue.substring(listValue.lastIndexOf('.')+1);
+ StringBuilder referenceIndividualStringBuilder= new StringBuilder();
+ referenceIndividualStringBuilder.append(trimValue+":MANY-true");
+ dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
+ }//Its string
+ else{
+ StringBuilder stringListItems= new StringBuilder();
+ stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false");
+ dataMapForJson.put(uniqueDataKey, stringListItems.toString());
+ dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=[");
+ for(int i=0;i<10;i++){
+ String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i;
+ String constraintsValue=map.get(findConstraints);
+ LOGGER.info(constraintsValue);
+ if(constraintsValue==null){
+ break;
+ }
+ else{
+ dataConstraints.add(constraintsValue);
+ dataListBuffer.append(constraintsValue+",");
+ }
+ }
+ dataListBuffer.append("]#");
+
+ LOGGER.info(dataListBuffer);
+ }
+ }
+ }
+ else{
+ String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type";
+ String userDefinedValue=map.get(findUserDefined);
+ String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1);
+ StringBuilder referenceIndividualStringBuilder= new StringBuilder();
+ referenceIndividualStringBuilder.append(trimValue+":MANY-false");
+ dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString());
+
+ }
+ }
+ }
+ return dataMapForJson;
+ }
+
+ void constructJsonForDataFields(HashMap<String,String> dataMapForJson){
+ HashMap<String,HashMap<String,String>> dataMapKey= new HashMap <>();
+ HashMap<String,String> hmSub;
+ for(Map.Entry<String, String> entry: dataMapForJson.entrySet()){
+ String uniqueDataKey= entry.getKey();
+ String[] uniqueDataKeySplit=uniqueDataKey.split("%");
+ String value= dataMapForJson.get(uniqueDataKey);
+ if(dataMapKey.containsKey(uniqueDataKeySplit[0])){
+ hmSub = dataMapKey.get(uniqueDataKeySplit[0]);
+ hmSub.put(uniqueDataKeySplit[1], value);
+ }
+ else{
+ hmSub=new HashMap <>();
+ hmSub.put(uniqueDataKeySplit[1], value);
+ }
+
+ dataMapKey.put(uniqueDataKeySplit[0], hmSub);
+ }
+
+ JSONObject mainObject= new JSONObject();
+ JSONObject json;
+ for(Map.Entry<String,HashMap<String,String>> entry: dataMapKey.entrySet()){
+ String s=entry.getKey();
+ json= new JSONObject();
+ HashMap<String,String> jsonHm=dataMapKey.get(s);
+ for(Map.Entry<String,String> entryMap:jsonHm.entrySet()){
+ String key=entryMap.getKey();
+ json.put(key, jsonHm.get(key));
+ }
+ mainObject.put(s,json);
+ }
+ Iterator<String> keysItr = mainObject.keys();
+ while(keysItr.hasNext()) {
+ String key = keysItr.next();
+ String value = mainObject.get(key).toString();
+ retmap.put(key, value);
+ }
+
+ LOGGER.info("#############################################################################");
+ LOGGER.info(mainObject);
+ LOGGER.info("###############################################################################");
+ }
+
+
+ HashMap<String,HashMap<String,String>> parsePolicyNodes(Map<String,String> map){
+ HashMap<String,HashMap<String,String>> mapKey= new HashMap <>();
+ for(String uniqueKey: uniqueKeys){
+ HashMap<String,String> hm;
+
+ for(Map.Entry<String,String> entry:map.entrySet()){
+ String key=entry.getKey();
+ if(key.contains(uniqueKey) && key.contains("policy.nodes")){
+ if(mapKey.containsKey(uniqueKey)){
+ hm = mapKey.get(uniqueKey);
+ String keyStr= key.substring(key.lastIndexOf('.')+1);
+ String valueStr= map.get(key);
+ if(("type").equals(keyStr)){
+ if(!key.contains("entry_schema"))
+ {
+ hm.put(keyStr,valueStr);
+ }
+ }else{
+ hm.put(keyStr,valueStr);
+ }
+
+ } else {
+ hm = new HashMap <>();
+ String keyStr= key.substring(key.lastIndexOf('.')+1);
+ String valueStr= map.get(key);
+ if(("type").equals(keyStr)){
+ if(!key.contains("entry_schema"))
+ {
+ hm.put(keyStr,valueStr);
+ }
+ }else{
+ hm.put(keyStr,valueStr);
+ }
+ mapKey.put(uniqueKey, hm);
+ }
+ }
+ }
+ }
+ return mapKey;
+ }
+
+ void createAttributes(HashMap<String,HashMap<String,String>> mapKey){
+ StringBuilder attributeStringBuilder= new StringBuilder();
+ StringBuilder referenceStringBuilder= new StringBuilder();
+ StringBuilder listBuffer= new StringBuilder();
+ List<String> constraints= new ArrayList<>();
+ for(Map.Entry<String,HashMap<String,String>> entry: mapKey.entrySet()){
+ String keySetString= entry.getKey();
+ HashMap<String,String> keyValues=mapKey.get(keySetString);
+ if(keyValues.get("type").equalsIgnoreCase(STRING)||
+ keyValues.get("type").equalsIgnoreCase(INTEGER)
+ ){
+ StringBuilder attributeIndividualStringBuilder= new StringBuilder();
+ attributeIndividualStringBuilder.append(keySetString+"=");
+ attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-");
+ attributeIndividualStringBuilder.append(keyValues.get("default")+":required-");
+ attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false");
+ attributeStringBuilder.append(attributeIndividualStringBuilder+",");
+
+ }
+ else if(keyValues.get("type").equalsIgnoreCase(LIST)){
+ //List Datatype
+ Set<String> keys= keyValues.keySet();
+ Iterator<String> itr=keys.iterator();
+ while(itr.hasNext()){
+ String key= itr.next();
+ if((!("type").equals(key) ||("required").equals(key)))
+ {
+ String value= keyValues.get(key);
+ //The "." in the value determines if its a string or a user defined type.
+ if (!value.contains(".")){
+ //This is string
+ constraints.add(keyValues.get(key));
+ }else{
+ //This is userdefined string
+ String trimValue=value.substring(value.lastIndexOf('.')+1);
+ StringBuilder referenceIndividualStringBuilder= new StringBuilder();
+ referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true");
+ referenceStringBuilder.append(referenceIndividualStringBuilder+",");
+ }
+ }
+ }
+
+ }else{
+ //User defined Datatype.
+ String value=keyValues.get("type");
+ String trimValue=value.substring(value.lastIndexOf('.')+1);
+ StringBuilder referenceIndividualStringBuilder= new StringBuilder();
+ referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false");
+ referenceStringBuilder.append(referenceIndividualStringBuilder+",");
+
+ }
+ if(constraints!=null &&constraints.isEmpty()==false){
+ //List handling.
+ listBuffer.append(keySetString.toUpperCase()+"=[");
+ for(String str:constraints){
+ listBuffer.append(str+",");
+ }
+ listBuffer.append("]#");
+ LOGGER.info(listBuffer);
+
+
+ StringBuilder referenceIndividualStringBuilder= new StringBuilder();
+ referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false");
+ referenceStringBuilder.append(referenceIndividualStringBuilder+",");
+ constraints.clear();
+ }
+ }
+
+ dataListBuffer.append(listBuffer);
+
+
+ LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
+ LOGGER.info("Whole attribute String is:"+attributeStringBuilder);
+ LOGGER.info("Whole reference String is:"+referenceStringBuilder);
+ LOGGER.info("List String is:"+listBuffer);
+ LOGGER.info("Data list buffer is:"+dataListBuffer);
+ LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
+
+ this.listConstraints=dataListBuffer.toString();
+ this.referenceAttributes=referenceStringBuilder.toString();
+ this.attributeString=attributeStringBuilder.toString();
+ }
+
+
+
+ public void parseTosca (String fileName){
+ Map<String,String> map= new HashMap<>();
+
+ try {
+ map=load(fileName);
+
+ parseDataAndPolicyNodes(map);
+
+ HashMap<String,String> dataMapForJson=parseDataNodes(map);
+
+ constructJsonForDataFields(dataMapForJson);
+
+ HashMap<String,HashMap<String,String>> mapKey= parsePolicyNodes(map);
+
+ createAttributes(mapKey);
+
+ } catch (IOException e) {
+ LOGGER.error(e);
+ }
+
+ }
+
+ private String cleanUPJson(String json) {
+ String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
+ 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<>();
+ 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.
+ LOGGER.info(key+"\n");
+ if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
+ if(!oldValue.equals(key.substring(0,key.indexOf("@")))){
+ jsonResult.put(oldValue, jsonArray);
+ 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(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
+ jsonArray.put(decodeContent(node));
+ }
+ if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))) || !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(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
+ jsonArray.put(decodeContent(node));
+ }
+ jsonResult.put(arryKey, jsonArray);
+ jsonArray = new JSONArray();
+ arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
+ }else{
+ isArray = false;
+ jsonResult.put(nodeKey, decodeContent(node));
+ }
+ node = nodeFactory.objectNode();
+ if(key.contains("@")){
+ isArray = true;
+ if(key.endsWith("@0")|| jsonArray==null){
+ 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", "rawtypes" })
+ private String createMicroSeriveJson(MicroServiceModels returnModel) {
+ Map<String, String> attributeMap = new HashMap<>();
+ Map<String, String> refAttributeMap = new HashMap<>();
+ 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<>();
+ 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<>();
+ 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<>();
+ ObjectMapper mapper = new ObjectMapper();
+ List<String> priorityList = new ArrayList<>();
+ 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){
+ LOGGER.error(e);
+ }
+ }
+
+ 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) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (matchList.size()>1 && iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ if (attributeId.equals("ONAPName")) {
+ policyAdapter.setOnapName(value);
+ }
+ if (attributeId.equals("ConfigName")){
+ policyAdapter.setConfigName(value);
+ }
+ if (attributeId.equals("uuid")){
+ policyAdapter.setUuid(value);
+ }
+ if (attributeId.equals("location")){
+ policyAdapter.setLocation(value);
+ }
+ if (attributeId.equals("RiskType")){
+ policyAdapter.setRiskType(value);
+ }
+ if (attributeId.equals("RiskLevel")){
+ policyAdapter.setRiskLevel(value);
+ }
+ if (attributeId.equals("guard")){
+ policyAdapter.setGuard(value);
+ }
+ if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ }
+ readFile(policyAdapter, entity);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ 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<>();
+ 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<>();
+ LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
+ readRecursivlyJSONContent(map, data);
+ policyAdapter.setRuleData(data);
+ }
+
+ } catch (Exception e) {
+ LOGGER.error(e);
+ }
+
+ }
+
+ @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<>();
+ 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<>();
+ 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) {
+ List<Object> groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
+ if(groupList != null && !groupList.isEmpty()){
+ GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
+ return pScope.getGroupName();
+ }
+ return null;
+ }
+
+ //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 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;
+ boolean yml= false;
+ for (FileItem item : items) {
+ if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
+ 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 if(item.getName().endsWith(".yml")){
+ this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", ""));
+ yml = true;
+ }
+ else {
+ this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", ""));
+ }
+ }
+
+ }catch(Exception e){
+ LOGGER.error("Upload error : " + e);
+ }
+ }
+
+ }
+ List<File> fileList = new ArrayList<>();;
+ this.directory = "model";
+ if (zip){
+ extractFolder(this.newFile);
+ fileList = listModelFiles(this.directory);
+ }else if (yml==true){
+ parseTosca(this.newFile);
+ }else {
+ File file = new File(this.newFile);
+ fileList.add(file);
+ }
+ String modelType= "";
+ if(yml==false){
+ modelType="xmi";
+ //Process Main Model file first
+ classMap = new HashMap<>();
+ for (File file : fileList) {
+ if(!file.isDirectory() && file.getName().endsWith(".xmi")){
+ retreiveDependency(file.toString(), true);
+ }
+ }
+
+ modelList = createList();
+
+ cleanUp(this.newFile);
+ cleanUp(directory);
+ }else{
+ modelType="yml";
+ modelList.add(this.newModel.getModelName());
+ String className=this.newModel.getModelName();
+ MSAttributeObject msAttributes= new MSAttributeObject();
+ msAttributes.setClassName(className);
+
+ HashMap<String, String> returnAttributeList =new HashMap<>();
+ returnAttributeList.put(className, this.attributeString);
+ msAttributes.setAttribute(returnAttributeList);
+
+ msAttributes.setSubClass(this.retmap);
+
+ HashMap<String, String> returnReferenceList =new HashMap<>();
+ //String[] referenceArray=this.referenceAttributes.split("=");
+ returnReferenceList.put(className, this.referenceAttributes);
+ msAttributes.setRefAttribute(returnReferenceList);
+
+ if(this.listConstraints!=""){
+ HashMap<String, String> enumList =new HashMap<>();
+ String[] listArray=this.listConstraints.split("#");
+ for(String str:listArray){
+ String[] strArr= str.split("=");
+ if(strArr.length>1){
+ enumList.put(strArr[0], strArr[1]);
+ }
+ }
+ msAttributes.setEnumType(enumList);
+ }
+
+ classMap=new HashMap<>();
+ classMap.put(className, msAttributes);
+
+ }
+
+ PrintWriter out = response.getWriter();
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ ObjectMapper mapper = new ObjectMapper();
+ JSONObject j = new JSONObject();
+ j.put("classListDatas", modelList);
+ j.put("modelDatas", mapper.writeValueAsString(classMap));
+ j.put("modelType", modelType);
+ 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 = null;
+ 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);
+ }finally{
+ try {
+ if(zip != null)
+ zip.close();
+ } catch (IOException e) {
+ LOGGER.error("Exception Occured While closing zipfile " + e);
+ }
+ }
+ }
+
+ private void retreiveDependency(String workingFile, Boolean modelClass) {
+
+ MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
+ HashMap<String, MSAttributeObject> tempMap = new HashMap<>();
+
+ tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
+
+ classMap.putAll(tempMap);
+ LOGGER.info(tempMap);
+
+ return;
+
+ }
+
+ private List<File> listModelFiles(String directoryName) {
+ File directory = new File(directoryName);
+ List<File> resultList = new ArrayList<>();
+ 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<>();
+ 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;
+ }
+
+ public Map<String, String> getAttributesListRefMap() {
+ return attributesListRefMap;
+ }
+
+ public Map<String, LinkedList<String>> getArrayTextList() {
+ return arrayTextList;
+ }
+
+}
+
+class DCAEMicroServiceObject {
+
+ private String service;
+ private String location;
+ private String uuid;
+ private String policyName;
+ private String description;
+ private String configName;
+ private String templateVersion;
+ private String version;
+ private String priority;
+ private String policyScope;
+ private String riskType;
+ private String riskLevel;
+ private 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/onap/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java
new file mode 100644
index 000000000..828bc3886
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java
@@ -0,0 +1,929 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.policy.controller;
+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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.AddressGroupJson;
+import org.onap.policy.rest.adapter.AddressJson;
+import org.onap.policy.rest.adapter.AddressMembers;
+import org.onap.policy.rest.adapter.DeployNowJson;
+import org.onap.policy.rest.adapter.IdMap;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.adapter.PrefixIPList;
+import org.onap.policy.rest.adapter.ServiceGroupJson;
+import org.onap.policy.rest.adapter.ServiceListJson;
+import org.onap.policy.rest.adapter.ServiceMembers;
+import org.onap.policy.rest.adapter.ServicesJson;
+import org.onap.policy.rest.adapter.TagDefines;
+import org.onap.policy.rest.adapter.Tags;
+import org.onap.policy.rest.adapter.Term;
+import org.onap.policy.rest.adapter.TermCollector;
+import org.onap.policy.rest.adapter.VendorSpecificData;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.AddressGroup;
+import org.onap.policy.rest.jpa.FWTagPicker;
+import org.onap.policy.rest.jpa.GroupServiceList;
+import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.policy.rest.jpa.PrefixList;
+import org.onap.policy.rest.jpa.SecurityZone;
+import org.onap.policy.rest.jpa.ServiceList;
+import org.onap.policy.rest.jpa.TermList;
+import org.onap.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 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.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.TargetType;
+
+@Controller
+@RequestMapping("/")
+public class CreateFirewallController extends RestrictedBaseController {
+ private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class);
+
+ @Autowired
+ SessionFactory sessionFactory;
+
+ private static CommonClassDao commonClassDao;
+
+ private List<String> tagCollectorList;
+ private String jsonBody;
+ List<String> expandablePrefixIPList = new ArrayList<>();
+ List<String> expandableServicesList= new ArrayList<>();
+ @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<>();
+ tagCollectorList = new ArrayList<>();
+ if(!policyData.getAttributes().isEmpty()){
+ 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) {
+ List <String> valueDesc= new ArrayList<>();
+ 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)) {
+ String value = prefixList.getPrefixListValue();
+ valueDesc.add(value);
+ String 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<>();
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ // policy name value is the policy name without any prefix and Extensions.
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") +3);
+ if (policyLogger.isDebugEnabled()) {
+ policyLogger.debug("Prepopulating form data for Config Policy selected:"+ policyAdapter.getPolicyName());
+ }
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try{
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ }catch(Exception e){
+ policyLogger.info("General error", e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+
+ 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) {
+ policyLogger.error("Exception Caused while Retriving the JSON body data" +e);
+ }
+
+ Map<String, String> termTagMap=null;
+ if(tc1 != 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) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ if (attributeId.equals("ConfigName")) {
+ policyAdapter.setConfigName(value);
+ }
+ if (attributeId.equals("RiskType")){
+ policyAdapter.setRiskType(value);
+ }
+ if (attributeId.equals("RiskLevel")){
+ policyAdapter.setRiskLevel(value);
+ }
+ if (attributeId.equals("guard")){
+ policyAdapter.setGuard(value);
+ }
+ if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ 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 void setFWViewRule(HttpServletRequest request, HttpServletResponse response){
+ try {
+ termCollectorList = new ArrayList<>();
+ 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().isEmpty()){
+ 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<>();
+ 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());
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ }
+ }
+
+ 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<>();
+ TermList jpaTermList;
+ TermCollector tc = new TermCollector();
+ SecurityZone jpaSecurityZone;
+ List<Term> termList = new ArrayList<>();
+
+ Tags tags=null;
+ List<Tags>tagsList= new ArrayList<>();
+
+ TagDefines tagDefine= new TagDefines();
+ List<TagDefines> tagList=null;
+ ServiceListJson targetSl=null;
+ int i=0;
+ try{
+ String networkRole="";
+ 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<>();
+ 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);
+
+ }
+ networkRole=jpaTagPickerList.getNetworkRole();
+ break;
+ }
+ }
+ tags.setTags(tagList);
+ tags.setTagPickerName(tag);
+ tags.setRuleName(termCollectorList.get(i));
+ tags.setNetworkRole(networkRole);
+ 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<>();
+ fromZone_map.put(tl, ruleFromZone);
+ }
+ ruleToZone=jpaTermList.getToZone();
+
+ if ((ruleToZone != null) && (!ruleToZone.isEmpty())){
+ toZone_map = new HashMap<>();
+ toZone_map.put(tl, ruleToZone);
+ }
+ ruleSrcPrefixList=jpaTermList.getSrcIPList();
+
+ if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())){
+ srcIP_map = new HashMap<>();
+ srcIP_map.put(tl, ruleSrcPrefixList);
+ }
+
+ ruleDestPrefixList= jpaTermList.getDestIPList();
+ if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())){
+ destIP_map = new HashMap<>();
+ destIP_map.put(tl, ruleDestPrefixList);
+ }
+
+ ruleSrcPort=jpaTermList.getSrcPortList();
+
+ if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())){
+ srcPort_map = new HashMap<>();
+ srcPort_map.put(tl, ruleSrcPort);
+ }
+
+ ruleDestPort= jpaTermList.getDestPortList();
+
+ if (ruleDestPort!= null && (!jpaTermList.getDestPortList().isEmpty())){
+ destPort_map = new HashMap<>();
+ destPort_map.put(tl, ruleDestPort);
+ }
+
+ ruleAction=jpaTermList.getAction();
+
+ if (( ruleAction!= null) && (!ruleAction.isEmpty())){
+ action_map = new HashMap<>();
+ 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<>();
+ 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<>();
+ 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<>();
+ 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<>();
+ 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<>();
+ 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());
+ IdMap idMapInstance= new IdMap();
+ idMapInstance.setAstraId(jpaSecurityZone.getZoneValue());
+ idMapInstance.setVendorId("deviceGroup:dev");
+
+ List<IdMap> idMap = new ArrayList<IdMap>();
+ idMap.add(idMapInstance);
+
+ VendorSpecificData vendorStructure= new VendorSpecificData();
+ vendorStructure.setIdMap(idMap);
+ tc.setVendorSpecificData(vendorStructure);
+ break;
+ }
+ }
+
+ tc.setServiceTypeId("/v0/firewall/pan");
+ tc.setConfigName(policyData.getConfigName());
+ tc.setVendorServiceId("vipr");
+
+ DeployNowJson deployNow= new DeployNowJson();
+ deployNow.setDeployNow(false);
+
+ tc.setDeploymentOption(deployNow);
+
+ Set<ServiceListJson> servListArray = new HashSet<>();
+ Set<ServiceGroupJson> servGroupArray= new HashSet<>();
+ Set<AddressGroupJson> addrGroupArray= new HashSet<>();
+
+ 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<>();
+
+ 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<>();
+ for(String prefixList:expandablePrefixIPList){
+ for(String prefixIP: prefixList.split(",")){
+ if((!prefixIP.startsWith("Group_"))){
+ if(!prefixIP.equals("ANY")){
+ List<AddressMembers> addMembersList= new ArrayList<>();
+ List<String> valueDesc= new ArrayList<>();
+ PrefixIPList targetAddressList = new PrefixIPList();
+ AddressMembers addressMembers= new AddressMembers();
+ targetAddressList.setName(prefixIP);
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:"+prefixIP);
+ valueDesc = mapping(prefixIP);
+ if(!valueDesc.isEmpty()){
+ policyLogger.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<>();
+ for(String groupString: ag.getPrefixList().split(",")){
+ List<String> valueDesc= new ArrayList<>();
+ 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<>();
+
+ for(Object obj1:servGroupArray){
+ serviceGroup.add(obj1);
+ }
+
+ for(Object obj:servListArray){
+ serviceGroup.add(obj);
+ }
+
+ Set<Object> addressGroup= new HashSet<>();
+
+ 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 (Exception e) {
+ policyLogger.error("Exception Occured"+e);
+ }
+
+ }catch (Exception e) {
+ policyLogger.error("Exception Occured"+e);
+ }
+
+ return json;
+ }
+
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
new file mode 100644
index 000000000..9c07876c1
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
@@ -0,0 +1,163 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.policy.controller;
+
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.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<>();
+ 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 attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ if (attributeId.equals("ONAPName")) {
+ policyAdapter.setOnapName(value);
+ }
+ if (attributeId.equals("RiskType")){
+ policyAdapter.setRiskType(value);
+ }
+ if (attributeId.equals("RiskLevel")){
+ policyAdapter.setRiskLevel(value);
+ }
+ if (attributeId.equals("guard")){
+ policyAdapter.setGuard(value);
+ }
+ if (attributeId.equals("TTLDate") && !value.contains("NA")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ if (attributeId.equals("ConfigName")){
+ policyAdapter.setConfigName(value);
+ }
+ // After Onap and Config it is optional to have attributes, so
+ // check weather dynamic values or there or not.
+ if (index >= 7) {
+ Map<String, String> attribute = new HashMap<>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ }
+ index++;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ policyAdapter.setAttributes(attributeList);
+ }
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ for (Object o : ruleList) {
+ if (o instanceof RuleType) {
+ // get the condition data under the rule for rule Algorithms.
+ policyAdapter.setRuleID(((RuleType) o).getRuleId());
+ }
+ }
+ }
+ }
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
new file mode 100644
index 000000000..d6d4a2c69
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
@@ -0,0 +1,430 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.onap.policy.dao.SystemLogDbDao;
+import org.onap.policy.model.PDPGroupContainer;
+import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
+import org.onap.policy.xacml.api.XACMLErrorConstants;
+import org.onap.policy.xacml.api.pap.OnapPDP;
+import org.onap.policy.xacml.api.pap.OnapPDPGroup;
+
+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 policyLogger = 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;
+
+ private PolicyController policyController;
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
+
+ private PolicyController getPolicyControllerInstance(){
+ return policyController != null ? getPolicyController() : new PolicyController();
+ }
+
+ @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<>();
+ 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){
+ policyLogger.error("Exception Occured"+e);
+ }
+ }
+
+ @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<>();
+ 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){
+ policyLogger.error("Exception Occured"+e);
+ }
+ }
+
+ @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<>();
+ 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){
+ policyLogger.error("Exception Occured"+e);
+ }
+ }
+
+ @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<>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
+ PolicyController controller = getPolicyControllerInstance();
+ this.pdpConatiner = new PDPGroupContainer(controller.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){
+ policyLogger.error("Exception Occured"+e);
+ }
+ }
+
+ @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<>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
+ PolicyController controller = getPolicyControllerInstance();
+ this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
+ addPolicyToTable();
+ model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ policyLogger.error("Exception Occured"+e);
+ }
+ }
+
+ /*
+ * Add the PAP information to the PAP Table
+ */
+ public void addPAPToTable(){
+ papStatusData = new ArrayList<>();
+ String papStatus = null;
+ try {
+ PolicyController controller = getPolicyControllerInstance();
+ Set<OnapPDPGroup> groups = controller.getPapEngine().getOnapPDPGroups();
+ if (groups == null) {
+ papStatus = "UNKNOWN";
+ throw new PAPException("PAP not running");
+ }else {
+ papStatus = "IS_OK";
+ }
+ } catch (PAPException | NullPointerException e1) {
+ papStatus = "CANNOT_CONNECT";
+ policyLogger.error("Error getting PAP status, PAP not responding to requests", e1);
+ }
+ 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<>();
+ long naCount;
+ long denyCount = 0;
+ long permitCount = 0;
+ for (PDPGroup group : this.pdpConatiner.getGroups()){
+ for (PDP pdp : group.getPdps()){
+ naCount = -1;
+ if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0){
+ String pdpIpAddress = parseIPSystem(pdp.getId());
+ int port = ((OnapPDP) pdp).getJmxPort();
+ if (port != 0){
+ policyLogger.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) {
+
+ policyLogger.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();
+ policyLogger.debug("pdpEvaluationNA value retreived: " + o);
+ return (long) o;
+ } catch (MalformedURLException e) {
+ policyLogger.error("MalformedURLException for JMX connection" , e);
+ } catch (IOException e) {
+ policyLogger.error("Error in reteriving" + jmxAttribute + " from JMX connection", e);
+ } catch (AttributeNotFoundException e) {
+ policyLogger.error("AttributeNotFoundException " + jmxAttribute + " for JMX connection", e);
+ } catch (InstanceNotFoundException e) {
+ policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e);
+ } catch (MalformedObjectNameException e) {
+ policyLogger.error("MalformedObjectNameException for JMX connection", e);
+ } catch (MBeanException e) {
+ policyLogger.error("MBeanException for JMX connection");
+ policyLogger.error("Exception Occured"+e);
+ } catch (ReflectionException e) {
+ policyLogger.error("ReflectionException for JMX connection", e);
+ }
+
+ 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<>();
+ 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){
+ policyLogger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+policy.getName() +e);
+ }
+ }
+
+ for (PDP pdp : group.getPdps()){
+ // Add rows to the Policy Table
+ policyList = null;
+ if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0){
+ String pdpIpAddress = parseIPSystem(pdp.getId());
+ policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort(), "policyCount");
+ }
+ 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(object);
+ }
+ }
+ }
+ }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(object);
+ }else{
+ JSONObject object = new JSONObject();
+ object.put("policyId", "Unable to access PDP JMX Server");
+ object.put("fireCount", "NA");
+ object.put("system", pdp.getId());
+ policyActivityData.add(object);
+ }
+ }
+ }
+ }
+ }
+
+ /*
+ * Contact JMX Connector Sever and return the list of {policy id , count}
+ */
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private Object getPolicy(String host, int port, String jmxAttribute){
+ policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
+ HashMap map = 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();
+ policyLogger.debug("policyMap value retreived: " + o);
+ return o;
+ } catch (MalformedURLException e) {
+ policyLogger.error("MalformedURLException for JMX connection" , e);
+ } catch (IOException e) {
+ policyLogger.error("AttributeNotFoundException for policyMap" , e);
+ } catch (AttributeNotFoundException e) {
+ policyLogger.error("AttributeNotFoundException for JMX connection", e);
+ } catch (InstanceNotFoundException e) {
+ policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e);
+ } catch (MalformedObjectNameException e) {
+ policyLogger.error("MalformedObjectNameException for JMX connection", e);
+ } catch (MBeanException e) {
+ policyLogger.error("MBeanException for JMX connection", e);
+ policyLogger.error("Exception Occured"+e);
+ } catch (ReflectionException e) {
+ policyLogger.error("ReflectionException for JMX connection", e);
+ }
+
+ 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/onap/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
new file mode 100644
index 000000000..45369ce2f
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
@@ -0,0 +1,361 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.policy.controller;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.adapter.RainyDayParams;
+import org.onap.policy.rest.adapter.YAMLParams;
+import org.onap.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.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.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 policyLogger = FlexLogger.getLogger(DecisionPolicyController.class);
+
+ public DecisionPolicyController(){}
+
+ protected PolicyRestAdapter policyAdapter = null;
+ private ArrayList<Object> attributeList;
+ private ArrayList<Object> decisionList;
+ private ArrayList<Object> ruleAlgorithmList;
+ private ArrayList<Object> treatmentList = null;
+ protected LinkedList<Integer> ruleAlgoirthmTracker;
+ public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
+
+ @SuppressWarnings("unchecked")
+ public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ attributeList = new ArrayList<>();
+ decisionList = new ArrayList<>();
+ ruleAlgorithmList = new ArrayList<>();
+ treatmentList = new ArrayList<>();
+
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ RainyDayParams rainydayParams = new RainyDayParams();
+ 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){
+ policyLogger.info("General error", e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy for Action.
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // 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 OnapName, so set that value.
+ if (attributeId.equals("ONAPName")) {
+ policyAdapter.setOnapName(value);
+ }
+ // Component attributes are saved under Target here we are fetching them back.
+ // One row is default so we are not adding dynamic component at index 0.
+ if (index >= 1) {
+ Map<String, String> attribute = new HashMap<>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ }
+ index++;
+ }
+ }
+ policyAdapter.setAttributes(attributeList);
+ }
+ }
+ }
+ // Setting rainy day attributes to the parameters object if they exist
+ boolean rainy = false;
+ if(!attributeList.isEmpty()) {
+ for(int i=0; i<attributeList.size() ; i++){
+ Map<String, String> map = (Map<String,String>)attributeList.get(i);
+ if(map.get("key").equals("WorkStep")){
+ rainydayParams.setWorkstep(map.get("value"));
+ rainy=true;
+ }else if(map.get("key").equals("BB_ID")){
+ rainydayParams.setBbid(map.get("value"));
+ rainy=true;
+ }else if(map.get("key").equals("ServiceType")){
+ rainydayParams.setServiceType(map.get("value"));
+ rainy=true;
+ }else if(map.get("key").equals("VNFType")){
+ rainydayParams.setVnfType(map.get("value"));
+ rainy=true;
+ }
+ }
+ }
+ if(rainy){
+ policyAdapter.setRuleProvider("Rainy_Day");
+ }
+ }
+
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ int index = 0;
+ for (Object object : ruleList) {
+ if (object instanceof VariableDefinitionType) {
+ VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
+ Map<String, String> settings = new HashMap<>();
+ settings.put("key", variableDefinitionType.getVariableId());
+ JAXBElement<AttributeValueType> attributeValueTypeElement = (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
+ if (attributeValueTypeElement != null) {
+ AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
+ settings.put("value", attributeValueType.getContent().get(0).toString());
+ }
+ decisionList.add(settings);
+ } else if (object instanceof RuleType) {
+ // get the condition data under the rule for rule Algorithms.
+ if(((RuleType) object).getEffect().equals(EffectType.DENY)) {
+ if(((RuleType) object).getAdviceExpressions()!=null){
+ if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("AAF")){
+ policyAdapter.setRuleProvider("AAF");
+ break;
+ }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_YAML")){
+ policyAdapter.setRuleProvider("GUARD_YAML");
+ }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_BL_YAML")){
+ policyAdapter.setRuleProvider("GUARD_BL_YAML");
+ }
+ }else{
+ policyAdapter.setRuleProvider("Custom");
+ }
+ ConditionType condition = ((RuleType) object).getCondition();
+ if (condition != null) {
+ ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
+ decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
+ ruleAlgoirthmTracker = new LinkedList<>();
+ if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals("GUARD_YAML")||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){
+ YAMLParams yamlParams = new YAMLParams();
+ for(int i=0; i<attributeList.size() ; i++){
+ Map<String, String> map = (Map<String,String>)attributeList.get(i);
+ if(map.get("key").equals("actor")){
+ yamlParams.setActor(map.get("value"));
+ }else if(map.get("key").equals("recipe")){
+ yamlParams.setRecipe(map.get("value"));
+ }else if(map.get("key").equals("targets")){
+ yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
+ }else if(map.get("key").equals("clname")){
+ yamlParams.setClname(map.get("value"));
+ }
+ }
+ ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue());
+ yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString());
+ yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString());
+ if(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")){
+ apply = (ApplyType)((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue()).getExpression().get(2).getValue();
+ Iterator<JAXBElement<?>> attributes = apply.getExpression().iterator();
+ List<String> blackList = new ArrayList<>();
+ while(attributes.hasNext()){
+ blackList.add(((AttributeValueType)attributes.next().getValue()).getContent().get(0).toString());
+ }
+ yamlParams.setBlackList(blackList);
+ }else{
+ ApplyType timeWindowSection = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue();
+ yamlParams.setLimit(((AttributeValueType)timeWindowSection.getExpression().get(1).getValue()).getContent().get(0).toString());
+ String timeWindow = ((AttributeDesignatorType)((ApplyType)timeWindowSection.getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer();
+ yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':')+1));
+ yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:")+4,timeWindow.lastIndexOf(':')));
+ }
+ policyAdapter.setYamlparams(yamlParams);
+ policyAdapter.setAttributes(new ArrayList<Object>());
+ policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
+ break;
+ }
+ // Populating Rule Algorithms starting from compound.
+ prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
+ policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
+ }
+ } else if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("Rainy_Day")&& ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
+
+ TargetType ruleTarget = ((RuleType) object).getTarget();
+ AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
+
+ String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().
+ get(1).getAttributeValue().getContent().get(0).toString();
+ JAXBElement<AttributeValueType> tempTreatmentObj = (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().
+ get(0).getAttributeAssignmentExpression().get(0).getExpression();
+ String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
+
+ prePopulateRainyDayTreatments(errorcode, treatment);
+
+ }
+ }
+ }
+ }
+
+ rainydayParams.setTreatmentTableChoices(treatmentList);
+ policyAdapter.setRainyday(rainydayParams);
+ policyAdapter.setSettings(decisionList);
+ }
+
+ }
+
+ private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
+ Map<String, String> ruleMap = new HashMap<>();
+
+ ruleMap.put("errorcode", errorcode);
+ ruleMap.put("treatment", treatment);
+ treatmentList.add(ruleMap);
+
+ }
+
+ private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, List<JAXBElement<?>> jaxbDecisionTypes) {
+ Map<String, String> ruleMap = new HashMap<>();
+ ruleMap.put("id", "A" + (index +1));
+ Map<String, String> dropDownMap = PolicyController.getDropDownMap();
+ for (String key : dropDownMap.keySet()) {
+ String keyValue = dropDownMap.get(key);
+ if (keyValue.equals(decisionApply.getFunctionId())) {
+ ruleMap.put("dynamicRuleAlgorithmCombo", key);
+ }
+ }
+ // 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 (policyLogger.isDebugEnabled()) {
+ policyLogger.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 (policyLogger.isDebugEnabled()) {
+ policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
+ }
+ Map<String, String> rule = new HashMap<>();
+ for (String key : PolicyController.getDropDownMap().keySet()) {
+ String keyValue = PolicyController.getDropDownMap().get(key);
+ if (keyValue.equals(decisionApply.getFunctionId())) {
+ rule.put("dynamicRuleAlgorithmCombo", key);
+ break;
+ }
+ }
+
+ rule.put("id", "A" + (index +1));
+ // Populate Key and values for Compound Rule
+ rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 ));
+ ruleAlgoirthmTracker.removeLast();
+ rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
+ ruleAlgoirthmTracker.removeLast();
+ ruleAlgoirthmTracker.addLast(index);
+ ruleAlgorithmList.add(rule);
+ index++;
+ }
+
+ return index;
+ }
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
new file mode 100644
index 000000000..0f8a3c988
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
@@ -0,0 +1,394 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.policy.controller;
+
+
+import java.io.File;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.model.PDPGroupContainer;
+import org.onap.policy.model.Roles;
+import org.onap.policy.xacml.api.XACMLErrorConstants;
+import org.onap.policy.xacml.api.pap.OnapPDPGroup;
+import org.onap.policy.xacml.std.pap.StdPDP;
+import org.onap.policy.xacml.std.pap.StdPDPGroup;
+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.http.MediaType;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+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 PDPController extends RestrictedBaseController {
+ private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class);
+
+ protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
+ private PDPGroupContainer container;
+
+ private static String SUPERADMIN = "super-admin";
+ private static String SUPEREDITOR = "super-editor";
+ private static String SUPERGUEST = "super-guest";
+
+ private Set<OnapPDPGroup> groupsData;
+
+ private boolean junit = false;
+
+ private PolicyController policyController;
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
+
+ public synchronized void refreshGroups(HttpServletRequest request) {
+ synchronized(this.groups) {
+ this.groups.clear();
+ try {
+ PolicyController controller = getPolicyControllerInstance();
+ Set<PDPPolicy> filteredPolicies = new HashSet<>();
+ Set<String> scopes = null;
+ List<String> roles = null;
+ String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId();
+ List<Object> userRoles = controller.getRoles(userId);
+ roles = new ArrayList<>();
+ scopes = new HashSet<>();
+ for(Object role: userRoles){
+ Roles userRole = (Roles) role;
+ roles.add(userRole.getRole());
+ if(userRole.getScope() != null){
+ if(userRole.getScope().contains(",")){
+ String[] multipleScopes = userRole.getScope().split(",");
+ for(int i =0; i < multipleScopes.length; i++){
+ scopes.add(multipleScopes[i]);
+ }
+ }else{
+ scopes.add(userRole.getScope());
+ }
+ }
+ }
+ if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ) {
+ if(!junit){
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ }else{
+ this.groups.addAll(this.getGroupsData());
+ }
+ }else{
+ if(!userRoles.isEmpty()){
+ if(!scopes.isEmpty()){
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ List<OnapPDPGroup> tempGroups = new ArrayList<>();
+ if(!groups.isEmpty()){
+ Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
+ while(pdpGroup.hasNext()){
+ OnapPDPGroup group = pdpGroup.next();
+ Set<PDPPolicy> policies = group.getPolicies();
+ for(PDPPolicy policy : policies){
+ for(String scope : scopes){
+ scope = scope.replace(File.separator, ".");
+ String policyName = policy.getId();
+ if(policyName.contains(".Config_")){
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Config_"));
+ }else if(policyName.contains(".Action_")){
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Action_"));
+ }else if(policyName.contains(".Decision_")){
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_"));
+ }
+ if(policyName.startsWith(scope)){
+ filteredPolicies.add(policy);
+ }
+ }
+ }
+ pdpGroup.remove();
+ StdPDPGroup newGroup = (StdPDPGroup) group;
+ newGroup.setPolicies(filteredPolicies);
+ tempGroups.add(newGroup);
+ }
+ groups.clear();
+ groups = tempGroups;
+ }
+ }
+ }
+ }
+ } catch (PAPException e) {
+ String message = "Unable to retrieve Groups from server: " + e;
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Pap Engine is Null" + message);
+ }
+ }
+ }
+
+ @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ ObjectMapper mapper = new ObjectMapper();
+ refreshGroups(request);
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ policyLogger.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 void savePDPGroup(HttpServletRequest request, HttpServletResponse response){
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ PolicyController controller = getPolicyControllerInstance();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ this.container = new PDPGroupContainer(controller.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();
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message + e);
+ }
+
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ refreshGroups(request);
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ out.write(j.toString());
+ }
+ catch (Exception e){
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e);
+ response.setCharacterEncoding("UTF-8");
+ PrintWriter out = null;
+ try {
+ request.setCharacterEncoding("UTF-8");
+ out = response.getWriter();
+ out.write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e1);
+ }
+ }
+ }
+
+ @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void removePDPGroup(HttpServletRequest request, HttpServletResponse response){
+ try{
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyController controller = getPolicyControllerInstance();
+ this.container = new PDPGroupContainer(controller.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(request);
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ out.write(j.toString());
+ }
+ catch (Exception e){
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e);
+ PrintWriter out;
+ try {
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ out = response.getWriter();
+ out.write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger.error("Exception Occured"+ e1);
+ }
+ }
+ }
+
+ @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response){
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyController controller = getPolicyControllerInstance();
+ this.container = new PDPGroupContainer(controller.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();
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message + e);
+ }
+
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ refreshGroups(request);
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ out.write(j.toString());
+ }
+ catch (Exception e){
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e);
+ PrintWriter out;
+ try {
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ out = response.getWriter();
+ out.write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger.error("Exception Occured"+ e1);
+ }
+ }
+ }
+
+ @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response){
+ try{
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyController controller = getPolicyControllerInstance();
+ this.container = new PDPGroupContainer(controller.getPapEngine());
+ StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
+ StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
+
+ this.container.removePDP(deletePdp, activeGroupData);
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ refreshGroups(request);
+ String responseString = mapper.writeValueAsString(groups);
+ JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}");
+ out.write(j.toString());
+ }
+ catch (Exception e){
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e);
+ PrintWriter out;
+ try {
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ out = response.getWriter();
+ out.write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger.error("Exception Occured"+ e1);
+ }
+ }
+ }
+
+ private PolicyController getPolicyControllerInstance(){
+ return policyController != null ? getPolicyController() : new PolicyController();
+ }
+
+ public boolean isJunit() {
+ return junit;
+ }
+
+ public void setJunit(boolean junit) {
+ this.junit = junit;
+ }
+
+ public Set<OnapPDPGroup> getGroupsData() {
+ return groupsData;
+ }
+
+ public void setGroupsData(Set<OnapPDPGroup> groupsData) {
+ this.groupsData = groupsData;
+ }
+}
+
+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/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
new file mode 100644
index 000000000..aa1918967
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
@@ -0,0 +1,696 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.onap.policy.admin.PolicyNotificationMail;
+import org.onap.policy.admin.RESTfulPAPEngine;
+import org.onap.policy.model.PDPGroupContainer;
+import org.onap.policy.model.Roles;
+import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlAdminAuthorization;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.Datatype;
+import org.onap.policy.rest.jpa.FunctionDefinition;
+import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.policy.rest.jpa.PolicyVersion;
+import org.onap.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.onap.policy.xacml.api.XACMLErrorConstants;
+import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
+
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+
+
+@Controller
+@RequestMapping("/")
+public class PolicyController extends RestrictedBaseController {
+ private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class);
+
+ private static CommonClassDao commonClassDao;
+
+ // Our authorization object
+ //
+ XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization();
+ //
+ // The PAP Engine
+ //
+ private static PAPPolicyEngine papEngine;
+
+ private static String logTableLimit;
+ private static String systemAlertTableLimit;
+ protected static Map<String, String> dropDownMap = new HashMap<>();
+ 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;
+
+ //Constant variables used across Policy-sdk
+ private static final String policyData = "policyData";
+ private static final String characterEncoding = "UTF-8";
+ private static final String contentType = "application/json";
+ private static final String file = "file";
+
+ //Smtp Java Mail Properties
+ private static String smtpHost = null;
+ private static String smtpPort = null;
+ private static String smtpUsername = null;
+ private static String smtpPassword = null;
+ private static String smtpApplicationName = null;
+ private static String smtpEmailExtension = null;
+ //log db Properties
+ private static String logdbDriver = null;
+ private static String logdbUrl = null;
+ private static String logdbUserName = null;
+ private static String logdbPassword = null;
+ private static String logdbDialect = null;
+ //Xacml db properties
+ private static String xacmldbUrl = null;
+ private static String xacmldbUserName = null;
+ private static String xacmldbPassword = null;
+
+ //AutoPush feature.
+ private static String autoPushAvailable;
+ private static String autoPushDSClosedLoop;
+ private static String autoPushDSFirewall;
+ private static String autoPushDSMicroservice;
+ private static String autoPushPDPGroup;
+
+ //papURL
+ private static String papUrl;
+
+ //MicroService Model Properties
+ private static String msOnapName;
+ private static String msPolicyName;
+
+ //WebApp directories
+ private static String configHome;
+ private static String actionHome;
+
+ @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
+ setPapUrl(prop.getProperty("xacml.rest.pap.url"));
+ // get the property values
+ setSmtpHost(prop.getProperty("onap.smtp.host"));
+ setSmtpPort(prop.getProperty("onap.smtp.port"));
+ setSmtpUsername(prop.getProperty("onap.smtp.userName"));
+ setSmtpPassword(prop.getProperty("onap.smtp.password"));
+ setSmtpApplicationName(prop.getProperty("onap.application.name"));
+ setSmtpEmailExtension(prop.getProperty("onap.smtp.emailExtension"));
+ //Log Database Properties
+ setLogdbDriver(prop.getProperty("xacml.log.db.driver"));
+ setLogdbUrl(prop.getProperty("xacml.log.db.url"));
+ setLogdbUserName(prop.getProperty("xacml.log.db.user"));
+ setLogdbPassword(prop.getProperty("xacml.log.db.password"));
+ setLogdbDialect(prop.getProperty("onap.dialect"));
+ //Xacml Database Properties
+ setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url"));
+ setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user"));
+ setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password"));
+ //AutoPuh
+ setAutoPushAvailable(prop.getProperty("xacml.automatic.push"));
+ setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop"));
+ setAutoPushDSFirewall(prop.getProperty("xacml.autopush.firewall"));
+ setAutoPushDSMicroservice(prop.getProperty("xacml.autopush.microservice"));
+ setAutoPushPDPGroup(prop.getProperty("xacml.autopush.pdpGroup"));
+ //Micro Service Properties
+ setMsOnapName(prop.getProperty("xacml.policy.msOnapName"));
+ setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName"));
+ //WebApp directories
+ setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config");
+ setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action");
+ //Get the Property Values for Dashboard tab Limit
+ try{
+ setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit"));
+ setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
+ }catch(Exception e){
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
+ setLogTableLimit("5000");
+ setSystemAlertTableLimit("2000");
+ }
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
+ } catch (IOException ex) {
+ policyLogger.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) {
+ policyLogger.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 = 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<>();
+ mapID2Function = new HashMap<>();
+ 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())) {
+ 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<>();
+ 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){
+ policyLogger.error(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);
+ return (PolicyEntity) data.get(0);
+ }
+
+ public static Map<String, Roles> getUserRoles(String userId) {
+ Map<String, Roles> scopes = new HashMap<>();
+ List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
+ if (roles != null && !roles.isEmpty()) {
+ for (Object role : roles) {
+ scopes.put(((Roles) role).getScope(), (Roles) role);
+ }
+ }
+ return scopes;
+ }
+
+ public List<String> getRolesOfUser(String userId) {
+ List<String> rolesList = new ArrayList<>();
+ List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
+ for (Object role: roles) {
+ rolesList.add(((Roles) role).getRole());
+ }
+ return rolesList;
+ }
+
+ public 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<>();
+ 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){
+ policyLogger.error("Exception Occured"+e);
+ }
+ }
+
+ //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) {
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e);
+ }
+ Map<String, Object> model = new HashMap<>();
+ return new ModelAndView("policy_Editor","model", model);
+ }
+
+ public 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 List<Object> getData(@SuppressWarnings("rawtypes") Class className){
+ return commonClassDao.getData(className);
+ }
+
+ public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
+ return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
+ }
+
+ 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) {
+ policyLogger.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<>();
+ 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;
+ }
+
+ public static String getLogTableLimit() {
+ return logTableLimit;
+ }
+
+ public static void setLogTableLimit(String logTableLimit) {
+ PolicyController.logTableLimit = logTableLimit;
+ }
+
+ public static String getSystemAlertTableLimit() {
+ return systemAlertTableLimit;
+ }
+
+ public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
+ PolicyController.systemAlertTableLimit = systemAlertTableLimit;
+ }
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ PolicyController.commonClassDao = commonClassDao;
+ }
+
+ public XacmlAdminAuthorization getAuthorizer() {
+ return authorizer;
+ }
+
+ public void setAuthorizer(XacmlAdminAuthorization authorizer) {
+ this.authorizer = authorizer;
+ }
+
+ public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
+ return mapDatatype2Function;
+ }
+
+ public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
+ PolicyController.mapDatatype2Function = mapDatatype2Function;
+ }
+
+ public static Map<String, FunctionDefinition> getMapID2Function() {
+ return mapID2Function;
+ }
+
+ public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
+ PolicyController.mapID2Function = mapID2Function;
+ }
+
+ public static String getSmtpHost() {
+ return smtpHost;
+ }
+
+ public static void setSmtpHost(String smtpHost) {
+ PolicyController.smtpHost = smtpHost;
+ }
+
+ public static String getSmtpPort() {
+ return smtpPort;
+ }
+
+ public static void setSmtpPort(String smtpPort) {
+ PolicyController.smtpPort = smtpPort;
+ }
+
+ public static String getSmtpUsername() {
+ return smtpUsername;
+ }
+
+ public static void setSmtpUsername(String smtpUsername) {
+ PolicyController.smtpUsername = smtpUsername;
+ }
+
+ public static String getSmtpPassword() {
+ return smtpPassword;
+ }
+
+ public static void setSmtpPassword(String smtpPassword) {
+ PolicyController.smtpPassword = smtpPassword;
+ }
+
+ public static String getSmtpApplicationName() {
+ return smtpApplicationName;
+ }
+
+ public static void setSmtpApplicationName(String smtpApplicationName) {
+ PolicyController.smtpApplicationName = smtpApplicationName;
+ }
+
+ public static String getSmtpEmailExtension() {
+ return smtpEmailExtension;
+ }
+
+ public static void setSmtpEmailExtension(String smtpEmailExtension) {
+ PolicyController.smtpEmailExtension = smtpEmailExtension;
+ }
+
+ public static String getLogdbDriver() {
+ return logdbDriver;
+ }
+
+ public static void setLogdbDriver(String logdbDriver) {
+ PolicyController.logdbDriver = logdbDriver;
+ }
+
+ public static String getLogdbUrl() {
+ return logdbUrl;
+ }
+
+ public static void setLogdbUrl(String logdbUrl) {
+ PolicyController.logdbUrl = logdbUrl;
+ }
+
+ public static String getLogdbUserName() {
+ return logdbUserName;
+ }
+
+ public static void setLogdbUserName(String logdbUserName) {
+ PolicyController.logdbUserName = logdbUserName;
+ }
+
+ public static String getLogdbPassword() {
+ return logdbPassword;
+ }
+
+ public static void setLogdbPassword(String logdbPassword) {
+ PolicyController.logdbPassword = logdbPassword;
+ }
+
+ public static String getLogdbDialect() {
+ return logdbDialect;
+ }
+
+ public static void setLogdbDialect(String logdbDialect) {
+ PolicyController.logdbDialect = logdbDialect;
+ }
+
+ public static String getXacmldbUrl() {
+ return xacmldbUrl;
+ }
+
+ public static void setXacmldbUrl(String xacmldbUrl) {
+ PolicyController.xacmldbUrl = xacmldbUrl;
+ }
+
+ public static String getXacmldbUserName() {
+ return xacmldbUserName;
+ }
+
+ public static void setXacmldbUserName(String xacmldbUserName) {
+ PolicyController.xacmldbUserName = xacmldbUserName;
+ }
+
+ public static String getXacmldbPassword() {
+ return xacmldbPassword;
+ }
+
+ public static void setXacmldbPassword(String xacmldbPassword) {
+ PolicyController.xacmldbPassword = xacmldbPassword;
+ }
+
+ public static String getAutoPushAvailable() {
+ return autoPushAvailable;
+ }
+
+ public static void setAutoPushAvailable(String autoPushAvailable) {
+ PolicyController.autoPushAvailable = autoPushAvailable;
+ }
+
+ public static String getAutoPushDSClosedLoop() {
+ return autoPushDSClosedLoop;
+ }
+
+ public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
+ PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
+ }
+
+ public static String getAutoPushDSFirewall() {
+ return autoPushDSFirewall;
+ }
+
+ public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
+ PolicyController.autoPushDSFirewall = autoPushDSFirewall;
+ }
+
+ public static String getAutoPushDSMicroservice() {
+ return autoPushDSMicroservice;
+ }
+
+ public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
+ PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
+ }
+
+ public static String getAutoPushPDPGroup() {
+ return autoPushPDPGroup;
+ }
+
+ public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
+ PolicyController.autoPushPDPGroup = autoPushPDPGroup;
+ }
+
+ public static String getPapUrl() {
+ return papUrl;
+ }
+
+ public static void setPapUrl(String papUrl) {
+ PolicyController.papUrl = papUrl;
+ }
+
+ public static String getMsOnapName() {
+ return msOnapName;
+ }
+
+ public static void setMsOnapName(String msOnapName) {
+ PolicyController.msOnapName = msOnapName;
+ }
+
+ public static String getMsPolicyName() {
+ return msPolicyName;
+ }
+
+ public static void setMsPolicyName(String msPolicyName) {
+ PolicyController.msPolicyName = msPolicyName;
+ }
+
+ public static String getConfigHome() {
+ return configHome;
+ }
+
+ public static void setConfigHome(String configHome) {
+ PolicyController.configHome = configHome;
+ }
+
+ public static String getActionHome() {
+ return actionHome;
+ }
+
+ public static void setActionHome(String actionHome) {
+ PolicyController.actionHome = actionHome;
+ }
+
+ public static Object getMapaccess() {
+ return mapAccess;
+ }
+
+ public static String getPolicydata() {
+ return policyData;
+ }
+
+ public static String getCharacterencoding() {
+ return characterEncoding;
+ }
+
+ public static String getContenttype() {
+ return contentType;
+ }
+
+ public static String getFile() {
+ return file;
+ }
+}
+
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
new file mode 100644
index 000000000..92794dda9
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
@@ -0,0 +1,384 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.model.Roles;
+import org.onap.policy.rest.adapter.PolicyExportAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.ActionBodyEntity;
+import org.onap.policy.rest.jpa.ConfigurationDataEntity;
+import org.onap.policy.rest.jpa.PolicyEditorScopes;
+import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.policy.rest.jpa.PolicyVersion;
+import org.onap.policy.rest.jpa.UserInfo;
+import org.onap.policy.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;
+
+ private PolicyController policyController;
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ PolicyExportAndImportController.commonClassDao = commonClassDao;
+ }
+
+ @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<>();
+ 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 = policyController != null ? getPolicyController() : new PolicyController();
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId);
+
+ //Check if the Role and Scope Size are Null get the values from db.
+ List<Object> userRoles = controller.getRoles(userId);
+ roles = new ArrayList<>();
+ scopes = new HashSet<>();
+ for(Object role: userRoles){
+ Roles userRole = (Roles) role;
+ roles.add(userRole.getRole());
+ if(userRole.getScope() != null){
+ if(userRole.getScope().contains(",")){
+ String[] multipleScopes = userRole.getScope().split(",");
+ for(int i =0; i < multipleScopes.length; i++){
+ scopes.add(multipleScopes[i]);
+ }
+ }else{
+ scopes.add(userRole.getScope());
+ }
+ }
+ }
+ 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/onap/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java
new file mode 100644
index 000000000..f3291a79b
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java
@@ -0,0 +1,122 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.onap.policy.rest.dao.CommonClassDao;
+import org.onap.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/onap/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java
new file mode 100644
index 000000000..6f8b3de8e
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java
@@ -0,0 +1,167 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.PolicyEditorScopes;
+import org.onap.policy.rest.jpa.PolicyRoles;
+import org.onap.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{
+
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyRolesController.class);
+
+ @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<>();
+ 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){
+ LOGGER.error("Exception Occured"+e);
+ }
+ }
+
+ @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){
+ LOGGER.error("Exception Occured"+e);
+ }
+ 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<>();
+ Map<String, Object> model = new HashMap<>();
+ 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){
+ LOGGER.error("Exception Occured"+e);
+ }
+ }
+}
+
+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/onap/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
new file mode 100644
index 000000000..5fb0c1a7e
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
@@ -0,0 +1,776 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP 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.onap.policy.controller;
+
+
+import java.io.ByteArrayInputStream;
+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.LinkedHashMap;
+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.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
+import org.apache.commons.lang.StringUtils;
+import org.dom4j.util.XMLErrorHandler;
+import org.json.JSONObject;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
+import org.onap.policy.rest.adapter.ClosedLoopPMBody;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.MicroServiceModels;
+import org.onap.policy.rest.jpa.SafePolicyWarning;
+import org.onap.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.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 {
+
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class);
+
+ 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> mapAttribute = new HashMap<>();
+
+ 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;
+ StringBuilder responseString = new StringBuilder();
+ 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.append("PolicyName:" + policyNameValidate + "<br>");
+ valid = false;
+ };
+ }else{
+ responseString.append( "PolicyName: PolicyName Should not be empty" + "<br>");
+ valid = false;
+ }
+ if(policyData.getPolicyDescription() != null){
+ String descriptionValidate = descriptionValidator(policyData.getPolicyDescription());
+ if(!descriptionValidate.contains("success")){
+ responseString.append("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.getOnapName() != null){
+ String onapNameValidate = emptyValidator(policyData.getOnapName());
+ if(!onapNameValidate.contains("success")){
+ responseString.append("OnapName:" + onapNameValidate + "<br>");
+ valid = false;
+ }
+ }else{
+ responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
+ valid = false;
+ }
+ }
+
+ if(policyData.getRiskType() != null){
+ String riskTypeValidate = emptyValidator(policyData.getRiskType());
+ if(!riskTypeValidate.contains("success")){
+ responseString.append("RiskType:" + riskTypeValidate + "<br>");
+ valid = false;
+ }
+ }else {
+ responseString.append("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.append("RiskLevel:" + validateRiskLevel + "<br>");
+ valid = false;
+ }
+ }else {
+ responseString.append("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.append("Guard:" + validateGuard + "<br>");
+ valid = false;
+ }
+ }else {
+ responseString.append("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.append("ConfigName:" + configNameValidate + "<br>");
+ valid = false;
+ }
+ }else{
+ responseString.append("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.append("ConfigType:" + configTypeValidate + "<br>");
+ valid = false;
+ }
+ }else{
+ responseString.append("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.append("Config Body: JSON Content is not valid" + "<br>");
+ valid = false;
+ }
+ } else if (policyType.equals("XML")) {
+ if (!isXMLValid(configBodyData)) {
+ responseString.append("Config Body: XML Content data is not valid" + "<br>");
+ valid = false;
+ }
+ } else if (policyType.equals("PROPERTIES")) {
+ if (!isPropValid(configBodyData)||configBodyData.equals("")) {
+ responseString.append("Config Body: Property data is not valid" + "<br>");
+ valid = false;
+ }
+ } else if (policyType.equals("OTHER")) {
+ if (configBodyData.equals("")) {
+ responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
+ valid = false;
+ }
+ }
+ }
+ }else{
+ responseString.append("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.append("<b>ConfigName</b>:<i>" + configNameValidate + "</i><br>");
+ valid = false;
+ }
+ }else{
+ responseString.append("<b>Config Name</b>:<i> Config Name is required" + "</i><br>");
+ valid = false;
+ }
+ if(policyData.getSecurityZone() == null){
+ responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + "</i><br>");
+ valid = false;
+ }
+ }
+ if(policyData.getConfigPolicyType().equals("BRMS_Param")){
+ if(policyData.getRuleName() == null){
+ responseString.append("<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.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>");
+ valid = false;
+ }
+ }else{
+ responseString.append("<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.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
+ valid = false;
+ }
+ }catch(Exception e){
+ responseString.append("<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.toString());
+ if(result != "success"){
+ responseString.append(result + "<br>");
+ valid = false;
+ }
+ }
+ if(pmBody.getGeoLink() != null){
+ String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink());
+ if(!result.contains("success")){
+ responseString.append("<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.append("<b>Attributes</b>:<i>" + key + " : value has spaces</i><br>");
+ valid = false;
+ };
+ }
+ }
+ }
+ }else{
+ responseString.append("<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.toString());
+ if(result != "success"){
+ responseString.append(result+ "<br>");
+ valid = false;
+ }
+ }
+ if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
+ responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
+ valid = false;
+ }
+ if(faultBody.getActions() == null){
+ responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
+ valid = false;
+ }
+ if(faultBody.getClosedLoopPolicyStatus() == null){
+ responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
+ valid = false;
+ }
+ if(faultBody.getConditions() == null){
+ responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
+ valid = false;
+ }
+ if(faultBody.getGeoLink() != null){
+ String result = PolicyUtils.emptyPolicyValidatorWithSpaceAllowed(faultBody.getGeoLink());
+ if(!result.contains("success")){
+ responseString.append("<b>GeoLink</b>:<i>" + result + "</i><br>");
+ valid = false;
+ };
+ }
+
+ if(faultBody.getTimeInterval() == 0){
+ responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
+ valid = false;
+ }
+ if(faultBody.getRetrys() == 0){
+ responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
+ valid = false;
+ }
+ if(faultBody.getTimeOutvPRO() == 0){
+ responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
+ valid = false;
+ }
+ if(faultBody.getTimeOutRuby() == 0){
+ responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
+ valid = false;
+ }
+ if(faultBody.getVnfType() == null){
+ responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
+ valid = false;
+ }
+ }else{
+ responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
+ responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
+ responseString.append("<b>Aging Window</b>:<i>Aging Window is required</i><br>");
+ responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
+ responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
+ responseString.append("<b>PEP Name</b>:<i>PEP Name is required</i><br>");
+ responseString.append("<b>PEP Action</b>:<i>PEP Action is required</i><br>");
+ responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
+ responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
+ responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
+ responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
+ responseString.append("<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)){
+ Map<String, String> rangeMap = new HashMap<>();
+ 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 (PolicyUtils.isInteger(value.replace("\"", ""))){
+ int result = Integer.parseInt(value.replace("\"", ""));
+ if (result < startNum || result > endNum){
+ responseString.append(returnString);
+ valid = false;
+ }
+ }else {
+ responseString.append(returnString);
+ valid = false;
+ }
+ }
+ }
+ }
+ }else{
+ responseString.append("<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>");
+ valid = false;
+ }
+
+ if(policyData.getPriority() == null){
+ responseString.append("<b>Priority</b>:<i> Priority is required" + "</i><br>");
+ valid = false;
+ }
+ }
+ }
+ if (policyData.getPolicyType().equals(DECISION_POLICY)){
+ if(policyData.getOnapName() != null){
+ String onapNameValidate = emptyValidator(policyData.getOnapName());
+ if(!onapNameValidate.contains("success")){
+ responseString.append("OnapName:" + onapNameValidate + "<br>");
+ valid = false;
+ }
+ }else{
+ responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
+ valid = false;
+ }
+
+ if("Rainy_Day".equals(policyData.getRuleProvider())){
+ if(policyData.getRainyday()==null){
+ responseString.append("<b> Rainy Day Parameters are Required </b><br>");
+ valid = false;
+ }else{
+ if(policyData.getRainyday().getServiceType()==null){
+ responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
+ valid = false;
+ }
+ if(policyData.getRainyday().getVnfType()==null){
+ responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
+ valid = false;
+ }
+ if(policyData.getRainyday().getBbid()==null){
+ responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
+ valid = false;
+ }
+ if(policyData.getRainyday().getWorkstep()==null){
+ responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
+ valid = false;
+ }
+ if(policyData.getRainyday().getServiceType()==null){
+ responseString.append("Rainy Day <b>Error Code</b> is Required<br>");
+ valid = false;
+ }
+ }
+ }
+
+ if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
+ if(policyData.getYamlparams()==null){
+ responseString.append("<b> Guard Params are Required </b>" + "<br>");
+ valid = false;
+ }else{
+ if(policyData.getYamlparams().getActor()==null){
+ responseString.append("Guard Params <b>Actor</b> is Required " + "<br>");
+ valid = false;
+ }
+ if(policyData.getYamlparams().getRecipe()==null){
+ responseString.append("Guard Params <b>Recipe</b> is Required " + "<br>");
+ valid = false;
+ }
+ if(policyData.getYamlparams().getGuardActiveStart()==null){
+ responseString.append("Guard Params <b>Guard Active Start/b>is Required " + "<br>");
+ valid = false;
+ }
+ if(policyData.getYamlparams().getGuardActiveEnd()==null){
+ responseString.append("Guard Params <b>Guard Active End</b>is Required " + "<br>");
+ valid = false;
+ }
+ if("GUARD_YAML".equals(policyData.getRuleProvider())){
+ if(policyData.getYamlparams().getLimit()==null){
+ responseString.append(" Guard Params <b>Limit</b> is Required " + "<br>");
+ valid = false;
+ }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){
+ responseString.append(" Guard Params <b>Limit</b> Should be Integer " + "<br>");
+ valid = false;
+ }
+ if(policyData.getYamlparams().getTimeWindow()==null){
+ responseString.append("Guard Params <b>Time Window</b> is Required" + "<br>");
+ valid = false;
+ }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){
+ responseString.append(" Guard Params <b>Time Window</b> Should be Integer " + "<br>");
+ valid = false;
+ }
+ if(policyData.getYamlparams().getTimeUnits()==null){
+ responseString.append("Guard Params <b>Time Units</b> is Required" + "<br>");
+ valid = false;
+ }
+ }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
+ if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
+ responseString.append(" Guard Params <b>BlackList</b> is Required " + "<br>");
+ valid = false;
+ }else{
+ for(String blackList: policyData.getYamlparams().getBlackList()){
+ if(blackList==null || !("success".equals(emptyValidator(blackList)))){
+ responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
+ valid = false;
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if(policyData.getPolicyType().equals(ACTION_POLICY)){
+ if(policyData.getActionPerformer() != null){
+ String actionPerformer = emptyValidator(policyData.getActionPerformer());
+ if(!actionPerformer.contains("success")){
+ responseString.append("ActionPerformer:" + actionPerformer + "<br>");
+ valid = false;
+ };
+ }else{
+ responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
+ valid = false;
+ }
+ if(policyData.getAttributes() != null){
+ for(Object attribute : policyData.getAttributes()){
+ if(attribute instanceof LinkedHashMap<?, ?>){
+ try{
+ //This is for validation check if the value exists or not
+ String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
+ String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
+ if("".equals(key) || "".equals(value)){
+ responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
+ valid = false;
+ break;
+ }
+ }catch(Exception e){
+ LOGGER.error("This is a Policy Validation check" +e);
+ responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
+ valid = false;
+ break;
+ }
+ }
+ }
+ }else{
+ responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
+ valid = false;
+ }
+ if(policyData.getActionAttributeValue() != null){
+ String actionAttribute = emptyValidator(policyData.getActionAttributeValue());
+ if(!actionAttribute.contains("success")){
+ responseString.append("ActionAttribute:" + actionAttribute + "<br>");
+ valid = false;
+ };
+ }else{
+ responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "<br>");
+ valid = false;
+ }
+ }
+
+ if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){
+ if(!policyData.getRuleAlgorithmschoices().isEmpty()){
+ for(Object attribute : policyData.getRuleAlgorithmschoices()){
+ if(attribute instanceof LinkedHashMap<?, ?>){
+ try{
+ String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
+ String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
+ String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
+ String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
+ if("".equals(label) || "".equals(key) || "".equals(rule) || "".equals(value)){
+ responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
+ valid = false;
+ }
+ }catch(Exception e){
+ LOGGER.error("This is a Policy Validation check" +e);
+ responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
+ valid = false;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if(policyData.getPolicyType().equals(CONFIG_POLICY)){
+ String value = "";
+ if(valid){
+ List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
+ if (!spData.isEmpty()){
+ SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0);
+ safePolicyWarningData.getMessage();
+ value = "Message:" + safePolicyWarningData.getMessage();
+ }
+ responseString.append("success" + "@#"+ value);
+ }
+ }else{
+ if(valid){
+ responseString.append("success");
+ }
+ }
+
+ PrintWriter out = response.getWriter();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
+ JSONObject j = new JSONObject(msg);
+ out.write(j.toString());
+
+ return null;
+ }
+ catch (Exception e){
+ LOGGER.error("Exception Occured while Policy Validation" +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;
+ if ("".equals(field) || 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;
+ 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 response){
+ if(email != null){
+ String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
+ if(!validateEmail.contains("success")){
+ response += "<b>Email</b>:<i>" + validateEmail+ "</i><br>";
+ }else{
+ return "success";
+ }
+ }
+ return response;
+ }
+
+ 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());
+ }
+ }
+ }
+ }
+
+ // Validation for json.
+ protected static boolean isJSONValid(String data) {
+ JsonReader jsonReader = null;
+ try {
+ new JSONObject(data);
+ InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
+ jsonReader = Json.createReader(stream);
+ LOGGER.info("Json Value is: " + jsonReader.read().toString() );
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured While Validating"+e);
+ return false;
+ }finally{
+ if(jsonReader != null){
+ jsonReader.close();
+ }
+ }
+ 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 (Exception e) {
+ LOGGER.error("Exception Occured While Validating"+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 = 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;
+ }
+
+} \ No newline at end of file