From 91d04c64771832a0b8815ffbe1f0f9920320d94d Mon Sep 17 00:00:00 2001 From: Pamela Dragosh Date: Tue, 14 Feb 2017 19:41:00 -0500 Subject: Initial OpenECOMP policy/engine commit Change-Id: I7dbff37733b661643dd4d1caefa3d7dccc361b6e Signed-off-by: Pamela Dragosh --- .../policy/components/ElasticSearchComponent.java | 426 +++++++++ .../policy/components/HumanPolicyComponent.java | 982 +++++++++++++++++++++ .../policy/components/PolicyImportWindow.java | 226 +++++ 3 files changed, 1634 insertions(+) create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/components/ElasticSearchComponent.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java (limited to 'ecomp-sdk-app/src/main/java/org/openecomp/policy/components') diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/ElasticSearchComponent.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/ElasticSearchComponent.java new file mode 100644 index 000000000..35a4d14b8 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/ElasticSearchComponent.java @@ -0,0 +1,426 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.components; + + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.regex.Pattern; + +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.elk.client.ElkConnector; +import org.openecomp.policy.elk.client.ElkConnector.PolicyIndexType; +import org.openecomp.policy.rest.dao.DescriptiveScopeDao; +import org.openecomp.policy.rest.jpa.DescriptiveScope; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.elk.client.Pair; +import org.openecomp.policy.elk.client.PolicyLocator; +import org.springframework.beans.factory.annotation.Autowired; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +public class ElasticSearchComponent { + private static final Logger logger = FlexLogger.getLogger(ElasticSearchComponent.class); + + + private static PolicyVersionDao policyVersionDao; + private static DescriptiveScopeDao descriptiveScopeDao; + + @Autowired + public ElasticSearchComponent(PolicyVersionDao policyVersionDao){ + ElasticSearchComponent.policyVersionDao = policyVersionDao; + } + + @Autowired + public ElasticSearchComponent(DescriptiveScopeDao descriptiveScopeDao){ + ElasticSearchComponent.descriptiveScopeDao = descriptiveScopeDao; + } + + + private volatile static HashMap filteredPolicies = new HashMap(); + + public static final HashMap name2jsonPath = new HashMap() { + private static final long serialVersionUID = 1L; + { + put(CLFAULT_UIFIELD_D2_SERVICES_TRINITY, CLFAULT_UIJSON_D2_SERVICES_TRINITY); + put(CLFAULT_UIFIELD_D2_SERVICES_VUSP, CLFAULT_UIJSON_D2_SERVICES_VUSP); + put(CLFAULT_UIFIELD_D2_SERVICES_MCR, CLFAULT_UIJSON_D2_SERVICES_MCR); + put(CLFAULT_UIFIELD_D2_SERVICES_GAMMA, CLFAULT_UIJSON_D2_SERVICES_GAMMA); + put(CLFAULT_UIFIELD_D2_SERVICES_VDNS, CLFAULT_UIJSON_D2_SERVICES_VDNS); + + put(CLFAULT_UIFIELD_EMAIL_ADDRESS, CLFAULT_UIJSON_EMAIL_ADDRESS); + put(CLFAULT_UIFIELD_TRIGGER_SIGNATURE, CLFAULT_UIJSON_TRIGGER_SIGNATURE); + put(CLFAULT_UIFIELD_VERIFICATION_SIGNATURE, CLFAULT_UIJSON_VERIFICATION_SIGNATURE); + put(CLFAULT_UIFIELD_CONNECT_ALL_TRAPS, CLFAULT_UIJSON_CONNECT_ALL_TRAPS); + put(CLFAULT_UIFIELD_CONNECT_ALL_FAULTS, CLFAULT_UIJSON_CONNECT_ALL_FAULTS); + + put(CLFAULT_UIFIELD_POLICY_STATUS_INACTIVE, CLFAULT_UIJSON_POLICY_STATUS_ACTIVE); + put(CLFAULT_UIFIELD_POLICY_STATUS_ACTIVE, CLFAULT_UIJSON_POLICY_STATUS_INACTIVE); + + put(CLPM_UIFIELD_ONSET_MESSAGE, CLPM_UIJSON_ONSET_MESSAGE); + put(CLPM_UIFIELD_POLICY_NAME, CLPM_UIJSON_POLICY_NAME); + put(CLPM_UIFIELD_ABATEMENT_MESSAGE, CLPM_UIJSON_ABATEMENT_MESSAGE); + put(CLPM_UIFIELD_GEOLINK, CLPM_UIJSON_GEOLINK); + }}; + + //For AND and OR logical connector AND=0 and OR=1 + private static int connectorSelected; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_TRINITY = "Hosted Voice (Trinity)"; + public static final String CLFAULT_UIJSON_D2_SERVICES_TRINITY = "trinity"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_VUSP = "vUSP"; + public static final String CLFAULT_UIJSON_D2_SERVICES_VUSP = "vUSP"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_MCR = "MCR"; + public static final String CLFAULT_UIJSON_D2_SERVICES_MCR = "mcr"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_GAMMA = "Gamma"; + public static final String CLFAULT_UIJSON_D2_SERVICES_GAMMA = "gama"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_VDNS = "vDNS"; + public static final String CLFAULT_UIJSON_D2_SERVICES_VDNS = "vDNS"; + + public static final String CLFAULT_UIFIELD_EMAIL_ADDRESS = "Email Address"; + public static final String CLFAULT_UIJSON_EMAIL_ADDRESS = "emailAddress"; + + public static final String CLFAULT_UIFIELD_TRIGGER_SIGNATURE = "Trigger Signature"; + public static final String CLFAULT_UIJSON_TRIGGER_SIGNATURE = "triggerSignaturesUsedForUI.signatures"; + + public static final String CLFAULT_UIFIELD_VERIFICATION_SIGNATURE = "Verification Signature"; + public static final String CLFAULT_UIJSON_VERIFICATION_SIGNATURE = "verificationSignaturesUsedForUI.signatures"; + + public static final String CLFAULT_UIFIELD_CONNECT_ALL_TRAPS = "Connect All Traps"; + public static final String CLFAULT_UIJSON_CONNECT_ALL_TRAPS = "triggerSignaturesUsedForUI.connectSignatures"; + + public static final String CLFAULT_UIFIELD_CONNECT_ALL_FAULTS = "Connect All Faults"; + public static final String CLFAULT_UIJSON_CONNECT_ALL_FAULTS = "verificationSignaturesUsedForUI.connectSignatures"; + + public static final String CLFAULT_UIFIELD_POLICY_STATUS_ACTIVE = "Active"; + public static final String CLFAULT_UIJSON_POLICY_STATUS_ACTIVE = "ACTIVE"; + + public static final String CLFAULT_UIFIELD_POLICY_STATUS_INACTIVE = "InActive"; + public static final String CLFAULT_UIJSON_POLICY_STATUS_INACTIVE = "INACTIVE"; + + + public static final String CLPM_UIFIELD_ONSET_MESSAGE = "Onset Message"; + public static final String CLPM_UIJSON_ONSET_MESSAGE = "attributes.OnsetMessage"; + + public static final String CLPM_UIFIELD_POLICY_NAME = "PolicyName"; + public static final String CLPM_UIJSON_POLICY_NAME = "attributes.PolicyName"; + + public static final String CLPM_UIFIELD_ABATEMENT_MESSAGE = "Abatement Message"; + public static final String CLPM_UIJSON_ABATEMENT_MESSAGE = "attributes.AbatementMessage"; + + public static final String CLPM_UIFIELD_GEOLINK = "Geo Link"; + public static final String CLPM_UIJSON_GEOLINK = "geoLink"; + + public static void search(String value){ + String policyType = "all";//(String) self.searchPolicyType.getValue() + + ArrayList,ArrayList>> filter_s = new ArrayList,ArrayList>>(); + + String searchText = "";//self.searchTextBox.getValue() + if (searchText == null || searchText.isEmpty()) { + if (policyType == null || policyType.isEmpty() && + !policyType.equals(ElkConnector.PolicyIndexType.closedloop.toString())) { + if (logger.isDebugEnabled()) { + logger.debug("Clearing search filters, nothing to search and not closed loop."); + } + return; + } + } else { + searchText = searchText.trim(); + //Descriptive Scope. + /* + When a item is selected in the "descriptiveScope" comboBox, the name of the item + is added to the Search-Text Box with the prefix "Descriptive-Scope" + User needs to press the "Search" button to perform the search. + */ + if(searchText.contains("Descriptive-Scope=")) + { + if (logger.isDebugEnabled()) { + logger.debug("Inside the Descriptive Scope"); + } + /* + First item is always String "Descriptive-Scope" before the "=", + So taking the second item of "split using =" + */ + String[] dsName= searchText.split("=",2); + /* + Trying to find the search String by traversing different items from the dictionary by Scope-Name + Once when the the "scope-name" is found, we get the search string from dictionary. + */ + for (int i = 0; i < descriptiveScopeDao.getDescriptiveScope().size(); i++) { + DescriptiveScope dsSearch=descriptiveScopeDao.getDescriptiveScope().get(i); + if(dsSearch.getScopeName().equals(dsName[1])){ + searchText=dsSearch.getSearch(); + if (logger.isDebugEnabled()) { + logger.debug("DescriptiveScope Search String is " +searchText ); + } + } + } + } + + if(searchText.contains(":")) + { + String connector="&"; + + if(searchText.contains("&")) + { + connector="&"; + connectorSelected=0; + } + else if(searchText.contains("|")) + { + connector=Pattern.quote("|"); + connectorSelected=1; + } + for (String retval: searchText.split(connector)){ + + int index= retval.indexOf(':'); + String filterKey=null; + String filterValue=null; + + filterKey=retval.substring(0,index); + filterValue= retval.substring(index+1); + + String clSearchBoxFilter=filterKey; + + ArrayList clSearchBoxFilterField_s = new ArrayList(); + + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchBoxFilter); + + + ArrayList clSearchBoxFilterValue_s = new ArrayList(); + clSearchBoxFilterValue_s.add(filterValue); + + filter_s.add(new Pair,ArrayList>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); + } + } + } + + if (policyType != null && !policyType.isEmpty() && + policyType.equals(ElkConnector.PolicyIndexType.closedloop.toString())) { + + /* closed loop policy type */ + + String clPolicyType = "";//(String) self.cbSearchCLPolicyType.getValue() + if (clPolicyType != null && !clPolicyType.isEmpty()) { + ArrayList clPolicyTypeField_s = new ArrayList(); + clPolicyTypeField_s.add("Policy.PolicyType"); + + ArrayList clPolicyTypeValue_s = new ArrayList(); + clPolicyTypeValue_s.add(clPolicyType); + + filter_s.add(new Pair,ArrayList>(clPolicyTypeField_s, clPolicyTypeValue_s)); + } + + String clEcompName = "";//(String) self.cbSearchCLEcompName.getValue() + if (clEcompName != null && !clEcompName.isEmpty()) { + clSearchBody(clPolicyType, "ecompname", clEcompName, filter_s); + } + + String clD2Services = "";//(String) self.cbSearchCLD2Services.getValue() + if (clD2Services != null && !clD2Services.isEmpty()) { + switch (clD2Services) { + case CLFAULT_UIFIELD_D2_SERVICES_TRINITY: + case CLFAULT_UIFIELD_D2_SERVICES_VUSP: + case CLFAULT_UIFIELD_D2_SERVICES_MCR: + case CLFAULT_UIFIELD_D2_SERVICES_GAMMA: + case CLFAULT_UIFIELD_D2_SERVICES_VDNS: + clSearchBody(clPolicyType, name2jsonPath.get(clD2Services), "true", filter_s); + break; + default: + if (logger.isWarnEnabled()) + logger.warn("Unexpected D2 Service: " + clD2Services); + break; + } + } + + String clFaultAction = "";//(String) self.cbSearchCLFaultAction.getValue() + if (clFaultAction != null && !clFaultAction.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "actions", clFaultAction, filter_s); + } + } + + String clFaultStatus = "";//(String) self.cbSearchCLFaultStatus.getValue() + if (clFaultStatus != null && !clFaultStatus.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "closedLoopPolicyStatus", clFaultStatus, filter_s); + } + } + + String clFaultVnfTypes = "";//(String) self.cbSearchCLFaultVnfTypes.getValue() + if (clFaultVnfTypes != null && !clFaultVnfTypes.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "vnfType", clFaultVnfTypes, filter_s); + } + } + + String clPMServiceType = "";//(String) self.cbSearchCLPMServiceType.getValue() + if (clPMServiceType != null && !clPMServiceType.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_PM.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_PM.name(), "serviceTypePolicyName", clPMServiceType, filter_s); + } + } + + String clSearchBoxFilter = "";//(String) self.cbSearchCLTextFilter.getValue() + if (clSearchBoxFilter != null && !clSearchBoxFilter.isEmpty() && + searchText != null && !searchText.isEmpty()) { + + if (name2jsonPath.containsKey(clSearchBoxFilter)) { + clSearchBoxFilter = name2jsonPath.get(clSearchBoxFilter); + } + + ArrayList clSearchBoxFilterField_s = new ArrayList(); + if (clPolicyType == null || clPolicyType.isEmpty()) { + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter); + } else { + clSearchBoxFilterField_s.add("Policy.Body." + clPolicyType + "_Body." + clSearchBoxFilter); + } + + ArrayList clSearchBoxFilterValue_s = new ArrayList(); + clSearchBoxFilterValue_s.add(searchText); + + filter_s.add(new Pair,ArrayList>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); + + // deactivate search all fields in case a searchbox filter is provided + searchText = ""; + } + } + + if ((searchText == null || searchText.isEmpty()) && + (filter_s == null || filter_s.size() <=0) ) { + if (logger.isWarnEnabled()) { + logger.warn("Clearing search filters, closed loop but nothing to search nor filters"); + } + + return; + } + + ArrayList locators; + try { + locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), + searchText, filter_s,connectorSelected); + } catch (Exception ise) { + /*AdminNotification.warn("Search is unavailable: " + ise.getMessage());*/ + return; + } + + synchronized(filteredPolicies) { + if (locators.isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("No match has been found"); + } + //AdminNotification.warn("No match has been found"); + return; + } + + // Retrieve active versions + + HashMap policyVersion_s = new HashMap(); + for(int i = 0; i < policyVersionDao.getPolicyVersionData().size(); i++) { + PolicyVersion entityVersion = policyVersionDao.getPolicyVersionData().get(i); + String dbPolicy = entityVersion.getPolicyName() + "." + entityVersion.getActiveVersion(); + policyVersion_s.put(dbPolicy, true); + if (logger.isDebugEnabled()) + logger.debug("Map addition: DB Policy Name: " + dbPolicy); + } + + filteredPolicies.clear(); + for (PolicyLocator p: locators) { + String dbPolicyName = p.scope + "/" + p.policyType + "_" + p.policyName; + if (policyVersion_s.containsKey(dbPolicyName)) { + String filterPolicyName = dbPolicyName + ".xml"; + filteredPolicies.put(Paths.get(filterPolicyName), filterPolicyName); + if (logger.isInfoEnabled()) + logger.info("Active Version Policy found in search: " + + dbPolicyName + " -> " + filterPolicyName); + } else { + if (logger.isInfoEnabled()) + logger.info("Inactive Version Policy found in search: " + dbPolicyName); + } + } + + if (filteredPolicies.isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("No match has been found for active versions"); + } + //AdminNotification.warn("No match has been found for active versions"); + return; + } + + //self.policyContainer.setFilter(self.filteredPolicies); + } + /* self.policyContainer.refresh();*/ + } + + + protected static void clSearchBody(String clPolicyType, String bodyField, String bodyValue, + ArrayList, ArrayList>> filter_s) { + if (logger.isDebugEnabled()) + logger.debug("ENTER: " + clPolicyType + ":" + bodyField + ":" + bodyValue); + + final ArrayList clBodyField_s = new ArrayList(); + final ArrayList clBodyValue_s = new ArrayList(); + + if (clPolicyType == null || clPolicyType.isEmpty()) { + clBodyField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + bodyField); + clBodyField_s.add("Policy.Body."+ ElkConnector.PolicyType.Config_PM.name() + "_Body." + bodyField); + clBodyValue_s.add(bodyValue); + } else { + clBodyField_s.add("Policy.Body." + clPolicyType + "_Body." + bodyField); + clBodyValue_s.add(bodyValue); + } + filter_s.add(new Pair, ArrayList>(clBodyField_s, clBodyValue_s)); + } + + protected static void clSearchFilter(String clType, String clField, String clValue, + ArrayList,ArrayList>> filter_s) { + if (logger.isDebugEnabled()) + logger.debug("ENTER: " + clType + ":" + clField + ":" + clValue); + + ArrayList clSearchField_s = new ArrayList(); + clSearchField_s.add("Policy.Body." + clType + "_Body." + clField); + + ArrayList clSearchValue_s = new ArrayList(); + clSearchValue_s.add(clValue); + + filter_s.add(new Pair,ArrayList>(clSearchField_s, clSearchValue_s)); + } + + public static ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException { + if (type == null || type.isEmpty()) + return PolicyIndexType.all; + + return PolicyIndexType.valueOf(type); + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java new file mode 100644 index 000000000..037888b7c --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java @@ -0,0 +1,982 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.components; + + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.util.Collection; +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.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.AttributeSelectorType; +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.PolicySetType; +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.VariableReferenceType; + +import org.apache.commons.io.FilenameUtils; +import org.json.JSONObject; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.rest.jpa.FunctionDefinition; +import org.openecomp.policy.utils.XACMLPolicyWriterWithPapNotify; + +import com.att.research.xacml.api.AttributeValue; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAttribute; +import com.att.research.xacml.std.StdAttributeValue; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; +import com.att.research.xacml.util.XACMLPolicyScanner.SimpleCallback; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + + +public class HumanPolicyComponent{ + + private static final Logger logger = FlexLogger.getLogger(HumanPolicyComponent.class); + + // Constants Used in XML Creation + public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"; + public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; + public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; + public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; + public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id"; + public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; + public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; + public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"; + public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"; + public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; + public static final String FUNCTION_STRING_REGEX_MATCH = "org.openecomp.function.regex-match"; + public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"; + public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; + public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; + public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string"; + public static final String URI_DATATYPE = "http://www.w3.org/2001/XMLSchema#anyURI"; + public static final String RULE_VARIABLE = "var:"; + public static final String EMPTY_STRING = ""; + + private static HtmlProcessor htmlProcessor; + + private static File policyFile; + + public static JSONObject DescribePolicy(final File policyFile) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + HumanPolicyComponent.policyFile = policyFile; + return humanPolicyLayout(); + + } + + private static JSONObject humanPolicyLayout() { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + try { + String html = processPolicy(); + JSONObject result = new JSONObject(); + result.put("html", html); + return result; + //ByteArrayInputStream is = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)); + + } catch (IllegalArgumentException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "cannot build html area por policy", e); + /*AdminNotification.warn("An error has occurred. Cannot describe this policy: " + + e.getMessage());*/ + } + return null; + } + + private static String processPolicy() throws IllegalArgumentException { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + FileInputStream pIS = null; + try { + pIS = new FileInputStream(policyFile); + Object policy = XACMLPolicyScanner.readPolicy(pIS); + if (policy == null) + throw new IllegalArgumentException("Policy File " + policyFile.getName() + + " cannot be unmarshalled"); + + HumanPolicyComponent.htmlProcessor = + new HtmlProcessor(HumanPolicyComponent.policyFile, policy); + + Path policyPath = FileSystems.getDefault().getPath(policyFile.getAbsolutePath()); + XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor); + xacmlScanner.scan(); + String html = htmlProcessor.html(); + if (logger.isDebugEnabled()) + logger.debug(policyPath + System.lineSeparator() + html); + + return html; + + } catch (Exception e) { + String msg = "Exception reading policy: " + policyFile.getAbsolutePath() + + ": " + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + msg, e); + throw new IllegalArgumentException(msg); + } finally { + if (pIS != null) { + try { + pIS.close(); + } catch (IOException e) { + logger.warn(e.getMessage(), e); + } + } + } + } + +} + +class HtmlProcessor extends SimpleCallback { + + private static final Logger logger = FlexLogger.getLogger(HtmlProcessor.class); + + private static Map function2human; + static { + function2human = new HashMap(); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL_IGNORE, "equal"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_ONE_AND_ONLY, "one-and-only"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_REGEX_MATCH, "matching regular expression"); + function2human.put(HumanPolicyComponent.FUNTION_INTEGER_ONE_AND_ONLY, "one-and-only"); + } + + private static Map combiningAlgo2human; + static { + combiningAlgo2human = new HashMap(); + combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to deny"); + combiningAlgo2human.put("permit-overrides", "to permit if any $placeholder$ below evaluates to permit"); + + combiningAlgo2human.put("ordered-deny-overrides", "to deny if any $placeholder$ below evaluates to deny"); + combiningAlgo2human.put("ordered-permit-overrides", "to permit if any $placeholder$ below evaluates to permit"); + combiningAlgo2human.put("deny-unless-permit", "to permit if any $placeholder$ below evaluates to deny and not indeterminate"); + + combiningAlgo2human.put("permit-unless-deny", "to deny if any $placeholder$ below evaluates to is permit and not indeterminate"); + combiningAlgo2human.put("first-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order"); + combiningAlgo2human.put("only-one-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order"); + } + + private Map attributeIdentifiersMap = new HashMap(); + + private final StringWriter stringWriter = new StringWriter(); + private final PrintWriter htmlOut = new PrintWriter(stringWriter); + private final String policyName; + private final Object rootPolicyObject; + + public HtmlProcessor(File policyFile, Object policyObject) + throws IllegalArgumentException { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + if (policyFile == null) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File"); + throw new IllegalArgumentException("Null Policy File"); + } + + if (!policyFile.exists() || !policyFile.canRead()) { + String msg = "Can't access " + policyFile.getAbsolutePath(); + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + msg); + throw new IllegalArgumentException(msg); + } + + if (policyObject == null || + (!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) { + String msg = "Invalid unmarshalled object: " + policyObject; + logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + msg); + throw new IllegalArgumentException(msg); + } + + this.policyName = FilenameUtils.removeExtension(policyFile.getName()); + this.rootPolicyObject = policyObject; + + String version = "-"; + if (policyObject instanceof PolicyType) { + PolicyType policy = (PolicyType) policyObject; + version = policy.getVersion(); + htmlOut.println("

Policy: " + policyName + + " (version " + version + ")

"); + + } else { + PolicySetType policySet = (PolicySetType) policyObject; + version = policySet.getVersion(); + htmlOut.println("

Policy Set: " + policyName + + " (v" + version + ")

"); + } + + htmlOut.println("

Location: " + policyFile.getPath() + "

"); + htmlOut.println("
"); + + if (rootPolicyObject instanceof PolicySetType) { + if (policyName.startsWith("Config_")) { + htmlOut.println("

This is a config policy set.

"); + } else if (policyName.startsWith("Action_")) { + htmlOut.println("

This is an action policy set.

"); + } + htmlOut.println("
"); + } else { + if (policyName.startsWith("Config_")) { + htmlOut.println("

This is a config policy.

"); + } else if (policyName.startsWith("Action_")) { + htmlOut.println("

This is an action policy.

"); + } + htmlOut.println("
    "); + } + } + + /** + * @return the attributeIdentifiersMap + */ + public Map getAttributeIdentifiersMap() { + return attributeIdentifiersMap; + } + + @Override + public void onFinishScan(Object root) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + if (rootPolicyObject instanceof PolicySetType) { + htmlOut.println("
"); + } else { + htmlOut.println(""); + } + + htmlOut.println("
"); + + htmlOut.println("

Attribute Table:

"); + + htmlOut.println(""); + htmlOut.println(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.println(""); + for(Map.Entry entry : this.attributeIdentifiersMap.entrySet()){ + AttributeIdentifiers value = entry.getValue(); + htmlOut.println(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.println(""); + } + htmlOut.println("
CategoryTypeIdentifier
" + value.category + "" + value.type + "" + value.id + "
"); + + htmlOut.println("

"); + + // Not necessary for the user, uncomment if desired at some point + // writeRawXACML() + + super.onFinishScan(root); + } + + @SuppressWarnings("unused") + private void writeRawXACML() { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + htmlOut.println("
"); + htmlOut.println("

Raw XACML:

"); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + if (rootPolicyObject instanceof PolicySetType) { + XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicySetType) rootPolicyObject); + } else if (rootPolicyObject instanceof PolicyType) { + XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicyType) rootPolicyObject); + } + + String xacml = bos.toString(); + xacml = xacml.replaceAll("<", "<"); + xacml = xacml.replaceAll(">", ">"); + htmlOut.println("
");
+		htmlOut.println(xacml);
+		htmlOut.println("
"); + } + + @Override + public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) { + if (logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policySet.getDescription(); + if (description != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + + " Description: " + policySet.getDescription()); + + if (parent == null) // root + policySet(policySet, "dl"); + else + policySet(policySet, "li"); + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) + htmlOut.println("
    "); + + return super.onPreVisitPolicySet(parent, policySet); + } + + @Override + public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) { + if (logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policySet.getDescription(); + if (description != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + + " Description: " + policySet.getDescription()); + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) + htmlOut.println("
"); + + htmlOut.println("

"); + + return super.onPostVisitPolicySet(parent, policySet); + } + + public void policySet(PolicySetType policySet, String htmlListElement) { + if (logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId()); + + String combiningAlgorithm = "-"; + String id = "-"; + String version = "-"; + + + if (policySet.getPolicyCombiningAlgId() != null) + combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":"); + + if (policySet.getPolicySetId() != null) + id = extractLastIdentifier(policySet.getPolicySetId(), ":"); + + if (policySet.getVersion() != null) + version = policySet.getVersion(); + + + htmlOut.println("<" + htmlListElement + ">Policy Set ID: " + id + + " (v" + version + ") " + ""); + + if (policySet.getTarget() == null || + policySet.getTarget().getAnyOf() == null || + policySet.getTarget().getAnyOf().size() <= 0) { + htmlOut.println("

This policy set applies to all requests.

"); + } else { + htmlOut.print("

"); + htmlOut.print("This policy set applies to requests with attributes "); + + List anyOf_s = policySet.getTarget().getAnyOf(); + target(anyOf_s); + htmlOut.println(".

"); + } + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference() != null && + policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) { + String algoDesc = combiningAlgo2human.get(combiningAlgorithm); + if (algoDesc != null) { + algoDesc = algoDesc.replace("$placeholder$", "policy") + " (" + "" + combiningAlgorithm + ")"; + } else { + algoDesc = combiningAlgorithm; + } + + htmlOut.println("

The result is " + algoDesc + ":

"); + } + } + + @Override + public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) { + if (logger.isTraceEnabled()) + logger.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policy.getPolicyId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policy.getDescription(); + if (description != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policy.getPolicyId() + + " Description: " + policy.getDescription()); + + policy(policy); + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) + htmlOut.println("
    "); + + return super.onPreVisitPolicy(parent, policy); + } + + @Override + public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) { + if (logger.isTraceEnabled()) + logger.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policy.getPolicyId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) + htmlOut.println("
"); + + htmlOut.println("

"); + return super.onPostVisitPolicy(parent, policy); + } + + public void policy(PolicyType policy) { + if (logger.isTraceEnabled()) + logger.trace("Policy: " + policy.getPolicyId()); + + String combiningAlgorithm = "-"; + String id = "-"; + String version = "-"; + + + if (policy.getRuleCombiningAlgId() != null) + combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":"); + + if (policy.getPolicyId() != null) + id = extractLastIdentifier(policy.getPolicyId(), ":"); + + if (policy.getVersion() != null) + version = policy.getVersion(); + + htmlOut.println("
  • Policy ID: " + id + + " (v" + version + ") " + "
  • "); + + if (policy.getTarget() == null || + policy.getTarget().getAnyOf() == null || + policy.getTarget().getAnyOf().size() <= 0) { + htmlOut.println("

    This policy applies to all requests.

    "); + } else { + htmlOut.print("

    "); + htmlOut.print("This policy applies to requests with attributes "); + + List anyOf_s = policy.getTarget().getAnyOf(); + target(anyOf_s); + htmlOut.println(".

    "); + } + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() != null && + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) { + String algoDesc = combiningAlgo2human.get(combiningAlgorithm); + if (algoDesc != null) { + algoDesc = algoDesc.replace("$placeholder$", "rule") + " (" + combiningAlgorithm + ")"; + } else { + algoDesc = combiningAlgorithm; + } + htmlOut.println("

    The result is " + algoDesc + ":

    "); + } + } + + + @Override + public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) { + if (logger.isTraceEnabled()) + logger.trace("Rule: " + rule.getRuleId()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + + String description = rule.getDescription(); + if (description != null && logger.isTraceEnabled()) { + logger.trace("Rule: " + rule.getRuleId() + + " Description: " + rule.getDescription()); + } + + rule(rule); + + return super.onPreVisitRule(parent, rule); + } + + @Override + public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) { + if (logger.isTraceEnabled()) + logger.trace("Rule: " + rule.getRuleId()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + + return super.onPostVisitRule(parent, rule); + } + + public void rule(RuleType rule) { + if (logger.isTraceEnabled()) + logger.trace("Rule: " + rule.getRuleId()); + + String id = "-"; + + if (rule.getRuleId() != null) + id = extractLastIdentifier(rule.getRuleId(), ":"); + + htmlOut.println("
  • Rule ID: " + id + "
  • "); + + htmlOut.println("
    "); + + htmlOut.print("

    "); + htmlOut.print(rule.getEffect().value()); + + if (rule.getTarget() == null || + rule.getTarget().getAnyOf() == null || + rule.getTarget().getAnyOf().size() <= 0) { + htmlOut.print(" for all requests"); + } else { + List anyOf_s = rule.getTarget().getAnyOf(); + htmlOut.print(" for requests with attributes "); + target(anyOf_s); + } + + if (rule.getCondition() != null) { + htmlOut.print(" when "); + htmlOut.println(this.stringifyCondition(rule.getCondition()) + " "); + } else { + htmlOut.print(" with no conditions "); + } + + if (rule.getAdviceExpressions() != null) { + advice(rule.getAdviceExpressions()); + if (rule.getObligationExpressions() != null) + htmlOut.println(" and "); + } + + if (rule.getObligationExpressions() != null) { + obligation(rule.getObligationExpressions()); + } + + htmlOut.println("

    "); + } + + private void advice(AdviceExpressionsType adviceExpressions) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + List ae = adviceExpressions.getAdviceExpression(); + for (AdviceExpressionType expression : ae) { + htmlOut.println(" with advice (" + expression.getAdviceId() + ") on " + + expression.getAppliesTo().value() + ":" ); + htmlOut.println("
      "); + List assignments = expression.getAttributeAssignmentExpression(); + if (assignments != null) { + processAttributeAssignments(assignments); + } + htmlOut.println("
    "); + } + } + + private void obligation(ObligationExpressionsType obligationExpressions) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + List oe = obligationExpressions.getObligationExpression(); + for (ObligationExpressionType expression : oe) { + htmlOut.println(" with obligations (" + expression.getObligationId() + ") to be fullfilled on " + + expression.getFulfillOn().value() + ":" ); + htmlOut.println("
      "); + List assignments = expression.getAttributeAssignmentExpression(); + if (assignments != null) { + processAttributeAssignments(assignments); + } + htmlOut.println("
    "); + } + } + + /** + * @param assignments + */ + private void processAttributeAssignments(List assignments) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + for (AttributeAssignmentExpressionType assignment : assignments) { + String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") + + ":" + extractLastIdentifier(assignment.getAttributeId(), ":"); + AttributeIdentifiers attributeIdentifiers = null; + if (!this.attributeIdentifiersMap.containsKey(succintIdentifier)) { + // Note Attribute Assignments do not have an Attribute Type, assume string + // but note this case is unlikely since attributeMap should have been populated + // during parsing of target and conditions, and not in this case for Advice and + // Obligations. + attributeIdentifiers = new AttributeIdentifiers(assignment.getCategory(), + "NA", + assignment.getAttributeId()); + this.attributeIdentifiersMap.put(succintIdentifier, attributeIdentifiers); + } + + htmlOut.print("
  • " + succintIdentifier + " is "); + // AttributeValueType + JAXBElement jaxbExp = assignment.getExpression(); + Object assignmentObject = jaxbExp.getValue(); + if (assignmentObject instanceof AttributeValueType) { + AttributeValueType avt = (AttributeValueType) assignmentObject; + if (attributeIdentifiers != null) { + attributeIdentifiers.type = avt.getDataType(); + } + int numContent = avt.getContent().size(); + int countContent = 0; + for (Object c: avt.getContent()) { + countContent++; + htmlOut.print("" + c + ""); + if (countContent < numContent) + htmlOut.print(" or "); + } + htmlOut.println("
  • "); + } else if (assignmentObject instanceof AttributeDesignatorType) { + htmlOut.println("NA"); + } else if (assignmentObject instanceof AttributeSelectorType) { + htmlOut.println("NA"); + } else if (assignmentObject instanceof ApplyType) { + htmlOut.println("NA"); + } else { + htmlOut.println("Unexpected"); + } + } + } + + /** + * + * @param anyOfList + */ + public void target(List anyOfList) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + String targetInHuman = ""; + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + if (matchList.size() > 1) + targetInHuman += "("; + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Finally down to the actual attribute + // + StdAttribute attribute = null; + AttributeValueType value = match.getAttributeValue(); + String attributeDataType = null; + if (match.getAttributeDesignator() != null && value != null) { + AttributeDesignatorType designator = match.getAttributeDesignator(); + attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), + new IdentifierImpl(designator.getAttributeId()), + new StdAttributeValue>(new IdentifierImpl(value.getDataType()), value.getContent()), + designator.getIssuer(), + false); + attributeDataType = designator.getDataType(); + } else if (match.getAttributeSelector() != null && value != null) { + AttributeSelectorType selector = match.getAttributeSelector(); + attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), + new IdentifierImpl(selector.getContextSelectorId()), + new StdAttributeValue>(new IdentifierImpl(value.getDataType()), value.getContent()), + null, + false); + attributeDataType = selector.getDataType(); + } else { + logger.warn("NULL designator/selector or value for match."); + attributeDataType = "NA"; + } + + String functionName = getHumanFunction(match.getMatchId()); + + String succintIdentifier = extractLastIdentifier(attribute.getCategory().stringValue(), ":") + + ":" + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":"); + AttributeIdentifiers ai = new AttributeIdentifiers(attribute.getCategory().stringValue(), + attributeDataType, + attribute.getAttributeId().stringValue()); + this.attributeIdentifiersMap.put(succintIdentifier,ai); + + targetInHuman += "" + succintIdentifier + " " + functionName + " "; + + int numAttributes = attribute.getValues().size(); + int count = 0; + for (AttributeValue v: attribute.getValues()) { + count++; + if (v.getValue() instanceof Collection) { + Collection value_s = (Collection) v.getValue(); + int numValues = value_s.size(); + int countValues = 0; + for (Object o : value_s) { + countValues++; + targetInHuman += " " + o + ""; + if (countValues < numValues) { + targetInHuman += ", or"; + } + } + } else { + targetInHuman += " " + v.getValue() + ""; + if (count < numAttributes) { + targetInHuman += ", or "; + } + } + } + + if (iterMatch.hasNext()) { + targetInHuman += " and "; + } + } // end iterMatch + if (matchList.size() > 1) { + targetInHuman += ")"; + } + } + if (iterAllOf.hasNext()) { + targetInHuman += " or "; + } + } // end iterAllOf + } + if (iterAnyOf.hasNext()) { + targetInHuman = "(" + targetInHuman + ")" + " or "; + } else { + if (anyOfList.size() > 1) { + targetInHuman += ")"; + } + } + } // end iterAnyOf + htmlOut.println(targetInHuman); + } + } + + private String getHumanFunction(String matchId) { + if (HtmlProcessor.function2human.containsKey(matchId)) { + return HtmlProcessor.function2human.get(matchId); + } + + FunctionDefinition function = PolicyController.getFunctionIDMap().get(matchId); + String functionName = function.getShortname(); + + if (logger.isDebugEnabled()) { + logger.debug(functionName + + ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]"); + } + + return extractLastIdentifier(removePrimitives(functionName), ":"); + } + + public String html() { + this.htmlOut.flush(); + return this.stringWriter.toString(); + } + + private String extractLastIdentifier(String in, String separator) { + int lastIndex = in.lastIndexOf(separator); + if (lastIndex < 0) + return in; + else + return in.substring(lastIndex+1); + } + + private String removePrimitives(String in) { + in = in.replace("string-", ""); + in = in.replace("integer-", ""); + in = in.replace("double-", ""); + in = in.replace("boolean-", ""); + return in; + } + + private String stringifyCondition(ConditionType condition) { + if (condition.getExpression() == null) { + return ""; + } + + return stringifyExpression(condition.getExpression().getValue()); + } + + private String stringifyExpression(Object expression) { + if (expression instanceof ApplyType) { + ApplyType apply = (ApplyType) expression; + FunctionDefinition function = PolicyController.getFunctionIDMap().get(apply.getFunctionId()); + String functionName = function.getShortname(); + + if (logger.isDebugEnabled()) { + logger.debug(functionName + + ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]"); + } + + if (functionName.contains("one-and-only")) { + if (logger.isDebugEnabled()) { + logger.debug("one-and-only found: " + functionName); + } + + List> exps = apply.getExpression(); + if (exps == null || exps.size() == 0) + return ""; + else { + String forResult = ""; + for (JAXBElement e : exps) { + Object v = e.getValue(); + if (logger.isDebugEnabled()) { + logger.debug("one-and-only children: " + v); + } + if (v != null) { + // C: return stringifyExpression(v, result); + forResult += stringifyExpression(v); + } + } + return forResult; + } + } + + final int numExpr = (apply.getExpression() == null) ? -1 : apply.getExpression().size(); + if (numExpr <= 0) { + if (logger.isDebugEnabled()) { + logger.debug(functionName + " 0 expressions: " + numExpr); + } + return ""; + } else if (numExpr == 1) { + // eg: not + if (logger.isDebugEnabled()) { + logger.debug(functionName + " 1 expression: " + numExpr); + } + String applySubresult = ""; + for (JAXBElement e : apply.getExpression()) { + Object v = e.getValue(); + if (v != null) { + applySubresult += this.stringifyExpression(e.getValue()); + } + } + return " " + removePrimitives(functionName) + " (" + applySubresult + ")"; + } else { + // > 1 arguments + if (logger.isDebugEnabled()) { + logger.debug(functionName + " > 1 expressions: " + numExpr); + } + String applySubresult = ""; + int exprCount = 0; + for (JAXBElement e : apply.getExpression()) { + exprCount++; + Object ev = e.getValue(); + if (ev != null) { + if (ev instanceof ApplyType) { + if (((ApplyType) ev).getFunctionId().contains("one-and-only")) { + applySubresult += this.stringifyExpression(e.getValue()); + } else { + applySubresult += "(" + this.stringifyExpression(e.getValue()) + ")"; + } + } else { + applySubresult += this.stringifyExpression(e.getValue()); + } + + if (exprCount < numExpr) { + applySubresult += " " + removePrimitives(functionName) + " "; + } + } + } + return applySubresult; + } + } + if (expression instanceof AttributeDesignatorType) { + AttributeDesignatorType adt = (AttributeDesignatorType) expression; + + String succintIdentifier = extractLastIdentifier(adt.getCategory(), ":") + + ":" + extractLastIdentifier(adt.getAttributeId(), ":"); + AttributeIdentifiers ai = new AttributeIdentifiers(adt.getCategory(), + adt.getDataType(), + adt.getAttributeId()); + this.attributeIdentifiersMap.put(succintIdentifier,ai); + + return "" + succintIdentifier + ""; + } + if (expression instanceof AttributeSelectorType) { + AttributeSelectorType ast = (AttributeSelectorType) expression; + + String attrName = ast.getPath(); + if (attrName == null || (attrName.length() == 0)) { + return ""; + } + + String textSelector = "/text()"; + if (attrName.endsWith(textSelector)) { + attrName = attrName.substring(0, attrName.length() - textSelector.length()); + } + + attrName = extractLastIdentifier(attrName, "/"); + attrName = extractLastIdentifier(attrName, ":"); + return " " + attrName; + } + if (expression instanceof AttributeValueType) { + AttributeValueType avt = (AttributeValueType) expression; + List content = avt.getContent(); + String value_s = ""; + for (Object o: content) { + value_s += " " + o.toString(); + } + return " " + value_s; + } + if (expression instanceof VariableReferenceType) { + // + // Really unknown - the variable may or may not have been defined + // + return " VARIABLEREF-NOT-HANDLED"; + } else { + throw new IllegalArgumentException("Unexpected input expression"); + } + } +} + + +class AttributeIdentifiers { + public final String category; + public String type; + public final String id; + + public AttributeIdentifiers(String category, String type, String id) { + this.category = category; + this.type = type; + this.id = id; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java new file mode 100644 index 000000000..c70e331d0 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java @@ -0,0 +1,226 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.components; + + +/* + * + */ +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.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Set; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.io.IOUtils; +import org.openecomp.policy.controller.PolicyController; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + + +public class PolicyImportWindow{ + + private static final Logger logger = FlexLogger.getLogger(PolicyImportWindow.class); + private static final int BUFFER_SIZE = 4096; + private static Path directory = PolicyController.getGitPath(); + private Path newfile = null; + private boolean succeeded = false; + public static String CONFIG_HOME = PolicyController.getConfigHome(); + public static String ACTION_HOME = PolicyController.getActionHome(); + private Boolean superadmin = false; + private ArrayList xacmlFiles = new ArrayList(); + /** + * The constructor should first build the main layout, set the + * composition root and then do any custom initialization. + * + * The constructor will not be automatically regenerated by the + * visual editor. + */ + + public OutputStream receiveUpload(String filename, String mimeType) { + + // + // Create its new full path + // + this.newfile = Paths.get(PolicyImportWindow.directory.toString(), filename); + // + // Does it already exist? + // + if (Files.exists(this.newfile)) { + return null; + } + // + // Try to create the output stream + // + try { + return new FileOutputStream(this.newfile.toFile()); + } catch (FileNotFoundException e) { + logger.error("Failed to create uploaded file", e); + } + return null; + } + + public void Upload(){ + TarArchiveEntry entry = null; + TarArchiveInputStream extractFile = null; + try { + extractFile = new TarArchiveInputStream (new FileInputStream(this.newfile.toFile())); + } catch (FileNotFoundException e1) { + e1.printStackTrace(); + } + //Create a loop to read every single entry in TAR file + try { + while ((entry = extractFile.getNextTarEntry()) != null) { + this.superadmin = true; + try{ + copyFileToLocation(extractFile, entry, xacmlFiles, null, superadmin); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception while Importing Polcies"+e); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + + + + + //Copy files to Directorys + public static void copyFileToLocation(TarArchiveInputStream extractFile, TarArchiveEntry entry, ArrayList xacmlFiles, Set finalScopes, Boolean superadminValue ) throws IOException{ + String individualFiles = ""; + int offset = 0; + FileOutputStream outputFile=null; + // Get the name of the file + if(superadminValue){ + individualFiles = entry.getName(); + }else{ + for(int i =0; i< finalScopes.size(); i++){ + if(entry.getName().startsWith(finalScopes.toArray()[i].toString())){ + individualFiles = entry.getName(); + } + } + } + + if(individualFiles.endsWith(".xls")){ + if(individualFiles.contains("\\")){ + individualFiles = individualFiles.replace("\\", File.separator); + }else if(individualFiles.contains("/")){ + individualFiles = individualFiles.replace("/", File.separator); + } + return; + } + + individualFiles = individualFiles.replace("/", File.separator); + individualFiles = individualFiles.replace("\\", File.separator); + + //Create the path with the entry name + String filePath = directory.toAbsolutePath() + File.separator + individualFiles; + String configPath = CONFIG_HOME + File.separator + individualFiles; + String actionPath = ACTION_HOME + File.separator + individualFiles; + logger.info("File Name in TAR File is: " + individualFiles); + logger.info("Xml directory file path: " + filePath); + logger.info("Config Home directory file path: " + configPath); + logger.info("Action Home directory file path: " + actionPath); + + + // Get Size of the file and create a byte array for the size + byte[] content = new byte[(int) entry.getSize()]; + + offset=0; + logger.info("File Name in TAR File is: " + individualFiles); + logger.info("Size of the File is: " + entry.getSize()); + // Read file from the archive into byte array + extractFile.read(content, offset, content.length - offset); + if (!entry.isDirectory()) { + if(!individualFiles.contains(".Config_") || !individualFiles.contains(".Action_")){ + // if the entry is a file, extracts it + String filePath1 = filePath.substring(0, filePath.lastIndexOf(File.separator)); + File newFile = new File(filePath1); + if(!(newFile.exists())) { + File dir = new File(filePath1); + dir.mkdir(); + extractFile(extractFile, filePath); + } + } + } else { + // if the entry is a directory, make the director + File dir = new File(filePath); + dir.mkdir(); + } + // Define OutputStream for writing the file + if(individualFiles.contains(".Config_")){ + outputFile=new FileOutputStream(new File(configPath)); + }else if(individualFiles.contains(".Action_")){ + outputFile=new FileOutputStream(new File(actionPath)); + }else{ + if(filePath != null){ + outputFile=new FileOutputStream(new File(filePath)); + xacmlFiles.add(filePath); + } + } + + // Use IOUtiles to write content of byte array to physical file + IOUtils.write(content,outputFile); + + // Close Output Stream + try { + outputFile.close(); + } catch (IOException e) { + logger.info("IOException:" +e); + e.printStackTrace(); + } + } + + private static void extractFile(TarArchiveInputStream extractFile, String filePath) throws IOException { + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = extractFile.read(bytesIn)) != -1) { + bos.write(bytesIn, 0, read); + } + bos.close(); + + } + + public Path getUploadedFile() { + if (this.succeeded) { + return this.newfile; + } + return null; + } + +} -- cgit 1.2.3-korg