diff options
author | Jorge Hernandez <jorge.hernandez-herrero@att.com> | 2019-11-19 16:37:11 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2019-11-19 16:37:11 +0000 |
commit | 89ef1958121b877e990ff8755f9087cd306d4b4c (patch) | |
tree | fc64629e87c6775e72c73bd8b389a276059db2e6 /ONAP-XACML/src/main | |
parent | 779125e31adbcc59a9864843b523bd6ed2751cbb (diff) | |
parent | d089848fdb0beef8446bdcf60cdb14e4655a93e5 (diff) |
Merge "Format ONAP-XACML and add JUnit"
Diffstat (limited to 'ONAP-XACML/src/main')
23 files changed, 3764 insertions, 3666 deletions
diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/XACMLErrorConstants.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/XACMLErrorConstants.java index 0cbba2f19..b8a68d10a 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/XACMLErrorConstants.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/XACMLErrorConstants.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,44 +17,46 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.api; /** * List of Error Classifications - * PE100 - Permissions - * PE200 - System Error (such as availability, timeout, configuration, etc...) - * PE300 - Data Issue( such as request for REST/JSON ) - * PE400 - Schema validation - * PE500 - Process Flow issues - * PE900 - Default/Unknown Errors - * + * PE100 - Permissions + * PE200 - System Error (such as availability, timeout, configuration, etc...) + * PE300 - Data Issue( such as request for REST/JSON ) + * PE400 - Schema validation + * PE500 - Process Flow issues + * PE900 - Default/Unknown Errors + * * */ public class XACMLErrorConstants { - //Captures all the errors related to Authentication, Authorizations and Permissions in the PolicyEngine Process - public static final String ERROR_PERMISSIONS = "PE100 - Permissions Error: "; - - //Captures all the errors related to availability, timeout configuration variables, etc... in the PolicyEngine - public static final String ERROR_SYSTEM_ERROR = "PE200 - System Error: "; - - /* - * Captures all the errors related to configuration values from properties files and data from the interfacing System - * like REST/JSON values - */ - public static final String ERROR_DATA_ISSUE = "PE300 - Data Issue: "; - - //Captures all the errors related to the XML schemas and/or REST/JSON structures - public static final String ERROR_SCHEMA_INVALID = "PE400 - Schema validation Error: "; - - //Captures all the errors related to the Process, when data from one Process to another Process does not flow - public static final String ERROR_PROCESS_FLOW = "PE500 - Process Flow Issue: "; - - //Captures all the errors that not related to the list of above error codes - public static final String ERROR_UNKNOWN = "PE900 - Unknown Error: "; - - // Static class, hide constructor + // Captures all the errors related to Authentication, Authorizations and Permissions in the PolicyEngine Process + public static final String ERROR_PERMISSIONS = "PE100 - Permissions Error: "; + + // Captures all the errors related to availability, timeout configuration variables, etc... in the PolicyEngine + public static final String ERROR_SYSTEM_ERROR = "PE200 - System Error: "; + + /* + * Captures all the errors related to configuration values from properties files and data from the interfacing + * System + * like REST/JSON values + */ + public static final String ERROR_DATA_ISSUE = "PE300 - Data Issue: "; + + // Captures all the errors related to the XML schemas and/or REST/JSON structures + public static final String ERROR_SCHEMA_INVALID = "PE400 - Schema validation Error: "; + + // Captures all the errors related to the Process, when data from one Process to another Process does not flow + public static final String ERROR_PROCESS_FLOW = "PE500 - Process Flow Issue: "; + + // Captures all the errors that not related to the list of above error codes + public static final String ERROR_UNKNOWN = "PE900 - Unknown Error: "; + + // Static class, hide constructor private XACMLErrorConstants() { - super(); + super(); } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactory.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactory.java index eacbeb216..a78dc3250 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactory.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactory.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017,2019 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. @@ -20,39 +20,40 @@ package org.onap.policy.xacml.api.pap; -import java.util.Properties; - import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.util.FactoryException; import com.att.research.xacml.util.FactoryFinder; -public abstract class ONAPPapEngineFactory{ - - /** - * Creates a new <code>PAPEngineFactory</code> instance using the given class name and the default thread class loader. - * - * @param factoryClassName the <code>String</code> name of the factory class to instantiate - * @return an instance of an object that extends <code>ONAPPapEngineFactory</code> to use in creating <code>PAPPolicyEngine</code> objects. - */ - public static ONAPPapEngineFactory newInstance(String factoryClassName) throws FactoryException { - return FactoryFinder.newInstance(factoryClassName, ONAPPapEngineFactory.class, null, true); - } - - /** - * Creates a new <code>PAPPolicyEngine</code> based on the configured <code>ONAPPapEngineFactory</code>. - * - * @return a new <code>PAPPolicyEngine</code> - * @throws PAPException - */ - public abstract PAPPolicyEngine newEngine() throws FactoryException, PAPException; - - /** - * Creates a new <code>PAPPolicyEngine</code> based on the configured <code>ONAPPapEngineFactory</code>. - * - * @return a new <code>PAPPolicyEngine</code> - * @throws PAPException - */ - public abstract PAPPolicyEngine newEngine(Properties properties) throws FactoryException, PAPException; +import java.util.Properties; +public abstract class ONAPPapEngineFactory { + + /** + * Creates a new <code>PAPEngineFactory</code> instance using the given class name and the default thread class + * loader. + * + * @param factoryClassName the <code>String</code> name of the factory class to instantiate + * @return an instance of an object that extends <code>ONAPPapEngineFactory</code> to use in creating + * <code>PAPPolicyEngine</code> objects. + */ + public static ONAPPapEngineFactory newInstance(String factoryClassName) throws FactoryException { + return FactoryFinder.newInstance(factoryClassName, ONAPPapEngineFactory.class, null, true); + } + + /** + * Creates a new <code>PAPPolicyEngine</code> based on the configured <code>ONAPPapEngineFactory</code>. + * + * @return a new <code>PAPPolicyEngine</code> + * @throws PAPException PAPException + */ + public abstract PAPPolicyEngine newEngine() throws FactoryException, PAPException; + + /** + * Creates a new <code>PAPPolicyEngine</code> based on the configured <code>ONAPPapEngineFactory</code>. + * + * @return a new <code>PAPPolicyEngine</code> + * @throws PAPException PAPException + */ + public abstract PAPPolicyEngine newEngine(Properties properties) throws FactoryException, PAPException; } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPAPPolicy.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPAPPolicy.java index 4539b4225..5879c098c 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPAPPolicy.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPAPPolicy.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,73 +17,115 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.api.pap; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonSubTypes.Type; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + import java.net.URI; import java.util.List; import java.util.Map; import org.onap.policy.xacml.std.pap.StdPAPPolicy; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonSubTypes.Type; - /* * The following allows us to use Jackson to convert sub-types of this type into JSON and back to objects. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - include = JsonTypeInfo.As.PROPERTY, - property = "PAPPolicyType") -@JsonSubTypes({ - @Type(value = StdPAPPolicy.class, name = "StdPAPPolicy") }) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "PAPPolicyType") +@JsonSubTypes({@Type(value = StdPAPPolicy.class, name = "StdPAPPolicy")}) public interface OnapPAPPolicy { - - public String getPolicyName(); - public String getOldPolicyFileName(); - public String getPolicyDescription(); - public String getOnapName(); - public String getConfigName(); - public Map<String, String> getDynamicFieldConfigAttributes(); - public Map<String, String> getTreatments(); - public Map<String, String> getDynamicSettingsMap(); - public List<String> getDynamicRuleAlgorithmLabels(); - public List<String> getDynamicRuleAlgorithmCombo(); - public List<String> getDynamicRuleAlgorithmField1(); - public List<String> getDynamicRuleAlgorithmField2(); - public List<Object> getDynamicVariableList(); - public List<String> getDataTypeList(); - public String getConfigBodyData(); - public String getPolicyID(); - public String getRuleID(); - public String getConfigType(); - public Boolean isEditPolicy(); - public Boolean isDraft(); - public String getVersion(); - public String getDomainDir(); - public String getConfigPolicyType(); - public String getJsonBody(); - public Integer getHighestVersion(); - public URI getLocation(); - public String getActionPerformer(); - public String getActionAttribute(); - public String getActionBody(); - public Map<String, String> getDropDownMap(); - public String getActionDictHeader(); - public String getActionDictType(); - public String getActionDictUrl(); - public String getActionDictMethod(); - public String getServiceType(); - public String getUuid(); - public String getMsLocation(); - public String getPriority(); + + public String getPolicyName(); + + public String getOldPolicyFileName(); + + public String getPolicyDescription(); + + public String getOnapName(); + + public String getConfigName(); + + public Map<String, String> getDynamicFieldConfigAttributes(); + + public Map<String, String> getTreatments(); + + public Map<String, String> getDynamicSettingsMap(); + + public List<String> getDynamicRuleAlgorithmLabels(); + + public List<String> getDynamicRuleAlgorithmCombo(); + + public List<String> getDynamicRuleAlgorithmField1(); + + public List<String> getDynamicRuleAlgorithmField2(); + + public List<Object> getDynamicVariableList(); + + public List<String> getDataTypeList(); + + public String getConfigBodyData(); + + public String getPolicyID(); + + public String getRuleID(); + + public String getConfigType(); + + public Boolean isEditPolicy(); + + public Boolean isDraft(); + + public String getVersion(); + + public String getDomainDir(); + + public String getConfigPolicyType(); + + public String getJsonBody(); + + public Integer getHighestVersion(); + + public URI getLocation(); + + public String getActionPerformer(); + + public String getActionAttribute(); + + public String getActionBody(); + + public Map<String, String> getDropDownMap(); + + public String getActionDictHeader(); + + public String getActionDictType(); + + public String getActionDictUrl(); + + public String getActionDictMethod(); + + public String getServiceType(); + + public String getUuid(); + + public String getMsLocation(); + + public String getPriority(); + public String getDeleteCondition(); + public String getDictionaryType(); + public String getDictionary(); + public String getDictionaryFields(); - public String getRiskLevel(); - public String getGuard(); - public String getRiskType(); - public String getTTLDate(); + + public String getRiskLevel(); + + public String getGuard(); + + public String getRiskType(); + + public String getTTLDate(); } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDP.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDP.java index 65db0b980..6224e38cd 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDP.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDP.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,28 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.policy.xacml.api.pap; -import org.onap.policy.xacml.std.pap.StdPDP; +package org.onap.policy.xacml.api.pap; import com.att.research.xacml.api.pap.PDP; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.onap.policy.xacml.std.pap.StdPDP; + /* * The following allows us to use Jackson to convert sub-types of this type into JSON and back to objects. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - include = JsonTypeInfo.As.PROPERTY, - property = "PDPType") -@JsonSubTypes({ - @Type(value = StdPDP.class, name = "StdPDP") }) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "PDPType") +@JsonSubTypes({@Type(value = StdPDP.class, name = "StdPDP")}) public interface OnapPDP extends PDP { - public Integer getJmxPort(); - - public void setJmxPort(Integer jmxport); - + public Integer getJmxPort(); + + public void setJmxPort(Integer jmxport); + } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDPGroup.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDPGroup.java index 7d3ad0c63..77561652a 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDPGroup.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDPGroup.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,16 +20,16 @@ package org.onap.policy.xacml.api.pap; -import java.util.Set; - import com.att.research.xacml.api.pap.PDPGroup; import com.att.research.xacml.api.pap.PDPPolicy; +import java.util.Set; + public interface OnapPDPGroup extends PDPGroup { - public Set<OnapPDP> getOnapPdps(); - - public Set<PDPPolicy> getSelectedPolicies(); - - public String getOperation(); + public Set<OnapPDP> getOnapPdps(); + + public Set<PDPPolicy> getSelectedPolicies(); + + public String getOperation(); } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/PAPPolicyEngine.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/PAPPolicyEngine.java index cae7456bc..cfb1434bc 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/PAPPolicyEngine.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/PAPPolicyEngine.java @@ -23,6 +23,7 @@ package org.onap.policy.xacml.api.pap; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.api.pap.PDPStatus; + import java.io.InputStream; import java.util.Set; diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java index 8e55300b1..464313e0e 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java @@ -30,6 +30,7 @@ import com.att.research.xacml.util.XACMLProperties; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Sets; + import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @@ -48,6 +49,7 @@ import java.util.List; import java.util.Properties; import java.util.Set; import java.util.TreeSet; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.policy.common.logging.eelf.MessageCodes; @@ -81,6 +83,12 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE protected final Path repository; protected Set<StdPDPGroup> groups; + /** + * StdEngine constructor. + * + * @throws PAPException PAPException + * @throws IOException IOException + */ public StdEngine() throws PAPException, IOException { // // Get the location in the file system of our repository @@ -92,6 +100,13 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE this.intialize(); } + /** + * StdEngine constructor. + * + * @param properties Properties + * @throws PAPException PAPException + * @throws IOException IOException + */ public StdEngine(Properties properties) throws PAPException, IOException { // // Get the location in the file system of our repository @@ -103,6 +118,13 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE this.intialize(); } + /** + * StdEngine constructor. + * + * @param repository Path + * @throws PAPException PAPException + * @throws IOException IOException + */ public StdEngine(Path repository) throws PAPException, IOException { // // Save our location @@ -211,7 +233,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } { Properties props = new Properties(); - props = setPIPProperties(props); + props = setPipProperties(props); Path pipPath = Paths.get(defaultPath.toAbsolutePath().toString(), "xacml.pip.properties"); Files.createFile(pipPath); try (OutputStream os = Files.newOutputStream(pipPath)) { @@ -282,7 +304,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } @Override - public void newGroup(String name, String description) throws PAPException, NullPointerException { + public void newGroup(String name, String description) throws PAPException { // // Null check // @@ -298,12 +320,10 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } } - // create an Id that can be used as a file name and a properties file key. // Ids must not contain \/:*?"<>|=,; // The ID must also be unique within the current set of PDPGroups. - String id = createNewPDPGroupId(name); - + String id = createNewPdpGroupId(name); // // Construct the directory path @@ -355,7 +375,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE logger.warn(addGroup + id + " file exists."); } else { try { - props = setPIPProperties(props); + props = setPipProperties(props); Files.createFile(pipProperties); try (OutputStream os = Files.newOutputStream(pipProperties)) { props.store(os, ""); @@ -389,17 +409,15 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } - - /** * Helper to create a new Group ID. Use the Name field to create the Id. The Name is expected to not be null; if it * is then this method throws an exception. The name is supposed to be unique within the current set of groups, so * creating the ID based on the name will create a unique string. * - * @param name - * @return + * @param name String + * @return String */ - private String createNewPDPGroupId(String name) { + private String createNewPdpGroupId(String name) { String id = name; // replace "bad" characters with sequences that will be ok for file names and properties keys. id = id.replace(" ", "_sp_"); @@ -420,7 +438,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE return id; } - @Override public OnapPDP getPDP(String pdpId) throws PAPException { for (OnapPDPGroup group : this.groups) { @@ -433,7 +450,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE return null; } - @Override public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException { if (newGroup == null) { @@ -471,21 +487,20 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } } - @Override public void updatePDP(OnapPDP pdp) throws PAPException { - PDP currentPDP = this.getPDP(pdp.getId()); - if (currentPDP == null) { + PDP currentPdp = this.getPDP(pdp.getId()); + if (currentPdp == null) { String message = "Unknown PDP id '" + pdp.getId() + "'"; logger.warn(message); throw new PAPException(message); } // the only things that the user can change are name and description - currentPDP.setDescription(pdp.getDescription()); - currentPDP.setName(pdp.getName()); - if (currentPDP instanceof OnapPDP) { - ((OnapPDP) currentPDP).setJmxPort(pdp.getJmxPort()); + currentPdp.setDescription(pdp.getDescription()); + currentPdp.setName(pdp.getName()); + if (currentPdp instanceof OnapPDP) { + ((OnapPDP) currentPdp).setJmxPort(pdp.getJmxPort()); } this.doSave(); } @@ -508,7 +523,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE throw new PAPException(message); } - @Override /** * Should never be called - Detailed status is held on the PDP, not the PAP @@ -531,7 +545,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE throw new PAPException("Unknown PDP Group: " + group.getId()); } - @Override public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { // @@ -539,7 +552,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE // } - @Override public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { if (group == null) { @@ -553,7 +565,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE throw new PAPException("Unknown PDP Group: " + group.getId()); } - // // HELPER methods // @@ -578,14 +589,14 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE // // Add our Group Object // - StdPDPGroup g = new StdPDPGroup(id.trim(), + StdPDPGroup newGroup = new StdPDPGroup(id.trim(), id.equals(properties.getProperty(PROP_PAP_GROUPS_DEFAULT, PROP_PAP_GROUPS_DEFAULT_NAME)), properties, Paths.get(repository.toString(), id)); // // Add it in // - pdpGroups.add(g); + pdpGroups.add(newGroup); } // // Dump what we got @@ -674,6 +685,12 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } } + /** + * removeGroupProperties. + * + * @param id String + * @param properties Properties + */ public static void removeGroupProperties(String id, Properties properties) { for (Object key : properties.keySet()) { if (key.toString().startsWith(id + ".")) { @@ -682,6 +699,12 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } } + /** + * setGroupProperties. + * + * @param group PDPGroup + * @param properties Properties + */ public static void setGroupProperties(PDPGroup group, Properties properties) { // // make sure its in the list of groups @@ -733,7 +756,9 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } } - + /** + * changed. + */ public void changed() { if (logger.isDebugEnabled()) { logger.debug("changed"); @@ -742,6 +767,11 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE this.fireChanged(); } + /** + * groupChanged. + * + * @param group OnapPDPGroup + */ public void groupChanged(OnapPDPGroup group) { if (logger.isDebugEnabled()) { logger.debug("groupChanged: " + group); @@ -750,7 +780,11 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE this.firePDPGroupChanged(group); } - + /** + * pdpChanged. + * + * @param pdp OnapPDP + */ public void pdpChanged(OnapPDP pdp) { if (logger.isDebugEnabled()) { logger.debug("pdpChanged: " + pdp); @@ -770,7 +804,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } } - private Properties setPIPProperties(Properties props) { + private Properties setPipProperties(Properties props) { props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "AAF"); props.setProperty("AAF.name", "AAFEngine"); props.setProperty("AAF.description", "AAFEngine to communicate with AAF to take decisions"); @@ -792,7 +826,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE return props; } - @Override public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException { final Set<OnapPDPGroup> grps = new HashSet<>(); @@ -815,26 +848,26 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE @Override public void setDefaultGroup(OnapPDPGroup group) throws PAPException { boolean changesMade = false; - for (OnapPDPGroup aGroup : groups) { - if (aGroup.getId().equals(group.getId())) { - if (!aGroup.isDefaultGroup()) { - if (aGroup instanceof StdPDPGroup) { - ((StdPDPGroup) aGroup).setDefault(true); + for (OnapPDPGroup theGroup : groups) { + if (theGroup.getId().equals(group.getId())) { + if (!theGroup.isDefaultGroup()) { + if (theGroup instanceof StdPDPGroup) { + ((StdPDPGroup) theGroup).setDefault(true); changesMade = true; } else { throw new IllegalArgumentException( - "Group in groups of unknown type '" + aGroup.getClass().getName() + "'"); + "Group in groups of unknown type '" + theGroup.getClass().getName() + "'"); } } } else { // not the new default group - if (aGroup.isDefaultGroup()) { - if (aGroup instanceof StdPDPGroup) { - ((StdPDPGroup) aGroup).setDefault(false); + if (theGroup.isDefaultGroup()) { + if (theGroup instanceof StdPDPGroup) { + ((StdPDPGroup) theGroup).setDefault(false); changesMade = true; } else { throw new IllegalArgumentException( - "Group in groups of unknown type '" + aGroup.getClass().getName() + "'"); + "Group in groups of unknown type '" + theGroup.getClass().getName() + "'"); } } } @@ -842,14 +875,11 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE if (changesMade) { this.doSave(); } - - return; - } @Override public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) - throws PAPException, NullPointerException { + throws PAPException { if (group == null) { throw new PAPException("You must specify which group the PDP will belong to."); } @@ -868,10 +898,13 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE // Save the properties and notify any listeners // pdpChanged(pdp); - return; } } - return; + } + + @Override + public void updateGroup(OnapPDPGroup group, String userName) throws PAPException { + // To pass the userId for PDP Audit log maintenance. } @@ -888,7 +921,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE throw new PAPException("Update found no existing group with id '" + group.getId() + "'"); } - // We do dramatically different things when the Name changes // because the Name is essentially the identity of the group (as the User knows it) so when the Identity changes // we have to change the group ID. @@ -908,7 +940,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } else { // the name/identity of the group has changed // generate the new id - String newId = createNewPDPGroupId(group.getName()); + String newId = createNewPdpGroupId(group.getName()); // make sure no other group uses the new id for (OnapPDPGroup g : groups) { @@ -950,11 +982,10 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE // perhaps only the group changed, but if the name/id changed it may look to a listener like more than one group changed(); - } @Override - public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException, NullPointerException { + public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException { if (group == null) { throw new NullPointerException(); } @@ -1036,14 +1067,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE // changed(); this.doSave(); - return; - - } - - @Override - public void updateGroup(OnapPDPGroup group, String userName) throws PAPException { - // To pass the userId for PDP Audit log maintenance. - } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngineFactory.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngineFactory.java index dd8a92135..b6a194361 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngineFactory.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngineFactory.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,41 +17,40 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.std.pap; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.util.FactoryException; import java.io.IOException; import java.util.Properties; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.util.FactoryException; - public class StdEngineFactory extends ONAPPapEngineFactory { - - @Override - public PAPPolicyEngine newEngine() throws FactoryException, PAPException { - try { - return new StdEngine(); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "StdEngineFactory", "Failed to create engine"); - return null; - } - } - - @Override - public PAPPolicyEngine newEngine(Properties properties) throws FactoryException, - PAPException { - try { - return new StdEngine(properties); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "StdEngineFactory", "Failed to create engine"); - return null; - } - } - + + @Override + public PAPPolicyEngine newEngine() throws FactoryException, PAPException { + try { + return new StdEngine(); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "StdEngineFactory", "Failed to create engine"); + return null; + } + } + + @Override + public PAPPolicyEngine newEngine(Properties properties) throws FactoryException, PAPException { + try { + return new StdEngine(properties); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "StdEngineFactory", "Failed to create engine"); + return null; + } + } + } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java index 2f752a0aa..41b0c05d7 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,6 +18,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.std.pap; import java.io.Serializable; @@ -89,12 +90,19 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable { // } - //Constructor for sending location when pushing policies + // Constructor for sending location when pushing policies public StdPAPPolicy(URI location) { this.location = location; } - //Constructor for Validating Config Policies + /** + * Constructor for Validating Config Policies. + * + * @param policyName String + * @param body String + * @param configType String + * @param configPolicyType String + */ public StdPAPPolicy(String policyName, String body, String configType, String configPolicyType) { this.policyName = policyName; this.configBodyData = body; @@ -103,15 +111,16 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable { } /** - * Constructor for - * Create Config Policies from API and Admin Console - * Updating Config Policies from the API - * Create/Update Action Policies from API - * Create/Update Decision Policies + * Constructor. + * Create Config Policies from API and Admin Console + * Updating Config Policies from the API + * Create/Update Action Policies from API + * Create/Update Decision Policies + * * @param stdPAPPolicyParams Input params object */ public StdPAPPolicy(StdPAPPolicyParams stdPAPPolicyParams) { - this.configPolicyType=stdPAPPolicyParams.getConfigPolicyType(); + this.configPolicyType = stdPAPPolicyParams.getConfigPolicyType(); this.policyName = stdPAPPolicyParams.getPolicyName(); this.policyDescription = stdPAPPolicyParams.getDescription(); this.onapName = stdPAPPolicyParams.getOnapName(); @@ -391,31 +400,25 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable { @Override public String toString() { return "StdPAPPolicy [policyName=" + policyName + ", policyDescription=" + policyDescription + ", onapName=" - + onapName + ", configName=" + configName + ", dynamicFieldConfigAttributes=" + - dynamicFieldConfigAttributes + ", configBodyData=" + configBodyData - + ", policyID=" + policyID + ", ruleID=" + ruleID + ", configType=" + configType + ", editPolicy=" + - ", version=" + ", domain=" + domain - + ", configPolicyType=" + configPolicyType + ", jsonBody=" + jsonBody + ", highestVersion=" + - highestVersion + ", location=" + location - + ",dynamicRuleAlgorithmLabels=" + dynamicRuleAlgorithmLabels + ",dynamicRuleAlgorithmCombo=" + - dynamicRuleAlgorithmCombo - + ",dynamicRuleAlgorithmField1=" + dynamicRuleAlgorithmField1 + ",dynamicRuleAlgorithmField2=" + - dynamicRuleAlgorithmField2 - + ",actionPerformer=" + actionPerformer + ",actionAttribute=" + actionAttribute + ",actionBody=" + - actionBody + ",dropDownMap=" + dropDownMap - + ",actionDictHeader=" + actionDictHeader + ",actionDictType=" + actionDictType + ",actionDictUrl=" + - actionDictUrl - + ",actionDictMethod=" + actionDictMethod + ",dynamicSettingsMap=" + dynamicSettingsMap + "," + - "dynamicVariableList=" + dynamicVariableList + ",providerComboBox=" + providerComboBox - + ",dataTypeList=" + dataTypeList + ",draft=" + ",oldPolicyFileName=" + oldPolicyFileName + "," + - "serviceType=" + serviceType - + ",uuid=" + uuid + ",msLocation=" + msLocation + ",priority=" + priority + ",deleteCondition=" + - deleteCondition + ",dictionaryType=" + dictionaryType - + ",dictionary=" + dictionary + ",dictionaryFields=" + dictionaryFields + ",uuid=" + uuid + "," + - "msLocation=" + msLocation + ",priority=" - + priority + ",deleteCondition=" + deleteCondition + ",riskType=" + riskType + ",riskLevel=" + - riskLevel + ",guard=" + guard + ",ttlDate=" + ttlDate - + ",treatments=" + treatments + "]"; + + onapName + ", configName=" + configName + ", dynamicFieldConfigAttributes=" + + dynamicFieldConfigAttributes + ", configBodyData=" + configBodyData + ", policyID=" + policyID + + ", ruleID=" + ruleID + ", configType=" + configType + ", editPolicy=" + ", version=" + ", domain=" + + domain + ", configPolicyType=" + configPolicyType + ", jsonBody=" + jsonBody + ", highestVersion=" + + highestVersion + ", location=" + location + ",dynamicRuleAlgorithmLabels=" + + dynamicRuleAlgorithmLabels + ",dynamicRuleAlgorithmCombo=" + dynamicRuleAlgorithmCombo + + ",dynamicRuleAlgorithmField1=" + dynamicRuleAlgorithmField1 + ",dynamicRuleAlgorithmField2=" + + dynamicRuleAlgorithmField2 + ",actionPerformer=" + actionPerformer + ",actionAttribute=" + + actionAttribute + ",actionBody=" + actionBody + ",dropDownMap=" + dropDownMap + ",actionDictHeader=" + + actionDictHeader + ",actionDictType=" + actionDictType + ",actionDictUrl=" + actionDictUrl + + ",actionDictMethod=" + actionDictMethod + ",dynamicSettingsMap=" + dynamicSettingsMap + "," + + "dynamicVariableList=" + dynamicVariableList + ",providerComboBox=" + providerComboBox + + ",dataTypeList=" + dataTypeList + ",draft=" + ",oldPolicyFileName=" + oldPolicyFileName + "," + + "serviceType=" + serviceType + ",uuid=" + uuid + ",msLocation=" + msLocation + ",priority=" + priority + + ",deleteCondition=" + deleteCondition + ",dictionaryType=" + dictionaryType + ",dictionary=" + + dictionary + ",dictionaryFields=" + dictionaryFields + ",uuid=" + uuid + "," + "msLocation=" + + msLocation + ",priority=" + priority + ",deleteCondition=" + deleteCondition + ",riskType=" + riskType + + ",riskLevel=" + riskLevel + ",guard=" + guard + ",ttlDate=" + ttlDate + ",treatments=" + treatments + + "]"; } // Methods needed for JSON Deserialization @@ -435,8 +438,7 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable { this.configName = configName; } - public void setDynamicFieldConfigAttributes( - Map<String, String> dynamicFieldConfigAttributes) { + public void setDynamicFieldConfigAttributes(Map<String, String> dynamicFieldConfigAttributes) { this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; } @@ -484,8 +486,7 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable { this.location = location; } - public void setDynamicRuleAlgorithmLabels( - List<String> dynamicRuleAlgorithmLabels) { + public void setDynamicRuleAlgorithmLabels(List<String> dynamicRuleAlgorithmLabels) { this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; } @@ -493,13 +494,11 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable { this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; } - public void setDynamicRuleAlgorithmField1( - List<String> dynamicRuleAlgorithmField1) { + public void setDynamicRuleAlgorithmField1(List<String> dynamicRuleAlgorithmField1) { this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; } - public void setDynamicRuleAlgorithmField2( - List<String> dynamicRuleAlgorithmField2) { + public void setDynamicRuleAlgorithmField2(List<String> dynamicRuleAlgorithmField2) { this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; } @@ -638,7 +637,7 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable { public void setTreatments(Map<String, String> treatments) { this.treatments = treatments; } - + public String getRawXacmlPolicy() { return rawXacmlPolicy; } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java index 1780dfc96..b7057175e 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java @@ -3,7 +3,7 @@ * ONAP-XACML * ================================================================================ * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. - * Modifications Copyright (C) 2018 AT&T Intellectual Property. + * Modifications Copyright (C) 2018-2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,14 +54,14 @@ public class StdPAPPolicyParams { private List<Object> dynamicVariableList; private List<String> dataTypeList; private Map<String, String> dropDownMap; - private Map<String,String> treatments; + private Map<String, String> treatments; private String policyID; private String ruleID; private String version; private String jsonBody; private String brmsController; private List<String> brmsDependency; - private Map<String,String> drlRuleAndUIParams; + private Map<String, String> drlRuleAndUIParams; private boolean draft; private String oldPolicyFileName; private String serviceType; @@ -75,8 +75,7 @@ public class StdPAPPolicyParams { private String rawXacmlPolicy = null; /** - - * Default constructor + * Default constructor. */ private StdPAPPolicyParams() { super(); @@ -186,7 +185,7 @@ public class StdPAPPolicyParams { return providerComboBox; } - public Map<String,String> getDynamicSettingsMap() { + public Map<String, String> getDynamicSettingsMap() { return dynamicSettingsMap; } @@ -198,11 +197,11 @@ public class StdPAPPolicyParams { return dataTypeList; } - public Map<String,String> getDropDownMap() { + public Map<String, String> getDropDownMap() { return dropDownMap; } - public Map<String,String> getTreatments() { + public Map<String, String> getTreatments() { return treatments; } @@ -230,7 +229,7 @@ public class StdPAPPolicyParams { return brmsDependency; } - public Map<String,String> getDrlRuleAndUIParams() { + public Map<String, String> getDrlRuleAndUIParams() { return drlRuleAndUIParams; } @@ -269,8 +268,9 @@ public class StdPAPPolicyParams { public String getRawXacmlPolicy() { return rawXacmlPolicy; } + /** - * Builder class for the Policy parameters + * Builder class for the Policy parameters. */ public static class StdPAPPolicyParamsBuilder { StdPAPPolicyParams m = new StdPAPPolicyParams(); @@ -284,7 +284,6 @@ public class StdPAPPolicyParams { return this; } - public StdPAPPolicyParamsBuilder policyName(String policyName) { m.policyName = policyName; return this; @@ -405,12 +404,12 @@ public class StdPAPPolicyParams { return this; } - public StdPAPPolicyParamsBuilder dropDownMap(Map<String, String> dropDownMap){ + public StdPAPPolicyParamsBuilder dropDownMap(Map<String, String> dropDownMap) { m.dropDownMap = dropDownMap; return this; } - public StdPAPPolicyParamsBuilder treatments(Map<String,String> treatments) { + public StdPAPPolicyParamsBuilder treatments(Map<String, String> treatments) { m.treatments = treatments; return this; } @@ -445,13 +444,13 @@ public class StdPAPPolicyParams { return this; } - public StdPAPPolicyParamsBuilder drlRuleAndUIParams(Map<String,String> drlRuleAndUIParams) { + public StdPAPPolicyParamsBuilder drlRuleAndUIParams(Map<String, String> drlRuleAndUIParams) { m.drlRuleAndUIParams = drlRuleAndUIParams; return this; } - public StdPAPPolicyParamsBuilder draft(boolean b) { - m.draft = b; + public StdPAPPolicyParamsBuilder draft(boolean isDraft) { + m.draft = isDraft; return this; } @@ -460,8 +459,8 @@ public class StdPAPPolicyParams { return this; } - public StdPAPPolicyParamsBuilder serviceType(String s) { - m.serviceType = s; + public StdPAPPolicyParamsBuilder serviceType(String serviceType) { + m.serviceType = serviceType; return this; } @@ -499,7 +498,7 @@ public class StdPAPPolicyParams { m.dictionaryFields = dictionaryFields; return this; } - + public StdPAPPolicyParamsBuilder rawXacmlPolicy(String rawXacmlPolicy) { m.rawXacmlPolicy = rawXacmlPolicy; return this; diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java index 8727b8185..dcebc86fc 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,8 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.std.pap; +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.api.pap.PDPStatus; + import java.io.Serializable; import java.util.Collections; import java.util.HashSet; @@ -27,196 +32,209 @@ import java.util.Set; import org.onap.policy.xacml.api.pap.OnapPDP; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import com.att.research.xacml.api.pap.PDPPIPConfig; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.api.pap.PDPStatus; - public class StdPDP extends StdPDPItemSetChangeNotifier implements OnapPDP, Comparable<StdPDP>, Serializable { - private static final long serialVersionUID = 1L; - private static Logger logger = FlexLogger.getLogger(StdPDP.class); - - private String id; - - private String name; - - private String description; - - private Integer jmxport = 0; - - private transient PDPStatus status = new StdPDPStatus(); - - private transient Set<PDPPolicy> policies = new HashSet<>(); - - private transient Set<PDPPIPConfig> pipConfigs = new HashSet<>(); - - public StdPDP() { - // - // Default constructor - // - } - - public StdPDP(String id, Integer jmxport) { - this(id, null, null, jmxport); - } - - public StdPDP(String id, String name, Integer jmxport) { - this(id, name, null, jmxport); - } - - public StdPDP(String id, String name, String description, Integer jmxport) { - this.id = id; - this.name = name; - this.description = description; - if(jmxport != null){ - this.jmxport = jmxport; - } - } - - public StdPDP(String id, Properties properties) { - this(id, 0); - - this.initialize(properties); - } - - public void initialize(Properties properties) { - for (Object key : properties.keySet()) { - if (key.toString().startsWith(this.id + ".")) { - if (logger.isDebugEnabled()) { - logger.debug("Found: " + key); - } - if (key.toString().endsWith(".name")) { - this.name = properties.getProperty(key.toString()); - } else if (key.toString().endsWith(".description")) { - this.description = properties.getProperty(key.toString()); - }else if (key.toString().endsWith(".jmxport")) { - if (properties.getProperty(key.toString()) != null && properties.getProperty(key.toString()).trim().length() > 0){ - logger.debug("initialize before: " + this.jmxport); - this.jmxport = Integer.valueOf( properties.getProperty(key.toString())); - logger.debug("initialize after: " + this.jmxport); - }else{ - this.jmxport = 0; - } - } - } - } - } - - @Override - public String getId() { - return this.id; - } - - public void setId(String id) { - this.id=id; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public void setName(String name) { - this.name = name; - this.firePDPChanged(this); - } - - @Override - public String getDescription() { - return this.description; - } - - @Override - public void setDescription(String description) { - this.description = description; - this.firePDPChanged(this); - } - - @Override - public PDPStatus getStatus() { - return this.status; - } - - public void setStatus(PDPStatus status) { - this.status = status; - } - - @Override - public Set<PDPPolicy> getPolicies() { - return Collections.unmodifiableSet(this.policies); - } - - public void setPolicies(Set<PDPPolicy> policies) { - this.policies = policies; - } - - @Override - public Set<PDPPIPConfig> getPipConfigs() { - return Collections.unmodifiableSet(this.pipConfigs); - } - - public void setPipConfigs(Set<PDPPIPConfig> pipConfigs) { - this.pipConfigs = pipConfigs; - } - - @Override - public void setJmxPort(Integer jmxport) { - this.jmxport = jmxport; - } - @Override - public Integer getJmxPort() { - return this.jmxport; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDP other = (StdPDP) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDP [id=" + id + ", name=" + name + ", description=" - + description + ", jmxport=" + jmxport + ", status=" + status + ", policies=" + policies - + ", pipConfigs=" + pipConfigs + "]"; - } - - // - // Comparable interface - // - @Override - public int compareTo(StdPDP o) { - if (o == null) { - return -1; - } - if (o.name == null) { - return -1; - } - if (name == null) { - return 1; - } - return name.compareTo(o.name); - } - + private static final long serialVersionUID = 1L; + + private String id; + + private String name; + + private String description; + + private Integer jmxport = 0; + + private transient PDPStatus status = new StdPDPStatus(); + + private transient Set<PDPPolicy> policies = new HashSet<>(); + + private transient Set<PDPPIPConfig> pipConfigs = new HashSet<>(); + + public StdPDP() { + // + // Default constructor + // + } + + public StdPDP(String id, Integer jmxport) { + this(id, null, null, jmxport); + } + + public StdPDP(String id, String name, Integer jmxport) { + this(id, name, null, jmxport); + } + + /** + * StdPDP. + * + * @param id String + * @param name String + * @param description String + * @param jmxport Integer + */ + public StdPDP(String id, String name, String description, Integer jmxport) { + this.id = id; + this.name = name; + this.description = description; + if (jmxport != null) { + this.jmxport = jmxport; + } + } + + /** + * StdPDP. + * + * @param id String + * @param properties Properties + */ + public StdPDP(String id, Properties properties) { + this(id, 0); + + this.initialize(properties); + } + + /** + * initialize. + * + * @param properties Properties + */ + public void initialize(Properties properties) { + for (Object key : properties.keySet()) { + if (key.toString().startsWith(this.id + ".")) { + if (key.toString().endsWith(".name")) { + this.name = properties.getProperty(key.toString()); + } else if (key.toString().endsWith(".description")) { + this.description = properties.getProperty(key.toString()); + } else if (key.toString().endsWith(".jmxport")) { + if (properties.getProperty(key.toString()) != null + && properties.getProperty(key.toString()).trim().length() > 0) { + this.jmxport = Integer.valueOf(properties.getProperty(key.toString())); + } else { + this.jmxport = 0; + } + } + } + } + } + + @Override + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public void setName(String name) { + this.name = name; + this.firePDPChanged(this); + } + + @Override + public String getDescription() { + return this.description; + } + + @Override + public void setDescription(String description) { + this.description = description; + this.firePDPChanged(this); + } + + @Override + public PDPStatus getStatus() { + return this.status; + } + + public void setStatus(PDPStatus status) { + this.status = status; + } + + @Override + public Set<PDPPolicy> getPolicies() { + return Collections.unmodifiableSet(this.policies); + } + + public void setPolicies(Set<PDPPolicy> policies) { + this.policies = policies; + } + + @Override + public Set<PDPPIPConfig> getPipConfigs() { + return Collections.unmodifiableSet(this.pipConfigs); + } + + public void setPipConfigs(Set<PDPPIPConfig> pipConfigs) { + this.pipConfigs = pipConfigs; + } + + @Override + public void setJmxPort(Integer jmxport) { + this.jmxport = jmxport; + } + + @Override + public Integer getJmxPort() { + return this.jmxport; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + StdPDP other = (StdPDP) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "StdPDP [id=" + id + ", name=" + name + ", description=" + description + ", jmxport=" + jmxport + + ", status=" + status + ", policies=" + policies + ", pipConfigs=" + pipConfigs + "]"; + } + + // + // Comparable interface + // + @Override + public int compareTo(StdPDP object) { + if (object == null) { + return -1; + } + if (object.name == null) { + return -1; + } + if (name == null) { + return 1; + } + return name.compareTo(object.name); + } + } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java index bdbbf33f7..d406a5498 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,8 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.std.pap; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPGroupStatus; +import com.att.research.xacml.api.pap.PDPGroupStatus.Status; +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.google.common.base.Joiner; +import com.google.common.base.Splitter; +import com.google.common.io.ByteStreams; + import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @@ -35,7 +48,8 @@ import java.util.List; import java.util.Properties; import java.util.Set; import java.util.TreeSet; - +import lombok.EqualsAndHashCode; +import lombok.ToString; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.policy.common.logging.eelf.MessageCodes; @@ -45,1000 +59,1038 @@ import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDP; -import com.att.research.xacml.api.pap.PDPGroupStatus; -import com.att.research.xacml.api.pap.PDPGroupStatus.Status; -import com.att.research.xacml.api.pap.PDPPIPConfig; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.google.common.base.Joiner; -import com.google.common.base.Splitter; -import com.google.common.io.ByteStreams; +@EqualsAndHashCode(callSuper=false) +@ToString +public class StdPDPGroup extends StdPDPItemSetChangeNotifier + implements OnapPDPGroup, StdItemSetChangeListener, Comparable<Object>, Serializable { + + private static final long serialVersionUID = 1L; + private static final String groupNotExist = "Group directory does NOT exist"; + private static Log logger = LogFactory.getLog(StdPDPGroup.class); + + private String id; + + private boolean isDefault = false; + + private String name; + + private String description; + + private transient StdPDPGroupStatus status = new StdPDPGroupStatus(Status.UNKNOWN); + + private transient Set<OnapPDP> pdps = new HashSet<>(); + + private transient Set<PDPPolicy> policies = new HashSet<>(); + + private transient Set<PDPPolicy> selectedPolicies = new HashSet<>(); + + private transient Set<PDPPIPConfig> pipConfigs = new HashSet<>(); + + private String operation; + + @JsonIgnore + private transient Path directory; + + @JsonIgnore + private Integer jmxport; + + public StdPDPGroup() { + // + // Methods needed for JSON deserialization + // + } + + /** + * StdPDPGroup constructor. + * + * @param group OnapPDPGroup + */ + public StdPDPGroup(OnapPDPGroup group) { + this.id = group.getId(); + this.name = group.getName(); + this.description = group.getDescription(); + this.isDefault = group.isDefaultGroup(); + this.pdps = group.getOnapPdps(); + this.policies = group.getPolicies(); + this.pipConfigs = group.getPipConfigs(); + } + + public StdPDPGroup(String id, Path directory) { + this.id = id; + this.directory = directory; + } + + public StdPDPGroup(String id, boolean isDefault, Path directory) { + this(id, directory); + this.isDefault = isDefault; + } + + /** + * StdPDPGroup. + * + * @param id String + * @param isDefault boolean + * @param name String + * @param description String + * @param directory Path + */ + public StdPDPGroup(String id, boolean isDefault, String name, String description, Path directory) { + this(id, isDefault, directory); + this.name = name; + // force all policies to have a name + if (name == null) { + this.name = id; + } + this.description = description; + } + + public StdPDPGroup(String id, String name, String description, Path directory) { + this(id, false, name, description, directory); + this.resetStatus(); + } + + /** + * StdPDPGroup. + * + * @param id String + * @param isDefault boolean + * @param properties Properties + * @param directory Path + * @throws PAPException PAPException + */ + public StdPDPGroup(String id, boolean isDefault, Properties properties, Path directory) throws PAPException { + this(id, isDefault, directory); + this.initialize(properties, directory); + this.resetStatus(); + } + + private void initialize(Properties properties, Path directory) throws PAPException { + if (this.id == null || this.id.length() == 0) { + logger.warn("Cannot initialize with a null or zero length id"); + return; + } + // + // Pull the group's properties + // + for (Object key : properties.keySet()) { + if (key.toString().startsWith(this.id + ".")) { + if (key.toString().endsWith(".name")) { + this.name = properties.getProperty(key.toString()); + } else if (key.toString().endsWith(".description")) { + this.description = properties.getProperty(key.toString()); + } else if (key.toString().endsWith(".pdps")) { + String pdpList = properties.getProperty(key.toString()); + if (pdpList != null && pdpList.length() > 0) { + for (String pdpId : Splitter.on(',').omitEmptyStrings().trimResults().split(pdpList)) { + StdPDP pdp = new StdPDP(pdpId, properties); + pdp.addItemSetChangeListener(this); + this.pdps.add(pdp); + } + } + } + } + // force all policies to have a name + if (this.name == null) { + this.name = this.id; + } + } + // + // Validate our directory + // + if (Files.notExists(directory)) { + logger.warn("Group directory does NOT exist: " + directory.toString()); + try { + Files.createDirectory(directory); + this.status.addLoadWarning(groupNotExist); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", groupNotExist); + this.status.addLoadError(groupNotExist); + this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); + } + } + // + // Parse policies + // + this.loadPolicies(Paths.get(directory.toString(), "xacml.policy.properties")); + // + // Parse pip config + // + this.loadPIPConfig(Paths.get(directory.toString(), "xacml.pip.properties")); + } + + /** + * loadPolicies. + * + * @param file Path + * @throws PAPException PAPException + */ + public void loadPolicies(Path file) throws PAPException { + // + // Read the Groups Policies + // + Properties policyProperties = new Properties(); + if (!file.toFile().exists()) { + // need to create the properties file with default values + policyProperties.setProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); + policyProperties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); + // save properties to file + try (OutputStream os = Files.newOutputStream(file)) { + policyProperties.store(os, ""); + } catch (Exception e) { + throw new PAPException("Failed to create new default policy properties file '" + file + "'", e); + } + } else { + // load previously existing file + try { + // + // Load the properties + // + try (InputStream is = Files.newInputStream(file)) { + policyProperties.load(is); + } + // + // Parse the policies + // + this.readPolicyProperties(directory, policyProperties); + } catch (IOException e) { + logger.warn("Failed to load group policy properties file: " + file, e); + this.status.addLoadError("Not policy properties defined"); + this.status.setStatus(Status.LOAD_ERRORS); + throw new PAPException("Failed to load group policy properties file: " + file); + } + } + } + + /** + * loadPIPConfig. + * + * @param file Path + * @throws PAPException PAPException + */ + public void loadPIPConfig(Path file) throws PAPException { + // + // Read the Groups' PIP configuration + // + Properties pipProperties = new Properties(); + if (!file.toFile().exists()) { + // need to create the properties file with no values + pipProperties = setPipProperties(pipProperties); + // save properties to file + try { + try (OutputStream os = Files.newOutputStream(file)) { + pipProperties.store(os, ""); + } + } catch (Exception e) { + throw new PAPException("Failed to create new default pip properties file '" + file + "'", e); + } + // Even if we create a new pip file, we still need to parse and load the properties + try { + this.readPipProperties(pipProperties); + } catch (Exception e) { + throw new PAPException("Failed to load the new pip properties file", e); + } + } else { + try { + // + // Load the properties + // + try (InputStream is = Files.newInputStream(file)) { + pipProperties.load(is); + } + // For all old PIP config's modify to the new PIP Configuration. + // If PIP is empty add the new values and save it. + if ("".equals(pipProperties.get(XACMLProperties.PROP_PIP_ENGINES).toString().trim())) { + pipProperties = setPipProperties(pipProperties); + try (OutputStream os = Files.newOutputStream(file)) { + pipProperties.store(os, ""); + } + } + // + // Parse the pips + // + this.readPipProperties(pipProperties); + } catch (IOException e) { + logger.warn("Failed to open group PIP Config properties file: " + file, e); + this.status.addLoadError("Not PIP config properties defined"); + this.status.setStatus(Status.LOAD_ERRORS); + throw new PAPException("Failed to load group policy properties file: " + file); + + } + } + } + + /** + * resetStatus. + */ + public void resetStatus() { + // + // Reset our status object + // + this.status.reset(); + // + // Determine our status + // + for (PDP pdp : this.pdps) { + switch (pdp.getStatus().getStatus()) { + case OUT_OF_SYNCH: + this.status.addOutOfSynchPDP(pdp); + break; + case LAST_UPDATE_FAILED: + this.status.addLastUpdateFailedPDP(pdp); + break; + case LOAD_ERRORS: + this.status.addFailedPDP(pdp); + break; + case UPDATING_CONFIGURATION: + this.status.addUpdatingPDP(pdp); + break; + case UP_TO_DATE: + this.status.addInSynchPDP(pdp); + break; + case UNKNOWN: + case CANNOT_CONNECT: + case NO_SUCH_HOST: + default: + this.status.addUnknownPDP(pdp); + break; + } + } + + // priority is worst-cast to best case + if (!this.status.getUnknownPDPs().isEmpty()) { + this.status.setStatus(Status.UNKNOWN); + } else if (!this.status.getFailedPDPs().isEmpty() || !this.status.getLastUpdateFailedPDPs().isEmpty()) { + this.status.setStatus(Status.LOAD_ERRORS); + } else if (!this.status.getOutOfSynchPDPs().isEmpty()) { + this.status.setStatus(Status.OUT_OF_SYNCH); + } else if (!this.status.getUpdatingPDPs().isEmpty()) { + this.status.setStatus(Status.UPDATING_CONFIGURATION); + } else { + this.status.setStatus(Status.OK); + } + } + + @Override + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public boolean isDefaultGroup() { + return this.isDefault; + } + + /** + * setDefaultGroup. + * + * @param isDefault boolean + */ + public void setDefaultGroup(boolean isDefault) { + this.isDefault = isDefault; + // + // Cannot fire this because 2 operations have + // to occur: 1) old default=false (don't want to fire) and + // then 2) new default=true (yes fire - but we'll have to do that + // elsewhere. + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String groupName) { + this.name = groupName; + this.firePDPGroupChanged(this); + } + + @Override + public String getDescription() { + return this.description; + } + + @Override + public void setDescription(String groupDescription) { + this.description = groupDescription; + this.firePDPGroupChanged(this); + } + + public Path getDirectory() { + return this.directory; + } + + public void setDirectory(Path groupDirectory) { + this.directory = groupDirectory; + // this is used only for transmission on the RESTful interface, so no need to fire group changed? + } + + @Override + public PDPGroupStatus getStatus() { + return this.status; + } + + @Override + public Set<PDPPolicy> getSelectedPolicies() { + return this.selectedPolicies; + } + + @Override + public String getOperation() { + return this.operation; + } + + @Override + public Set<PDP> getPdps() { + return Collections.unmodifiableSet(pdps); + } + + public void setOnapPdps(Set<OnapPDP> pdps) { + this.pdps = pdps; + } + + @Override + public Set<OnapPDP> getOnapPdps() { + return Collections.unmodifiableSet(pdps); + } + + public boolean addPDP(OnapPDP pdp) { + return this.pdps.add(pdp); + } + + public boolean removePDP(PDP pdp) { + return this.pdps.remove(pdp); + } + + @Override + public Set<PDPPolicy> getPolicies() { + return Collections.unmodifiableSet(this.policies); + } + + @Override + public PDPPolicy getPolicy(String id) { + for (PDPPolicy policy : this.policies) { + if (policy.getId().equals(id)) { + return policy; + } + } + return null; + } + + @Override + public Properties getPolicyProperties() { + Properties properties = new Properties() { + private static final long serialVersionUID = 1L; + + // For Debugging it is helpful for the file to be in a sorted order, + // any by returning the keys in the natural Alpha order for strings we get close enough. + // TreeSet is sorted, and this just overrides the normal Properties method to get the keys. + @Override + public synchronized Enumeration<Object> keys() { + return Collections.enumeration(new TreeSet<Object>(super.keySet())); + } + }; + List<String> roots = new ArrayList<>(); + List<String> refs = new ArrayList<>(); + + for (PDPPolicy policy : this.policies) { + // for all policies need to tell PDP the "name", which is the base name for the file id + if (policy.getName() != null) { + properties.setProperty(policy.getId() + ".name", policy.getName()); + } + // put the policy on the correct list + if (policy.isRoot()) { + roots.add(policy.getId()); + } else { + refs.add(policy.getId()); + } + } + + properties.setProperty(XACMLProperties.PROP_ROOTPOLICIES, Joiner.on(',').join(roots)); + properties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, Joiner.on(',').join(refs)); + + return properties; + } + + /** + * publishPolicy. + * + * @param id String + * @param name String + * @param isRoot boolean + * @param policy InputStream + * @return PDPPolicy + * @throws PAPException PAPException + */ + public PDPPolicy publishPolicy(String id, String name, boolean isRoot, InputStream policy) throws PAPException { + // + // Does it exist already? + // + if (this.getPolicy(id) != null) { + throw new PAPException("Policy with id " + id + " already exists - unpublish it first."); + } + Path tempFile = null; + try { + // + // Copy the policy over + // + tempFile = Files.createFile(Paths.get(this.directory.toAbsolutePath().toString(), id)); + long num; + try (OutputStream os = Files.newOutputStream(tempFile)) { + num = ByteStreams.copy(policy, os); + } + logger.info("Copied " + num + " bytes for policy " + name); + + StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, isRoot, name, tempFile.toUri()); + if (!tempRootPolicy.isValid()) { + try { + Files.delete(tempFile); + } catch (Exception ee) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", + "Policy was invalid, could NOT delete it."); + } + throw new PAPException("Policy is invalid"); + } + // + // Add it in + // + this.policies.add(tempRootPolicy); + // + // We are changed + // + this.firePDPGroupChanged(this); + // + // Return our new object. + // + return tempRootPolicy; + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdPDPGroup", "Failed to publishPolicy"); + } + return null; + } + + /** + * Copy one policy file into the Group's directory but do not change the configuration. + * This is one part of a multi-step process of publishing policies. + * There may be multiple changes in the group (adding multiple policies, deleting policies, changine + * root<->referenced) + * that must be done all at once, so we just copy the file in preparation for a later "update whole group" + * operation. + * + * @param id String + * @param policy InputStream + * @throws PAPException PAPException + */ + public void copyPolicyToFile(String id, InputStream policy) throws PAPException { + try { + // + // Copy the policy over + // + long num; + Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id); + + Path policyFile; + if (Files.exists(policyFilePath)) { + policyFile = policyFilePath; + } else { + policyFile = Files.createFile(policyFilePath); + } + + try (OutputStream os = Files.newOutputStream(policyFile)) { + num = ByteStreams.copy(policy, os); + } + + logger.info("Copied " + num + " bytes for policy " + name); + + for (PDPPolicy p : policies) { + if (p.getId().equals(id)) { + // we just re-copied/refreshed/updated the policy file for a policy that already exists in this + // group + logger.info("Policy '" + id + "' already exists in group '" + getId() + "'"); + return; + } + } + + // policy is new to this group + StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri()); + if (!tempRootPolicy.isValid()) { + try { + Files.delete(policyFile); + } catch (Exception ee) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", + "Policy was invalid, could NOT delete it."); + } + throw new PAPException("Policy is invalid"); + } + // + // Add it in + // + this.policies.add(tempRootPolicy); + // + // We are changed + // + this.firePDPGroupChanged(this); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to copyPolicyToFile"); + throw new PAPException("Failed to copy policy to file: " + e); + } + } + + /** + * Policy Engine API Copy one policy file into the Group's directory but do not change the configuration. + * + * @param id String + * @param name String + * @param policy InputStream + * @throws PAPException PAPException + */ + public void copyPolicyToFile(String id, String name, InputStream policy) throws PAPException { + try { + // + // Copy the policy over + // + long num; + Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id); + + Path policyFile; + if (Files.exists(policyFilePath)) { + policyFile = policyFilePath; + } else { + policyFile = Files.createFile(policyFilePath); + } + + try (OutputStream os = Files.newOutputStream(policyFile)) { + num = ByteStreams.copy(policy, os); + } + + logger.info("Copied " + num + " bytes for policy " + name); + for (PDPPolicy p : policies) { + if (p.getId().equals(id)) { + // we just re-copied/refreshed/updated the policy file for a policy that already exists in this + // group + logger.info("Policy '" + id + "' already exists in group '" + getId() + "'"); + return; + } + } + + // policy is new to this group + StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri()); + if (!tempRootPolicy.isValid()) { + try { + Files.delete(policyFile); + } catch (Exception ee) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", + "Policy was invalid, could NOT delete it."); + } + throw new PAPException("Policy is invalid"); + } + // + // Add it in + // + this.policies.add(tempRootPolicy); + // + // We are changed + // + this.firePDPGroupChanged(this); + + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to copyPolicyToFile"); + throw new PAPException("Failed to copy policy to file: " + e); + } + } + + /** + * removePolicyFromGroup. + * + * @param policy PDPPolicy + * @return boolean + */ + public boolean removePolicyFromGroup(PDPPolicy policy) { + PolicyLogger.info("policy: " + policy.getId()); + PolicyLogger.info("Policy ID:" + policy.getPolicyId()); + PolicyLogger.info("Policy Version: " + policy.getVersion()); + PolicyLogger.info("StdPDPPolicy Class cast: " + this.getPolicy(policy.getId()).toString()); + StdPDPPolicy currentPolicy = (StdPDPPolicy) this.getPolicy(policy.getId()); + if (currentPolicy == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Policy " + policy.getId() + " does not exist."); + return false; + } + try { + // + // Remove it from our list + // + this.policies.remove(currentPolicy); + // + // We are changed + // + this.firePDPGroupChanged(this); + return true; + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy"); + } + return false; + } + + /** + * removePolicy. + * + * @param policy PDPPolicy + * @return boolean + */ + public boolean removePolicy(PDPPolicy policy) { + PDPPolicy currentPolicy = this.getPolicy(policy.getId()); + if (currentPolicy == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Policy " + policy.getId() + " does not exist."); + return false; + } + try { + // + // Delete it on disk + // + Files.delete(Paths.get(currentPolicy.getLocation())); + // + // Remove it from our list + // + this.policies.remove(currentPolicy); + // + // We are changed + // + this.firePDPGroupChanged(this); + return true; + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy " + policy); + } + return false; + } + + @Override + public Set<PDPPIPConfig> getPipConfigs() { + return Collections.unmodifiableSet(this.pipConfigs); + } + + @Override + public PDPPIPConfig getPipConfig(String id) { + for (PDPPIPConfig config : this.pipConfigs) { + if (config.getId().equals(id)) { + return config; + } + } + return null; + } + + public void setPipConfigs(Set<PDPPIPConfig> pipConfigs) { + this.pipConfigs = pipConfigs; + this.firePDPGroupChanged(this); + } + + public void removeAllPIPConfigs() { + this.pipConfigs.clear(); + this.firePDPGroupChanged(this); + } + + @Override + public Properties getPipConfigProperties() { + Properties properties = new Properties(); + List<String> configs = new ArrayList<>(); + + for (PDPPIPConfig config : this.pipConfigs) { + configs.add(config.getId()); + properties.putAll(config.getConfiguration()); + } + + properties.setProperty(XACMLProperties.PROP_PIP_ENGINES, Joiner.on(',').join(configs)); + + return properties; + } + + @Override + public void repair() { + // + // Reset the status object + // + this.status.reset(); + // + // Validate our directory + // + boolean fire = false; + if (Files.notExists(directory)) { + logger.warn("Group directory does NOT exist: " + directory.toString()); + try { + Files.createDirectory(directory); + fire = true; + this.status.addLoadWarning("Created missing group directory"); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", + "Failed to create missing Group directory."); + this.status.addLoadError("Failed to create missing Group directory."); + this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); + } + } + // + // Validate our PIP config file + // + Path pipPropertiesFile = Paths.get(directory.toString(), "xacml.pip.properties"); + if (Files.notExists(pipPropertiesFile)) { + try { + Files.createFile(pipPropertiesFile); + fire = true; + this.status.addLoadWarning("Created missing PIP properties file"); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", + "Failed to create missing PIP properties file"); + this.status.addLoadError("Failed to create missing PIP properties file"); + this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); + } + } + // + // Valid our policy properties file + // + Path policyPropertiesFile = Paths.get(directory.toString(), "xacml.policy.properties"); + if (Files.notExists(policyPropertiesFile)) { + try { + Files.createFile(policyPropertiesFile); + fire = true; + this.status.addLoadWarning("Created missing Policy properties file"); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", + "Failed to create missing Policy properties file"); + this.status.addLoadError("Failed to create missing Policy properties file"); + this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); + } + } + this.resetStatus(); + if (fire) { + this.fireChanged(); + } + } + + private void readPolicyProperties(Path directory, Properties properties) { + // + // There are 2 property values that hold policies, root and referenced + // + String[] lists = new String[2]; + lists[0] = properties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); + lists[1] = properties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + // + // Iterate each policy list + // + boolean isRoot = true; + for (String list : lists) { + // + // Was there actually a property? + // + if (list == null || list.length() == 0) { + isRoot = false; + continue; + } + // + // Parse it out + // + Iterable<String> policyList = Splitter.on(',').trimResults().omitEmptyStrings().split(list); + // + // Was there actually a list + // + if (policyList == null) { + isRoot = false; + continue; + } + for (String policyId : policyList) { + // + // Construct the policy filename + // + Path policyPath = Paths.get(directory.toString(), policyId); + // + // Create the Policy Object + // + StdPDPPolicy policy; + try { + policy = new StdPDPPolicy(id, isRoot, policyPath.toUri(), properties); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", + "Failed to create policy object"); + policy = null; + } + // + // Is it valid? + // + if (policy != null && policy.isValid()) { + this.policies.add(policy); + this.status.addLoadedPolicy(policy); + } else { + this.status.addFailedPolicy(policy); + this.status.setStatus(Status.LOAD_ERRORS); + } + // force all policies to have a name + if (policy != null && policy.getName() == null) { + policy.setName(policy.getId()); + } + } + isRoot = false; + } + } + + private void readPipProperties(Properties properties) { + String list = properties.getProperty(XACMLProperties.PROP_PIP_ENGINES); + if (list == null || list.length() == 0) { + return; + } + for (String pipId : list.split("[,]")) { + StdPDPPIPConfig config = new StdPDPPIPConfig(pipId, properties); + if (config.isConfigured()) { + this.pipConfigs.add(config); + this.status.addLoadedPipConfig(config); + } else { + this.status.addFailedPipConfig(config); + this.status.setStatus(Status.LOAD_ERRORS); + } + } + } + + @Override + public void changed() { + + // save the (changed) properties + try { + saveGroupConfiguration(); + } catch (PAPException | IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdPDPGroup", + "Unable to save group configuration change"); + // don't notify other things of change if we cannot save it??? + return; + } + + this.firePDPGroupChanged(this); + + } + + @Override + public void groupChanged(OnapPDPGroup group) { + this.changed(); + } + + @Override + public void pdpChanged(OnapPDP pdp) { + // + // If one of the group's PDP's changed, then the group changed + // + this.changed(); + } + + public boolean isDefault() { + return isDefault; + } -public class StdPDPGroup extends StdPDPItemSetChangeNotifier implements OnapPDPGroup, StdItemSetChangeListener, Comparable<Object>, Serializable { - - private static final long serialVersionUID = 1L; - private static final String groupNotExist= "Group directory does NOT exist"; - private static Log logger = LogFactory.getLog(StdPDPGroup.class); - - private String id; - - private boolean isDefault = false; - - private String name; - - private String description; - - private transient StdPDPGroupStatus status = new StdPDPGroupStatus(Status.UNKNOWN); - - private transient Set<OnapPDP> pdps = new HashSet<>(); - - private transient Set<PDPPolicy> policies = new HashSet<>(); - - private transient Set<PDPPolicy> selectedPolicies = new HashSet<>(); - - private transient Set<PDPPIPConfig> pipConfigs = new HashSet<>(); - - private String operation; - - @JsonIgnore - private transient Path directory; - - @JsonIgnore - private Integer jmxport; - - public StdPDPGroup() { - // - // Methods needed for JSON deserialization - // - } - - public StdPDPGroup(OnapPDPGroup group) { - this.id = group.getId(); - this.name = group.getName(); - this.description = group.getDescription(); - this.isDefault = group.isDefaultGroup(); - this.pdps = group.getOnapPdps(); - this.policies = group.getPolicies(); - this.pipConfigs = group.getPipConfigs(); - } - - public StdPDPGroup(String id, Path directory) { - this.id = id; - this.directory = directory; - } - - public StdPDPGroup(String id, boolean isDefault, Path directory) { - this(id, directory); - this.isDefault = isDefault; - } - - public StdPDPGroup(String id, boolean isDefault, String name, String description, Path directory) { - this(id, isDefault, directory); - this.name = name; - // force all policies to have a name - if (name == null) { - this.name = id; - } - this.description = description; - } - - public StdPDPGroup(String id, String name, String description, Path directory) { - this(id, false, name, description, directory); - this.resetStatus(); - } - - public StdPDPGroup(String id, boolean isDefault, Properties properties, Path directory) throws PAPException { - this(id, isDefault, directory); - this.initialize(properties, directory); - this.resetStatus(); - } - - private void initialize(Properties properties, Path directory) throws PAPException { - if (this.id == null || this.id.length() == 0) { - logger.warn("Cannot initialize with a null or zero length id"); - return; - } - // - // Pull the group's properties - // - for (Object key : properties.keySet()) { - if (key.toString().startsWith(this.id + ".")) { - if (key.toString().endsWith(".name")) { - this.name = properties.getProperty(key.toString()); - } else if (key.toString().endsWith(".description")) { - this.description = properties.getProperty(key.toString()); - } else if (key.toString().endsWith(".pdps")) { - String pdpList = properties.getProperty(key.toString()); - if (pdpList != null && pdpList.length() > 0) { - for (String pdpId : Splitter.on(',').omitEmptyStrings().trimResults().split(pdpList)) { - StdPDP pdp = new StdPDP(pdpId, properties); - pdp.addItemSetChangeListener(this); - this.pdps.add(pdp); - } - } - } - } - // force all policies to have a name - if (this.name == null) { - this.name = this.id; - } - } - // - // Validate our directory - // - if (Files.notExists(directory)) { - logger.warn("Group directory does NOT exist: " + directory.toString()); - try { - Files.createDirectory(directory); - this.status.addLoadWarning(groupNotExist); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", groupNotExist); - this.status.addLoadError(groupNotExist); - this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); - } - } - // - // Parse policies - // - this.loadPolicies(Paths.get(directory.toString(), "xacml.policy.properties")); - // - // Parse pip config - // - this.loadPIPConfig(Paths.get(directory.toString(), "xacml.pip.properties")); - } - - public void loadPolicies(Path file) throws PAPException { - // - // Read the Groups Policies - // - Properties policyProperties = new Properties(); - if ( ! file.toFile().exists()) { - // need to create the properties file with default values - policyProperties.setProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); - policyProperties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); - // save properties to file - try (OutputStream os = Files.newOutputStream(file)) { - policyProperties.store(os, ""); - } catch (Exception e) { - throw new PAPException("Failed to create new default policy properties file '" + file +"'", e); - } - } else { - // load previously existing file - try { - // - // Load the properties - // - try (InputStream is = Files.newInputStream(file)) { - policyProperties.load(is); - } - // - // Parse the policies - // - this.readPolicyProperties(directory, policyProperties); - } catch (IOException e) { - logger.warn("Failed to load group policy properties file: " + file, e); - this.status.addLoadError("Not policy properties defined"); - this.status.setStatus(Status.LOAD_ERRORS); - throw new PAPException("Failed to load group policy properties file: " + file); - } - } - } - - public void loadPIPConfig(Path file) throws PAPException { - // - // Read the Groups' PIP configuration - // - Properties pipProperties = new Properties(); - if ( ! file.toFile().exists()) { - // need to create the properties file with no values - pipProperties = setPIPProperties(pipProperties); - // save properties to file - try { - try (OutputStream os = Files.newOutputStream(file)) { - pipProperties.store(os, ""); - } - } catch (Exception e) { - throw new PAPException("Failed to create new default pip properties file '" + file +"'", e); - } - //Even if we create a new pip file, we still need to parse and load the properties - try{ - this.readPIPProperties(pipProperties); - }catch(Exception e){ - throw new PAPException("Failed to load the new pip properties file", e); - } - } else { - try { - // - // Load the properties - // - try (InputStream is = Files.newInputStream(file)) { - pipProperties.load(is); - } - // For all old PIP config's modify to the new PIP Configuration. - // If PIP is empty add the new values and save it. - if("".equals(pipProperties.get(XACMLProperties.PROP_PIP_ENGINES).toString().trim())){ - pipProperties = setPIPProperties(pipProperties); - try (OutputStream os = Files.newOutputStream(file)) { - pipProperties.store(os, ""); - } - } - // - // Parse the pips - // - this.readPIPProperties(pipProperties); - } catch (IOException e) { - logger.warn("Failed to open group PIP Config properties file: " + file, e); - this.status.addLoadError("Not PIP config properties defined"); - this.status.setStatus(Status.LOAD_ERRORS); - throw new PAPException("Failed to load group policy properties file: " + file); - - } - } - } - - public void resetStatus() { - // - // Reset our status object - // - this.status.reset(); - // - // Determine our status - // - for (PDP pdp : this.pdps) { - switch (pdp.getStatus().getStatus()) { - case OUT_OF_SYNCH: - this.status.addOutOfSynchPDP(pdp); - break; - case LAST_UPDATE_FAILED: - this.status.addLastUpdateFailedPDP(pdp); - break; - case LOAD_ERRORS: - this.status.addFailedPDP(pdp); - break; - case UPDATING_CONFIGURATION: - this.status.addUpdatingPDP(pdp); - break; - case UP_TO_DATE: - this.status.addInSynchPDP(pdp); - break; - case UNKNOWN: - case CANNOT_CONNECT: - case NO_SUCH_HOST: - default: - this.status.addUnknownPDP(pdp); - break; - } - } - - // priority is worst-cast to best case - if (!this.status.getUnknownPDPs().isEmpty()) { - this.status.setStatus(Status.UNKNOWN); - } else if (!this.status.getFailedPDPs().isEmpty() || !this.status.getLastUpdateFailedPDPs().isEmpty()) { - this.status.setStatus(Status.LOAD_ERRORS); - } else if (!this.status.getOutOfSynchPDPs().isEmpty()) { - this.status.setStatus(Status.OUT_OF_SYNCH); - } else if (!this.status.getUpdatingPDPs().isEmpty()) { - this.status.setStatus(Status.UPDATING_CONFIGURATION); - } else { - this.status.setStatus(Status.OK); - } - } - - @Override - public String getId() { - return this.id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public boolean isDefaultGroup() { - return this.isDefault; - } - - public void setDefaultGroup(boolean isDefault) { - this.isDefault = isDefault; - // - // Cannot fire this because 2 operations have - // to occur: 1) old default=false (don't want to fire) and - // then 2) new default=true (yes fire - but we'll have to do that - // elsewhere. - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String groupName) { - this.name = groupName; - this.firePDPGroupChanged(this); - } - - @Override - public String getDescription() { - return this.description; - } - - @Override - public void setDescription(String groupDescription) { - this.description = groupDescription; - this.firePDPGroupChanged(this); - } - - public Path getDirectory() { - return this.directory; - } - - public void setDirectory(Path groupDirectory) { - this.directory = groupDirectory; - // this is used only for transmission on the RESTful interface, so no need to fire group changed? - } - - @Override - public PDPGroupStatus getStatus(){ - return this.status; - } - - @Override - public Set<PDPPolicy> getSelectedPolicies() { - return this.selectedPolicies; - } - - @Override - public String getOperation() { - return this.operation; - } - - @Override - public Set<PDP> getPdps() { - return Collections.unmodifiableSet(pdps); - } - - public void setOnapPdps(Set<OnapPDP> pdps) { - this.pdps = pdps; - } - - @Override - public Set<OnapPDP> getOnapPdps(){ - return Collections.unmodifiableSet(pdps); - } - - public boolean addPDP(OnapPDP pdp) { - return this.pdps.add(pdp); - } - - public boolean removePDP(PDP pdp) { - return this.pdps.remove(pdp); - } - - @Override - public Set<PDPPolicy> getPolicies() { - return Collections.unmodifiableSet(this.policies); - } - - @Override - public PDPPolicy getPolicy(String id) { - for (PDPPolicy policy : this.policies) { - if (policy.getId().equals(id)) { - return policy; - } - } - return null; - } - - @Override - public Properties getPolicyProperties() - { - Properties properties = new Properties(){ - private static final long serialVersionUID = 1L; - // For Debugging it is helpful for the file to be in a sorted order, - // any by returning the keys in the natural Alpha order for strings we get close enough. - // TreeSet is sorted, and this just overrides the normal Properties method to get the keys. - @Override - public synchronized Enumeration<Object> keys() { - return Collections.enumeration(new TreeSet<Object>(super.keySet())); - } - }; - List<String> roots = new ArrayList<>(); - List<String> refs = new ArrayList<>(); - - for (PDPPolicy policy : this.policies) { - // for all policies need to tell PDP the "name", which is the base name for the file id - if (policy.getName() != null) { - properties.setProperty(policy.getId() + ".name", policy.getName()); - } - // put the policy on the correct list - if (policy.isRoot()) { - roots.add(policy.getId()); - } else { - refs.add(policy.getId()); - } - } - - properties.setProperty(XACMLProperties.PROP_ROOTPOLICIES, Joiner.on(',').join(roots)); - properties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, Joiner.on(',').join(refs)); - - return properties; - } - - public PDPPolicy publishPolicy(String id, String name, boolean isRoot, InputStream policy) throws PAPException { - // - // Does it exist already? - // - if (this.getPolicy(id) != null) { - throw new PAPException("Policy with id " + id + " already exists - unpublish it first."); - } - Path tempFile = null; - try { - // - // Copy the policy over - // - tempFile = Files.createFile(Paths.get(this.directory.toAbsolutePath().toString(), id)); - long num; - try (OutputStream os = Files.newOutputStream(tempFile)) { - num = ByteStreams.copy(policy, os); - } - logger.info("Copied " + num + " bytes for policy " + name); - - StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, isRoot, name, tempFile.toUri()); - if (!tempRootPolicy.isValid()) { - try { - Files.delete(tempFile); - } catch(Exception ee) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", "Policy was invalid, could NOT delete it."); - } - throw new PAPException("Policy is invalid"); - } - // - // Add it in - // - this.policies.add(tempRootPolicy); - // - // We are changed - // - this.firePDPGroupChanged(this); - // - // Return our new object. - // - return tempRootPolicy; - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdPDPGroup", "Failed to publishPolicy"); - } - return null; - } - - /** - * Copy one policy file into the Group's directory but do not change the configuration. - * This is one part of a multi-step process of publishing policies. - * There may be multiple changes in the group (adding multiple policies, deleting policies, changine root<->referenced) - * that must be done all at once, so we just copy the file in preparation for a later "update whole group" operation. - * - * @param id - * @param name - * @param isRoot - * @param policy - * @return - * @throws PAPException - */ - public void copyPolicyToFile(String id, InputStream policy) throws PAPException { - try { - // - // Copy the policy over - // - long num; - Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id); - - Path policyFile; - if (Files.exists(policyFilePath)) { - policyFile = policyFilePath; - } else { - policyFile = Files.createFile(policyFilePath); - } - - try (OutputStream os = Files.newOutputStream(policyFile)) { - num = ByteStreams.copy(policy, os); - } - - logger.info("Copied " + num + " bytes for policy " + name); - - for (PDPPolicy p : policies) { - if (p.getId().equals(id)) { - // we just re-copied/refreshed/updated the policy file for a policy that already exists in this group - logger.info("Policy '" + id + "' already exists in group '" + getId() + "'"); - return; - } - } - - // policy is new to this group - StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri()); - if (!tempRootPolicy.isValid()) { - try { - Files.delete(policyFile); - } catch(Exception ee) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", "Policy was invalid, could NOT delete it."); - } - throw new PAPException("Policy is invalid"); - } - // - // Add it in - // - this.policies.add(tempRootPolicy); - // - // We are changed - // - this.firePDPGroupChanged(this); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to copyPolicyToFile"); - throw new PAPException("Failed to copy policy to file: " + e); - } - return; - } - - /** - * Policy Engine API Copy one policy file into the Group's directory but do not change the configuration. - * - * @param id - * @param name - * @param policy - * @return - * @throws PAPException - */ - public void copyPolicyToFile(String id, String name, InputStream policy) throws PAPException { - try { - // - // Copy the policy over - // - long num; - Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id); - - Path policyFile; - if (Files.exists(policyFilePath)) { - policyFile = policyFilePath; - } else { - policyFile = Files.createFile(policyFilePath); - } - - try (OutputStream os = Files.newOutputStream(policyFile)) { - num = ByteStreams.copy(policy, os); - } - - logger.info("Copied " + num + " bytes for policy " + name); - for (PDPPolicy p : policies) { - if (p.getId().equals(id)) { - // we just re-copied/refreshed/updated the policy file for a policy that already exists in this group - logger.info("Policy '" + id + "' already exists in group '" + getId() + "'"); - return; - } - } - - // policy is new to this group - StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri()); - if (!tempRootPolicy.isValid()) { - try { - Files.delete(policyFile); - } catch(Exception ee) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", "Policy was invalid, could NOT delete it."); - } - throw new PAPException("Policy is invalid"); - } - // - // Add it in - // - this.policies.add(tempRootPolicy); - // - // We are changed - // - this.firePDPGroupChanged(this); - - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to copyPolicyToFile"); - throw new PAPException("Failed to copy policy to file: " + e); - } - return; - } - - public boolean removePolicyFromGroup(PDPPolicy policy) { - PolicyLogger.info("policy: " + policy.getId()); - PolicyLogger.info("Policy ID:" + policy.getPolicyId()); - PolicyLogger.info("Policy Version: " + policy.getVersion()); - PolicyLogger.info("StdPDPPolicy Class cast: " + this.getPolicy(policy.getId()).toString()); - StdPDPPolicy currentPolicy = (StdPDPPolicy) this.getPolicy(policy.getId()); - if (currentPolicy == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Policy " + policy.getId() + " does not exist."); - return false; - } - try { - // - // Remove it from our list - // - this.policies.remove(currentPolicy); - // - // We are changed - // - this.firePDPGroupChanged(this); - return true; - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy"); - } - return false; - } - - public boolean removePolicy(PDPPolicy policy) { - PDPPolicy currentPolicy = this.getPolicy(policy.getId()); - if (currentPolicy == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Policy " + policy.getId() + " does not exist."); - return false; - } - try { - // - // Delete it on disk - // - Files.delete(Paths.get(currentPolicy.getLocation())); - // - // Remove it from our list - // - this.policies.remove(currentPolicy); - // - // We are changed - // - this.firePDPGroupChanged(this); - return true; - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy " + policy); - } - return false; - } - - @Override - public Set<PDPPIPConfig> getPipConfigs() { - return Collections.unmodifiableSet(this.pipConfigs); - } - - @Override - public PDPPIPConfig getPipConfig(String id) { - for (PDPPIPConfig config : this.pipConfigs) { - if (config.getId().equals(id)) { - return config; - } - } - return null; - } - - public void setPipConfigs(Set<PDPPIPConfig> pipConfigs) { - this.pipConfigs = pipConfigs; - this.firePDPGroupChanged(this); - } - - public void removeAllPIPConfigs() { - this.pipConfigs.clear(); - this.firePDPGroupChanged(this); - } - - @Override - public Properties getPipConfigProperties() { - Properties properties = new Properties(); - List<String> configs = new ArrayList<>(); - - for (PDPPIPConfig config : this.pipConfigs) { - configs.add(config.getId()); - properties.putAll(config.getConfiguration()); - } - - properties.setProperty(XACMLProperties.PROP_PIP_ENGINES, Joiner.on(',').join(configs)); - - return properties; - } - - @Override - public void repair() { - // - // Reset the status object - // - this.status.reset(); - // - // Validate our directory - // - boolean fire = false; - if (Files.notExists(directory)) { - logger.warn("Group directory does NOT exist: " + directory.toString()); - try { - Files.createDirectory(directory); - fire = true; - this.status.addLoadWarning("Created missing group directory"); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create missing Group directory."); - this.status.addLoadError("Failed to create missing Group directory."); - this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); - } - } - // - // Validate our PIP config file - // - Path pipPropertiesFile = Paths.get(directory.toString(), "xacml.pip.properties"); - if (Files.notExists(pipPropertiesFile)) { - try { - Files.createFile(pipPropertiesFile); - fire = true; - this.status.addLoadWarning("Created missing PIP properties file"); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create missing PIP properties file"); - this.status.addLoadError("Failed to create missing PIP properties file"); - this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); - } - } - // - // Valid our policy properties file - // - Path policyPropertiesFile = Paths.get(directory.toString(), "xacml.policy.properties"); - if (Files.notExists(policyPropertiesFile)) { - try { - Files.createFile(policyPropertiesFile); - fire = true; - this.status.addLoadWarning("Created missing Policy properties file"); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create missing Policy properties file"); - this.status.addLoadError("Failed to create missing Policy properties file"); - this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); - } - } - this.resetStatus(); - if (fire) { - this.fireChanged(); - } - } - - private void readPolicyProperties(Path directory, Properties properties) { - // - // There are 2 property values that hold policies, root and referenced - // - String[] lists = new String[2]; - lists[0] = properties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - lists[1] = properties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); - // - // Iterate each policy list - // - boolean isRoot = true; - for (String list : lists) { - // - // Was there actually a property? - // - if (list == null || list.length() == 0) { - isRoot = false; - continue; - } - // - // Parse it out - // - Iterable<String> policyList = Splitter.on(',').trimResults().omitEmptyStrings().split(list); - // - // Was there actually a list - // - if (policyList == null) { - isRoot = false; - continue; - } - for (String policyId : policyList) { - // - // Construct the policy filename - // - Path policyPath = Paths.get(directory.toString(), policyId ); - // - // Create the Policy Object - // - StdPDPPolicy policy; - try { - policy = new StdPDPPolicy(id, isRoot, policyPath.toUri(), properties); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create policy object"); - policy = null; - } - // - // Is it valid? - // - if (policy != null && policy.isValid()) { - this.policies.add(policy); - this.status.addLoadedPolicy(policy); - } else { - this.status.addFailedPolicy(policy); - this.status.setStatus(Status.LOAD_ERRORS); - } - // force all policies to have a name - if (policy!=null && policy.getName() == null) { - policy.setName(policy.getId()); - } - } - isRoot = false; - } - } - - private void readPIPProperties(Properties properties) { - String list = properties.getProperty(XACMLProperties.PROP_PIP_ENGINES); - if (list == null || list.length() == 0) { - return; - } - for (String pipId : list.split("[,]")) { - StdPDPPIPConfig config = new StdPDPPIPConfig(pipId, properties); - if (config.isConfigured()) { - this.pipConfigs.add(config); - this.status.addLoadedPipConfig(config); - } else { - this.status.addFailedPipConfig(config); - this.status.setStatus(Status.LOAD_ERRORS); - } - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDPGroup other = (StdPDPGroup) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDPGroup [id=" + id + ", isDefault=" + isDefault + ", name=" - + name + ", description=" + description + ", status=" + status - + ", pdps=" + pdps + ", policies=" + policies + ", pipConfigs=" - + pipConfigs + ", directory=" + directory + ",selectedPolicies=" - + selectedPolicies + ",operation=" + operation + "]"; - } - - @Override - public void changed() { - - // save the (changed) properties - try { - saveGroupConfiguration(); - } catch (PAPException | IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdPDPGroup", "Unable to save group configuration change"); - // don't notify other things of change if we cannot save it??? - return; - } - - this.firePDPGroupChanged(this); - - } - - @Override - public void groupChanged(OnapPDPGroup group) { - this.changed(); - } - - @Override - public void pdpChanged(OnapPDP pdp) { - // - // If one of the group's PDP's changed, then the group changed - // - this.changed(); - } - - public boolean isDefault() { - return isDefault; - } public void setDefault(boolean isDefault) { this.isDefault = isDefault; } - public void setStatus(PDPGroupStatus status) { - this.status = new StdPDPGroupStatus(status); - } - public void setPolicies(Set<PDPPolicy> policies) { - this.policies = policies; - } - public void setSelectedPolicies(Set<PDPPolicy> selectedPolicies) { - this.selectedPolicies = selectedPolicies; - } - public void setOperation(String operation) { - this.operation = operation; - } - - public void saveGroupConfiguration() throws PAPException, IOException { - - // First save the Policy properties - - // save the lists of policies - Properties policyProperties = this.getPolicyProperties(); - - // save info about each policy - for (PDPPolicy policy : this.policies){ - policyProperties.put(policy.getId() + ".name", policy.getName()); - } - - // - // Now we can save the file - // - Path file = Paths.get(this.directory.toString(), "xacml.policy.properties"); - try (OutputStream os = Files.newOutputStream(file)) { - policyProperties.store(os, ""); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "STdPDPGroup", "Group Policies Config save failed"); - throw new PAPException("Failed to save policy properties file '" + file +"'"); - } - - - // Now save the PIP Config properties - Properties pipProperties = this.getPipConfigProperties(); - - // - // Now we can save the file - // - file = Paths.get(this.directory.toString(), "xacml.pip.properties"); - try (OutputStream os = Files.newOutputStream(file)) { - pipProperties.store(os, ""); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Group PIP Config save failed"); - throw new PAPException("Failed to save pip properties file '" + file +"'"); - } - } - - // - // Comparable Interface - // - @Override - public int compareTo(Object arg0) { - if (arg0 == null) { - return -1; - } - if ( ! (arg0 instanceof StdPDPGroup)) { - return -1; - } - if (((StdPDPGroup)arg0).name == null) { - return -1; - } - if (name == null) { - return 1; - } - - return name.compareTo(((StdPDPGroup)arg0).name); - } - - //Adding Default PIP engine(s) while Loading initially. We don't want - // Programmer intervention with the PIP engines. - private Properties setPIPProperties(Properties props){ - props.setProperty("AAF.name", "AAFEngine"); - props.setProperty("AAF.description", "AAFEngine to communicate with AAF to take decisions"); - props.setProperty("AAF.classname","org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine"); - props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "AAF"); - // read from PIP properties file. - Path file = Paths.get(StdEngine.pipPropertyFile); - if (!Files.notExists(file)) { - InputStream in; - Properties prop = new Properties(); - try { - in = new FileInputStream(file.toFile()); - prop.load(in); - } catch (IOException e) { - PolicyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "can not load the pip properties from file" +e); - } - props = prop; - } - return props; - } + public void setStatus(PDPGroupStatus status) { + this.status = new StdPDPGroupStatus(status); + } + + public void setPolicies(Set<PDPPolicy> policies) { + this.policies = policies; + } + + public void setSelectedPolicies(Set<PDPPolicy> selectedPolicies) { + this.selectedPolicies = selectedPolicies; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + /** + * saveGroupConfiguration. + * + * @throws PAPException PAPException + * @throws IOException IOException + */ + public void saveGroupConfiguration() throws PAPException, IOException { + + // First save the Policy properties + + // save the lists of policies + Properties policyProperties = this.getPolicyProperties(); + + // save info about each policy + for (PDPPolicy policy : this.policies) { + policyProperties.put(policy.getId() + ".name", policy.getName()); + } + + // + // Now we can save the file + // + Path file = Paths.get(this.directory.toString(), "xacml.policy.properties"); + try (OutputStream os = Files.newOutputStream(file)) { + policyProperties.store(os, ""); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "STdPDPGroup", "Group Policies Config save failed"); + throw new PAPException("Failed to save policy properties file '" + file + "'"); + } + + // Now save the PIP Config properties + Properties pipProperties = this.getPipConfigProperties(); + + // + // Now we can save the file + // + file = Paths.get(this.directory.toString(), "xacml.pip.properties"); + try (OutputStream os = Files.newOutputStream(file)) { + pipProperties.store(os, ""); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Group PIP Config save failed"); + throw new PAPException("Failed to save pip properties file '" + file + "'"); + } + } + + // + // Comparable Interface + // + @Override + public int compareTo(Object arg0) { + if (arg0 == null) { + return -1; + } + if (!(arg0 instanceof StdPDPGroup)) { + return -1; + } + if (((StdPDPGroup) arg0).name == null) { + return -1; + } + if (name == null) { + return 1; + } + + return name.compareTo(((StdPDPGroup) arg0).name); + } + + // Adding Default PIP engine(s) while Loading initially. We don't want + // Programmer intervention with the PIP engines. + private Properties setPipProperties(Properties props) { + props.setProperty("AAF.name", "AAFEngine"); + props.setProperty("AAF.description", "AAFEngine to communicate with AAF to take decisions"); + props.setProperty("AAF.classname", "org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine"); + props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "AAF"); + // read from PIP properties file. + Path file = Paths.get(StdEngine.pipPropertyFile); + if (!Files.notExists(file)) { + InputStream in; + Properties prop = new Properties(); + try { + in = new FileInputStream(file.toFile()); + prop.load(in); + } catch (IOException e) { + PolicyLogger.error( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "can not load the pip properties from file" + e); + } + props = prop; + } + return props; + } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroupStatus.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroupStatus.java index dd9bf0a2c..3b93b8d66 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroupStatus.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroupStatus.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,11 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.policy.xacml.std.pap; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; +package org.onap.policy.xacml.std.pap; import com.att.research.xacml.api.pap.PDP; import com.att.research.xacml.api.pap.PDPGroupStatus; @@ -29,391 +26,318 @@ import com.att.research.xacml.api.pap.PDPPIPConfig; import com.att.research.xacml.api.pap.PDPPolicy; import com.fasterxml.jackson.annotation.JsonIgnore; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import lombok.EqualsAndHashCode; +import lombok.ToString; + +@EqualsAndHashCode(callSuper=false) +@ToString public class StdPDPGroupStatus implements PDPGroupStatus { - - private Status status = Status.UNKNOWN; - - private Set<String> loadErrors = new HashSet<>(); - - private Set<String> loadWarnings = new HashSet<>(); - - private Set<PDPPolicy> loadedPolicies = new HashSet<>(); - - private Set<PDPPolicy> failedPolicies = new HashSet<>(); - - private Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>(); - - private Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>(); - - private Set<PDP> inSynchPDPs = new HashSet<>(); - - private Set<PDP> outOfSynchPDPs = new HashSet<>(); - - private Set<PDP> failedPDPs = new HashSet<>(); - - private Set<PDP> updatingPDPs = new HashSet<>(); - - private Set<PDP> lastUpdateFailedPDPs = new HashSet<>(); - - private Set<PDP> unknownPDPs = new HashSet<>(); - - - - public StdPDPGroupStatus() { - // - // Constructor needed for JSON deserialization - // - } - - public StdPDPGroupStatus(Status status) { - this.status = status; - } - - public StdPDPGroupStatus(PDPGroupStatus stat) { - this.status = stat.getStatus(); - this.failedPDPs.clear(); - this.failedPDPs.addAll(stat.getFailedPDPs()); - this.failedPIPConfigs.clear(); - this.failedPIPConfigs.addAll(stat.getFailedPipConfigs()); - this.failedPolicies.clear(); - this.failedPolicies.addAll(stat.getFailedPolicies()); - this.inSynchPDPs.clear(); - this.inSynchPDPs.addAll(stat.getInSynchPDPs()); - this.lastUpdateFailedPDPs.clear(); - this.lastUpdateFailedPDPs.addAll(stat.getLastUpdateFailedPDPs()); - this.loadedPIPConfigs.clear(); - this.loadedPIPConfigs.addAll(stat.getLoadedPipConfigs()); - this.loadedPolicies.clear(); - this.loadedPolicies.addAll(stat.getLoadedPolicies()); - this.loadErrors.clear(); - this.loadErrors.addAll(stat.getLoadErrors()); - this.loadWarnings.clear(); - this.loadWarnings.addAll(stat.getLoadWarnings()); - this.outOfSynchPDPs.clear(); - this.outOfSynchPDPs.addAll(stat.getOutOfSynchPDPs()); - this.unknownPDPs.clear(); - this.unknownPDPs.addAll(stat.getUpdatingPDPs()); - this.updatingPDPs.clear(); - this.updatingPDPs.addAll(stat.getUpdatingPDPs()); - } - - public Set<PDPPIPConfig> getLoadedPIPConfigs() { - return loadedPIPConfigs; - } - public void setLoadedPIPConfigs(Set<PDPPIPConfig> loadedPIPConfigs) { - this.loadedPIPConfigs = loadedPIPConfigs; - } - public Set<PDPPIPConfig> getFailedPIPConfigs() { - return failedPIPConfigs; - } - public void setFailedPIPConfigs(Set<PDPPIPConfig> failedPIPConfigs) { - this.failedPIPConfigs = failedPIPConfigs; - } - public Set<PDP> getUnknownPDPs() { - return unknownPDPs; - } - public void setUnknownPDPs(Set<PDP> unknownPDPs) { - this.unknownPDPs = unknownPDPs; - } - public void setLoadErrors(Set<String> loadErrors) { - this.loadErrors = loadErrors; - } - public void setLoadWarnings(Set<String> loadWarnings) { - this.loadWarnings = loadWarnings; - } - public void setLoadedPolicies(Set<PDPPolicy> loadedPolicies) { - this.loadedPolicies = loadedPolicies; - } - public void setFailedPolicies(Set<PDPPolicy> failedPolicies) { - this.failedPolicies = failedPolicies; - } - public void setInSynchPDPs(Set<PDP> inSynchPDPs) { - this.inSynchPDPs = inSynchPDPs; - } - public void setOutOfSynchPDPs(Set<PDP> outOfSynchPDPs) { - this.outOfSynchPDPs = outOfSynchPDPs; - } - public void setFailedPDPs(Set<PDP> failedPDPs) { - this.failedPDPs = failedPDPs; - } - public void setUpdatingPDPs(Set<PDP> updatingPDPs) { - this.updatingPDPs = updatingPDPs; - } - public void setLastUpdateFailedPDPs(Set<PDP> lastUpdateFailedPDPs) { - this.lastUpdateFailedPDPs = lastUpdateFailedPDPs; - } - - - @Override - public Status getStatus() { - return status; - } - - public void setStatus(Status status) { - this.status = status; - } - - @Override - public Set<String> getLoadErrors() { - return Collections.unmodifiableSet(this.loadErrors); - } - - public void addLoadError(String error) { - this.loadErrors.add(error); - } - - @Override - public Set<String> getLoadWarnings() { - return Collections.unmodifiableSet(this.loadWarnings); - } - - public void addLoadWarning(String warning) { - this.loadWarnings.add(warning); - } - - @Override - public Set<PDPPolicy> getLoadedPolicies() { - return Collections.unmodifiableSet(this.loadedPolicies); - } - - public void addLoadedPolicy(PDPPolicy policy) { - this.loadedPolicies.add(policy); - } - - @Override - public Set<PDPPolicy> getFailedPolicies() { - return Collections.unmodifiableSet(this.failedPolicies); - } - - public void addFailedPolicy(PDPPolicy policy) { - this.failedPolicies.add(policy); - } - - @Override - public boolean policiesOK() { - if (!this.failedPolicies.isEmpty()) { - return false; - } - return true; - } - - @Override - public Set<PDPPIPConfig> getLoadedPipConfigs() { - return Collections.unmodifiableSet(this.loadedPIPConfigs); - } - - public void addLoadedPipConfig(PDPPIPConfig config) { - this.loadedPIPConfigs.add(config); - } - - @Override - public Set<PDPPIPConfig> getFailedPipConfigs() { - return Collections.unmodifiableSet(this.failedPIPConfigs); - } - - public void addFailedPipConfig(PDPPIPConfig config) { - this.failedPIPConfigs.add(config); - } - - @Override - public boolean pipConfigOK() { - if (!this.failedPIPConfigs.isEmpty()) { - return false; - } - return true; - } - - @Override - public Set<PDP> getInSynchPDPs() { - return Collections.unmodifiableSet(this.inSynchPDPs); - } - - public void addInSynchPDP(PDP pdp) { - this.inSynchPDPs.add(pdp); - } - - @Override - public Set<PDP> getOutOfSynchPDPs() { - return Collections.unmodifiableSet(this.outOfSynchPDPs); - } - - public void addOutOfSynchPDP(PDP pdp) { - this.outOfSynchPDPs.add(pdp); - } - - @Override - public Set<PDP> getFailedPDPs() { - return Collections.unmodifiableSet(this.failedPDPs); - } - - public void addFailedPDP(PDP pdp) { - this.failedPDPs.add(pdp); - } - - @Override - public Set<PDP> getUpdatingPDPs() { - return Collections.unmodifiableSet(this.updatingPDPs); - } - - public void addUpdatingPDP(PDP pdp) { - this.updatingPDPs.add(pdp); - } - - @Override - public Set<PDP> getLastUpdateFailedPDPs() { - return Collections.unmodifiableSet(this.lastUpdateFailedPDPs); - } - - public void addLastUpdateFailedPDP(PDP pdp) { - this.lastUpdateFailedPDPs.add(pdp); - } - - @Override - @JsonIgnore - public Set<PDP> getUnknownStatusPDPs() { - return Collections.unmodifiableSet(this.unknownPDPs); - } - - public void addUnknownPDP(PDP pdp) { - this.unknownPDPs.add(pdp); - } - - @Override - public boolean pdpsOK() { - if (!this.outOfSynchPDPs.isEmpty()) { - return false; - } - if (!this.failedPDPs.isEmpty()) { - return false; - } - if (!this.lastUpdateFailedPDPs.isEmpty()) { - return false; - } - if (!this.unknownPDPs.isEmpty()) { - return false; - } - return true; - } - - @Override - @JsonIgnore - public boolean isGroupOk() { - if (!this.policiesOK()) { - return false; - } - if (!this.pipConfigOK()) { - return false; - } - if (!this.pdpsOK()) { - return false; - } - if (!this.loadErrors.isEmpty()) { - return false; - } - return this.status == Status.OK; - } - - public void reset() { - this.status = Status.OK; - - this.loadErrors.clear(); - this.loadWarnings.clear(); - this.loadedPolicies.clear(); - this.failedPolicies.clear(); - this.loadedPIPConfigs.clear(); - this.failedPIPConfigs.clear(); - this.inSynchPDPs.clear(); - this.outOfSynchPDPs.clear(); - this.failedPDPs.clear(); - this.updatingPDPs.clear(); - this.lastUpdateFailedPDPs.clear(); - this.unknownPDPs.clear(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + (failedPDPs.hashCode()); - result = prime - * result - + (failedPIPConfigs.hashCode()); - result = prime * result - + (failedPolicies.hashCode()); - result = prime * result - + (inSynchPDPs.hashCode()); - result = prime - * result - + (lastUpdateFailedPDPs.hashCode()); - result = prime * result - + (loadErrors.hashCode()); - result = prime * result - + (loadWarnings.hashCode()); - result = prime - * result - + (loadedPIPConfigs.hashCode()); - result = prime * result - + (loadedPolicies.hashCode()); - result = prime * result - + (outOfSynchPDPs.hashCode()); - result = prime * result + (status.hashCode()); - result = prime * result - + (unknownPDPs.hashCode()); - result = prime * result - + (updatingPDPs.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDPGroupStatus other = (StdPDPGroupStatus) obj; - if (!failedPDPs.equals(other.failedPDPs)) - return false; - if (!failedPIPConfigs.equals(other.failedPIPConfigs)) - return false; - if (!failedPolicies.equals(other.failedPolicies)) - return false; - if (!inSynchPDPs.equals(other.inSynchPDPs)) - return false; - if (!lastUpdateFailedPDPs.equals(other.lastUpdateFailedPDPs)) - return false; - if (!loadErrors.equals(other.loadErrors)) - return false; - if (!loadWarnings.equals(other.loadWarnings)) - return false; - if (!loadedPIPConfigs.equals(other.loadedPIPConfigs)) - return false; - if (!loadedPolicies.equals(other.loadedPolicies)) - return false; - if (!outOfSynchPDPs.equals(other.outOfSynchPDPs)) - return false; - if (status != other.status) - return false; - if (!unknownPDPs.equals(other.unknownPDPs)) - return false; - if (!updatingPDPs.equals(other.updatingPDPs)) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDPGroupStatus [status=" + status + ", loadErrors=" - + loadErrors + ", loadWarnings=" + loadWarnings - + ", loadedPolicies=" + loadedPolicies + ", failedPolicies=" - + failedPolicies + ", loadedPIPConfigs=" + loadedPIPConfigs - + ", failedPIPConfigs=" + failedPIPConfigs + ", inSynchPDPs=" - + inSynchPDPs + ", outOfSynchPDPs=" + outOfSynchPDPs - + ", failedPDPs=" + failedPDPs + ", updatingPDPs=" - + updatingPDPs + ", lastUpdateFailedPDPs=" - + lastUpdateFailedPDPs + ", unknownPDPs=" + unknownPDPs + "]"; - } + + private Status status = Status.UNKNOWN; + + private Set<String> loadErrors = new HashSet<>(); + + private Set<String> loadWarnings = new HashSet<>(); + + private Set<PDPPolicy> loadedPolicies = new HashSet<>(); + + private Set<PDPPolicy> failedPolicies = new HashSet<>(); + + private Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>(); + + private Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>(); + + private Set<PDP> inSynchPDPs = new HashSet<>(); + + private Set<PDP> outOfSynchPDPs = new HashSet<>(); + + private Set<PDP> failedPDPs = new HashSet<>(); + + private Set<PDP> updatingPDPs = new HashSet<>(); + + private Set<PDP> lastUpdateFailedPDPs = new HashSet<>(); + + private Set<PDP> unknownPDPs = new HashSet<>(); + + public StdPDPGroupStatus() { + // + // Constructor needed for JSON deserialization + // + } + + public StdPDPGroupStatus(Status status) { + this.status = status; + } + + public StdPDPGroupStatus(PDPGroupStatus stat) { + this.status = stat.getStatus(); + this.failedPDPs.clear(); + this.failedPDPs.addAll(stat.getFailedPDPs()); + this.failedPIPConfigs.clear(); + this.failedPIPConfigs.addAll(stat.getFailedPipConfigs()); + this.failedPolicies.clear(); + this.failedPolicies.addAll(stat.getFailedPolicies()); + this.inSynchPDPs.clear(); + this.inSynchPDPs.addAll(stat.getInSynchPDPs()); + this.lastUpdateFailedPDPs.clear(); + this.lastUpdateFailedPDPs.addAll(stat.getLastUpdateFailedPDPs()); + this.loadedPIPConfigs.clear(); + this.loadedPIPConfigs.addAll(stat.getLoadedPipConfigs()); + this.loadedPolicies.clear(); + this.loadedPolicies.addAll(stat.getLoadedPolicies()); + this.loadErrors.clear(); + this.loadErrors.addAll(stat.getLoadErrors()); + this.loadWarnings.clear(); + this.loadWarnings.addAll(stat.getLoadWarnings()); + this.outOfSynchPDPs.clear(); + this.outOfSynchPDPs.addAll(stat.getOutOfSynchPDPs()); + this.unknownPDPs.clear(); + this.unknownPDPs.addAll(stat.getUpdatingPDPs()); + this.updatingPDPs.clear(); + this.updatingPDPs.addAll(stat.getUpdatingPDPs()); + } + + public Set<PDPPIPConfig> getLoadedPIPConfigs() { + return loadedPIPConfigs; + } + + public void setLoadedPIPConfigs(Set<PDPPIPConfig> loadedPIPConfigs) { + this.loadedPIPConfigs = loadedPIPConfigs; + } + + public Set<PDPPIPConfig> getFailedPIPConfigs() { + return failedPIPConfigs; + } + + public void setFailedPIPConfigs(Set<PDPPIPConfig> failedPIPConfigs) { + this.failedPIPConfigs = failedPIPConfigs; + } + + public Set<PDP> getUnknownPDPs() { + return unknownPDPs; + } + + public void setUnknownPDPs(Set<PDP> unknownPDPs) { + this.unknownPDPs = unknownPDPs; + } + + public void setLoadErrors(Set<String> loadErrors) { + this.loadErrors = loadErrors; + } + + public void setLoadWarnings(Set<String> loadWarnings) { + this.loadWarnings = loadWarnings; + } + + public void setLoadedPolicies(Set<PDPPolicy> loadedPolicies) { + this.loadedPolicies = loadedPolicies; + } + + public void setFailedPolicies(Set<PDPPolicy> failedPolicies) { + this.failedPolicies = failedPolicies; + } + + public void setInSynchPDPs(Set<PDP> inSynchPDPs) { + this.inSynchPDPs = inSynchPDPs; + } + + public void setOutOfSynchPDPs(Set<PDP> outOfSynchPDPs) { + this.outOfSynchPDPs = outOfSynchPDPs; + } + + public void setFailedPDPs(Set<PDP> failedPDPs) { + this.failedPDPs = failedPDPs; + } + + public void setUpdatingPDPs(Set<PDP> updatingPDPs) { + this.updatingPDPs = updatingPDPs; + } + + public void setLastUpdateFailedPDPs(Set<PDP> lastUpdateFailedPDPs) { + this.lastUpdateFailedPDPs = lastUpdateFailedPDPs; + } + + @Override + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } + + @Override + public Set<String> getLoadErrors() { + return Collections.unmodifiableSet(this.loadErrors); + } + + public void addLoadError(String error) { + this.loadErrors.add(error); + } + + @Override + public Set<String> getLoadWarnings() { + return Collections.unmodifiableSet(this.loadWarnings); + } + + public void addLoadWarning(String warning) { + this.loadWarnings.add(warning); + } + + @Override + public Set<PDPPolicy> getLoadedPolicies() { + return Collections.unmodifiableSet(this.loadedPolicies); + } + + public void addLoadedPolicy(PDPPolicy policy) { + this.loadedPolicies.add(policy); + } + + @Override + public Set<PDPPolicy> getFailedPolicies() { + return Collections.unmodifiableSet(this.failedPolicies); + } + + public void addFailedPolicy(PDPPolicy policy) { + this.failedPolicies.add(policy); + } + + @Override + public boolean policiesOK() { + return this.failedPolicies.isEmpty(); + } + + @Override + public Set<PDPPIPConfig> getLoadedPipConfigs() { + return Collections.unmodifiableSet(this.loadedPIPConfigs); + } + + public void addLoadedPipConfig(PDPPIPConfig config) { + this.loadedPIPConfigs.add(config); + } + + @Override + public Set<PDPPIPConfig> getFailedPipConfigs() { + return Collections.unmodifiableSet(this.failedPIPConfigs); + } + + public void addFailedPipConfig(PDPPIPConfig config) { + this.failedPIPConfigs.add(config); + } + + @Override + public boolean pipConfigOK() { + return this.failedPIPConfigs.isEmpty(); + } + + @Override + public Set<PDP> getInSynchPDPs() { + return Collections.unmodifiableSet(this.inSynchPDPs); + } + + public void addInSynchPDP(PDP pdp) { + this.inSynchPDPs.add(pdp); + } + + @Override + public Set<PDP> getOutOfSynchPDPs() { + return Collections.unmodifiableSet(this.outOfSynchPDPs); + } + + public void addOutOfSynchPDP(PDP pdp) { + this.outOfSynchPDPs.add(pdp); + } + + @Override + public Set<PDP> getFailedPDPs() { + return Collections.unmodifiableSet(this.failedPDPs); + } + + public void addFailedPDP(PDP pdp) { + this.failedPDPs.add(pdp); + } + + @Override + public Set<PDP> getUpdatingPDPs() { + return Collections.unmodifiableSet(this.updatingPDPs); + } + + public void addUpdatingPDP(PDP pdp) { + this.updatingPDPs.add(pdp); + } + + @Override + public Set<PDP> getLastUpdateFailedPDPs() { + return Collections.unmodifiableSet(this.lastUpdateFailedPDPs); + } + + public void addLastUpdateFailedPDP(PDP pdp) { + this.lastUpdateFailedPDPs.add(pdp); + } + + @Override + @JsonIgnore + public Set<PDP> getUnknownStatusPDPs() { + return Collections.unmodifiableSet(this.unknownPDPs); + } + + public void addUnknownPDP(PDP pdp) { + this.unknownPDPs.add(pdp); + } + + @Override + public boolean pdpsOK() { + if (!this.outOfSynchPDPs.isEmpty()) { + return false; + } + if (!this.failedPDPs.isEmpty()) { + return false; + } + if (!this.lastUpdateFailedPDPs.isEmpty()) { + return false; + } + return this.unknownPDPs.isEmpty(); + } + + @Override + @JsonIgnore + public boolean isGroupOk() { + if (!this.policiesOK()) { + return false; + } + if (!this.pipConfigOK()) { + return false; + } + if (!this.pdpsOK()) { + return false; + } + if (!this.loadErrors.isEmpty()) { + return false; + } + return this.status == Status.OK; + } + + /** + * reset. + */ + public void reset() { + this.status = Status.OK; + + this.loadErrors.clear(); + this.loadWarnings.clear(); + this.loadedPolicies.clear(); + this.failedPolicies.clear(); + this.loadedPIPConfigs.clear(); + this.failedPIPConfigs.clear(); + this.inSynchPDPs.clear(); + this.outOfSynchPDPs.clear(); + this.failedPDPs.clear(); + this.updatingPDPs.clear(); + this.lastUpdateFailedPDPs.clear(); + this.unknownPDPs.clear(); + } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java index cc80b62c2..bf986b38e 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.std.pap; import java.util.Collection; @@ -26,56 +27,79 @@ import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; public class StdPDPItemSetChangeNotifier { - - private Collection<StdItemSetChangeListener> listeners = null; - - public interface StdItemSetChangeListener { - - public void changed(); - - public void groupChanged(OnapPDPGroup group); - - public void pdpChanged(OnapPDP pdp); - } - - public void addItemSetChangeListener(StdItemSetChangeListener listener) { - if (this.listeners == null) { - this.listeners = new LinkedList<>(); - } - this.listeners.add(listener); - } - - public void removeItemSetChangeListener(StdItemSetChangeListener listener) { - if (this.listeners != null) { - this.listeners.remove(listener); - } - } + private Collection<StdItemSetChangeListener> listeners = null; + + public interface StdItemSetChangeListener { + + public void changed(); + + public void groupChanged(OnapPDPGroup group); + + public void pdpChanged(OnapPDP pdp); + + } + + /** + * addItemSetChangeListener. + * + * @param listener StdItemSetChangeListener + */ + public void addItemSetChangeListener(StdItemSetChangeListener listener) { + if (this.listeners == null) { + this.listeners = new LinkedList<>(); + } + this.listeners.add(listener); + } + + /** + * removeItemSetChangeListener. + * + * @param listener StdItemSetChangeListener + */ + public void removeItemSetChangeListener(StdItemSetChangeListener listener) { + if (this.listeners != null) { + this.listeners.remove(listener); + } + } - public void fireChanged() { - if (this.listeners == null) { - return; - } - for (StdItemSetChangeListener l : this.listeners) { - l.changed(); - } - } + /** + * fireChanged. + */ + public void fireChanged() { + if (this.listeners == null) { + return; + } + for (StdItemSetChangeListener l : this.listeners) { + l.changed(); + } + } - public void firePDPGroupChanged(OnapPDPGroup group) { - if (this.listeners == null) { - return; - } - for (StdItemSetChangeListener l : this.listeners) { - l.groupChanged(group); - } - } + /** + * firePDPGroupChanged. + * + * @param group OnapPDPGroup + */ + public void firePDPGroupChanged(OnapPDPGroup group) { + if (this.listeners == null) { + return; + } + for (StdItemSetChangeListener l : this.listeners) { + l.groupChanged(group); + } + } - public void firePDPChanged(OnapPDP pdp) { - if (this.listeners == null) { - return; - } - for (StdItemSetChangeListener l : this.listeners) { - l.pdpChanged(pdp); - } - } + /** + * firePDPChanged. + * + * @param pdp OnapPDP + */ + public void firePDPChanged(OnapPDP pdp) { + if (this.listeners == null) { + return; + } + for (StdItemSetChangeListener l : this.listeners) { + l.pdpChanged(pdp); + } + } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPIPConfig.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPIPConfig.java index 9a65d50b2..3b7699467 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPIPConfig.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPIPConfig.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,202 +17,161 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.std.pap; +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.fasterxml.jackson.annotation.JsonIgnore; + import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Properties; +import lombok.EqualsAndHashCode; +import lombok.ToString; -import com.att.research.xacml.api.pap.PDPPIPConfig; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; - +@EqualsAndHashCode(callSuper = false) +@ToString public class StdPDPPIPConfig implements PDPPIPConfig, Serializable { - private static final long serialVersionUID = 1L; - private static Logger logger = FlexLogger.getLogger(StdPDPPIPConfig.class); - - private String id; - - private String name; - - private String description; - - private String classname; - - private Map<String,String> config = new HashMap<>(); - - public StdPDPPIPConfig() { - // - // Default constructor - // - } - - public StdPDPPIPConfig(String id) { - this.id = id; - } - - public StdPDPPIPConfig(String id, String name, String description) { - this(id); - this.name = name; - this.description = description; - } - - public StdPDPPIPConfig(String id, Properties properties) { - this(id); - if ( ! this.initialize(properties) ) { - throw new IllegalArgumentException("PIP Engine '" + id + "' has no classname property in config"); - } - } - - public boolean initialize(Properties properties) { - boolean classnameSeen = false; - for (Object key : properties.keySet()) { - if (key.toString().startsWith(this.id + ".")) { - if (logger.isDebugEnabled()) { - logger.debug("Found: " + key); - } - if (key.toString().equals(this.id + ".name")) { - this.name = properties.getProperty(key.toString()); - } else if (key.toString().equals(this.id + ".description")) { - this.description = properties.getProperty(key.toString()); - } else if (key.toString().equals(this.id + ".classname")) { - this.classname = properties.getProperty(key.toString()); - classnameSeen = true; - } - // all properties, including the special ones located above, are included in the properties list - this.config.put(key.toString(), properties.getProperty(key.toString())); - } - } - return classnameSeen; - } - - @Override - public String getId() { - return this.id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String getClassname() { - return classname; - } - - public void setClassname(String classname) { - this.classname = classname; - } - - @Override - @JsonIgnore - public Map<String,String> getConfiguration() { - return Collections.unmodifiableMap(this.config); - } - - public void setValues(Map<String,String> config) { - this.config = config; - } - - @Override - @JsonIgnore - public boolean isConfigured() { - // - // Also include this in the JSON I/O if it is a data field rather than calculated - // - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((classname == null) ? 0 : classname.hashCode()); - result = prime * result + ((config == null) ? 0 : config.hashCode()); - result = prime * result - + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDPPIPConfig other = (StdPDPPIPConfig) obj; - if (classname == null) { - if (other.classname != null) - return false; - } else if (!classname.equals(other.classname)) - return false; - if (config == null) { - if (other.config != null) - return false; - } else if (!config.equals(other.config)) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDPPIPConfig [id=" + id + ", name=" + name - + ", description=" + description + ", classname=" + classname - + ", config=" + config + "]"; - } - - - - // - // Methods needed for JSON serialization/deserialization - // - - public Map<String, String> getConfig() { - return config; - } - public void setConfig(Map<String, String> config) { - this.config = config; - } - + private static final long serialVersionUID = 1L; + + private String id; + + private String name; + + private String description; + + private String classname; + + private Map<String, String> config = new HashMap<>(); + + public StdPDPPIPConfig() { + // + // Default constructor + // + } + + public StdPDPPIPConfig(String id) { + this.id = id; + } + + /** + * Constructor. + * + * @param id String + * @param name String + * @param description String + */ + public StdPDPPIPConfig(String id, String name, String description) { + this(id); + this.name = name; + this.description = description; + } + + /** + * Constructor. + * + * @param id String + * @param properties Properties + */ + public StdPDPPIPConfig(String id, Properties properties) { + this(id); + if (!this.initialize(properties)) { + throw new IllegalArgumentException("PIP Engine '" + id + "' has no classname property in config"); + } + } + + /** + * initialize. + * + * @param properties Properties + * @return boolean + */ + public boolean initialize(Properties properties) { + boolean classnameSeen = false; + for (Object key : properties.keySet()) { + if (key.toString().startsWith(this.id + ".")) { + if (key.toString().equals(this.id + ".name")) { + this.name = properties.getProperty(key.toString()); + } else if (key.toString().equals(this.id + ".description")) { + this.description = properties.getProperty(key.toString()); + } else if (key.toString().equals(this.id + ".classname")) { + this.classname = properties.getProperty(key.toString()); + classnameSeen = true; + } + // all properties, including the special ones located above, are included in the properties list + this.config.put(key.toString(), properties.getProperty(key.toString())); + } + } + return classnameSeen; + } + + @Override + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String getClassname() { + return classname; + } + + public void setClassname(String classname) { + this.classname = classname; + } + + @Override + @JsonIgnore + public Map<String, String> getConfiguration() { + return Collections.unmodifiableMap(this.config); + } + + public void setValues(Map<String, String> config) { + this.config = config; + } + + @Override + @JsonIgnore + public boolean isConfigured() { + // + // Also include this in the JSON I/O if it is a data field rather than calculated + // + return true; + } + + // + // Methods needed for JSON serialization/deserialization + // + + public Map<String, String> getConfig() { + return config; + } + + public void setConfig(Map<String, String> config) { + this.config = config; + } + } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicy.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicy.java index 2b198f5e7..5288435aa 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicy.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicy.java @@ -2,15 +2,15 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * 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. @@ -18,9 +18,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.std.pap; -import org.onap.policy.common.logging.eelf.PolicyLogger; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.google.common.base.Splitter; +import com.google.common.collect.Lists; import java.io.FileNotFoundException; import java.io.IOException; @@ -36,15 +41,9 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.xacml.util.XACMLPolicyScanner; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; - - public class StdPDPPolicy implements PDPPolicy, Serializable { private static final long serialVersionUID = 1L; private static Log logger = LogFactory.getLog(StdPDPPolicy.class); @@ -57,7 +56,7 @@ public class StdPDPPolicy implements PDPPolicy, Serializable { private String description = null; - private int[] version = null; + private int[] version = null; private boolean isRoot = false; @@ -81,7 +80,15 @@ public class StdPDPPolicy implements PDPPolicy, Serializable { this.name = name; } - + /** + * StdPDPPolicy. + * + * @param id String + * @param isRoot boolean + * @param name String + * @param location URI + * @throws IOException IOException + */ public StdPDPPolicy(String id, boolean isRoot, String name, URI location) throws IOException { this(id, isRoot); this.name = name; @@ -97,11 +104,17 @@ public class StdPDPPolicy implements PDPPolicy, Serializable { this.id = theID; } - logger.debug("The final outcome of the constructor returned the following: id = " + id + - ", location = " + location + ", name = " + name); + logger.debug("The final outcome of the constructor returned the following: id = " + id + ", location = " + + location + ", name = " + name); } + /** + * StdPDPPolicy constructor. + * + * @param stdPDPPolicyParams StdPDPPolicyParams + * @throws IOException IOException + */ public StdPDPPolicy(StdPDPPolicyParams stdPDPPolicyParams) throws IOException { this(stdPDPPolicyParams.getId(), stdPDPPolicyParams.isRoot()); this.name = stdPDPPolicyParams.getName(); @@ -111,23 +124,43 @@ public class StdPDPPolicy implements PDPPolicy, Serializable { this.version = versionStringToArray(stdPDPPolicyParams.getVersion()); this.isValid = stdPDPPolicyParams.isValid(); - logger.debug("The final outcome of the constructor returned the following: id = " + stdPDPPolicyParams.getId() + - ", location = " + stdPDPPolicyParams.getLocation() + ", name = " + stdPDPPolicyParams.getName() + ", policyId = " + stdPDPPolicyParams.getPolicyId() + - ", description = " + stdPDPPolicyParams.getDescription() + ", Version = " + stdPDPPolicyParams.getVersion()); + logger.debug("The final outcome of the constructor returned the following: id = " + stdPDPPolicyParams.getId() + + ", location = " + stdPDPPolicyParams.getLocation() + ", name = " + stdPDPPolicyParams.getName() + + ", policyId = " + stdPDPPolicyParams.getPolicyId() + ", description = " + + stdPDPPolicyParams.getDescription() + ", Version = " + stdPDPPolicyParams.getVersion()); } + /** + * StdPDPPolicy. + * + * @param id String + * @param isRoot boolean + * @param name String + * @param location URI + * @param isFromAPI boolean + * @throws IOException IOException + */ public StdPDPPolicy(String id, boolean isRoot, String name, URI location, boolean isFromAPI) throws IOException { this(id, isRoot); this.name = name; this.location = location; this.isValid = isFromAPI; - logger.debug("The final outcome of the constructor returned the following: id = " + id + - ", location = " + location + ", name = " + name); + logger.debug("The final outcome of the constructor returned the following: id = " + id + ", location = " + + location + ", name = " + name); } + /** + * StdPDPPolicy. + * + * @param id String + * @param isRoot boolean + * @param location URI + * @param properties boolean + * @throws IOException IOException + */ public StdPDPPolicy(String id, boolean isRoot, URI location, Properties properties) throws IOException { this(id, isRoot); this.location = location; @@ -146,31 +179,26 @@ public class StdPDPPolicy implements PDPPolicy, Serializable { } } - private String readPolicyData() throws IOException { // // Extract XACML policy information // URL url = this.location.toURL(); Object rootElement = XACMLPolicyScanner.readPolicy(url.openStream()); - if (rootElement == null || - ( - ! (rootElement instanceof PolicySetType) && - ! (rootElement instanceof PolicyType) - ) ) { + if (rootElement == null || (!(rootElement instanceof PolicySetType) && !(rootElement instanceof PolicyType))) { logger.warn("No root policy element in URI: " + this.location.toString() + " : " + rootElement); this.isValid = false; } else { this.version = versionStringToArray(XACMLPolicyScanner.getVersion(rootElement)); if (rootElement instanceof PolicySetType) { - this.policyId = ((PolicySetType)rootElement).getPolicySetId(); - this.description = ((PolicySetType)rootElement).getDescription(); + this.policyId = ((PolicySetType) rootElement).getPolicySetId(); + this.description = ((PolicySetType) rootElement).getDescription(); this.isValid = true; - this.version = versionStringToArray(((PolicySetType)rootElement).getVersion()); + this.version = versionStringToArray(((PolicySetType) rootElement).getVersion()); } else if (rootElement instanceof PolicyType) { - this.policyId = ((PolicyType)rootElement).getPolicyId(); - this.description = ((PolicyType)rootElement).getDescription(); - this.version = versionStringToArray(((PolicyType)rootElement).getVersion()); + this.policyId = ((PolicyType) rootElement).getPolicyId(); + this.description = ((PolicyType) rootElement).getDescription(); + this.version = versionStringToArray(((PolicyType) rootElement).getVersion()); this.isValid = true; } else { PolicyLogger.error("Unknown root element: " + rootElement.getClass().getCanonicalName()); @@ -230,8 +258,7 @@ public class StdPDPPolicy implements PDPPolicy, Serializable { } @Override - public boolean isValid() - { + public boolean isValid() { return this.isValid; } @@ -259,8 +286,7 @@ public class StdPDPPolicy implements PDPPolicy, Serializable { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result - + ((policyId == null) ? 0 : policyId.hashCode()); + result = prime * result + ((policyId == null) ? 0 : policyId.hashCode()); result = prime * result; if (version != null) { for (int i = 0; i < version.length; i++) { @@ -272,45 +298,50 @@ public class StdPDPPolicy implements PDPPolicy, Serializable { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } StdPDPPolicy other = (StdPDPPolicy) obj; if (id == null) { - if (other.id != null) + if (other.id != null) { return false; - } else if (!id.equals(other.id)) + } + } else if (!id.equals(other.id)) { return false; + } if (policyId == null) { - if (other.policyId != null) + if (other.policyId != null) { return false; - } else if (!policyId.equals(other.policyId)) + } + } else if (!policyId.equals(other.policyId)) { return false; - if (version != other.version) + } + if (version != other.version) { return false; + } return true; } @Override public String toString() { - return "StdPDPPolicy [id=" + id + ", name=" + name + ", policyId=" - + policyId + ", description=" + description + ", version=" - + this.getVersion() + ", isRoot=" + isRoot + ", isValid=" + isValid - + ", location=" + location + "]"; + return "StdPDPPolicy [id=" + id + ", name=" + name + ", policyId=" + policyId + ", description=" + description + + ", version=" + this.getVersion() + ", isRoot=" + isRoot + ", isValid=" + isValid + ", location=" + + location + "]"; } - /** * Given a version string consisting of integers with dots between them, convert it into an array of ints. * - * @param version - * @return - * @throws NumberFormatException + * @param version String + * @return int array */ - public static int[] versionStringToArray(String version) throws NumberFormatException { + public static int[] versionStringToArray(String version) { if (version == null || version.length() == 0) { return new int[0]; } @@ -325,8 +356,8 @@ public class StdPDPPolicy implements PDPPolicy, Serializable { /** * Given an array representing a version, create the corresponding dot-separated string. * - * @param array - * @return + * @param array int array + * @return String */ public static String versionArrayToString(int[] array) { if (array == null || array.length == 0) { @@ -345,18 +376,23 @@ public class StdPDPPolicy implements PDPPolicy, Serializable { public void setPolicyId(String policyId) { this.policyId = policyId; } + public void setDescription(String description) { this.description = description; } + public void setVersion(String version) { this.version = versionStringToArray(version); } + public void setRoot(boolean isRoot) { this.isRoot = isRoot; } + public void setValid(boolean isValid) { this.isValid = isValid; } + public void setLocation(URI location) { this.location = location; } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicyParams.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicyParams.java index dddfe2576..f5251214f 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicyParams.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicyParams.java @@ -3,6 +3,7 @@ * ONAP-XACML * ================================================================================ * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +24,7 @@ package org.onap.policy.xacml.std.pap; import java.net.URI; /** - * Parameters class for StdPDPPolicy + * Parameters class for StdPDPPolicy. */ public class StdPDPPolicyParams { private String id; @@ -36,14 +37,15 @@ public class StdPDPPolicyParams { private String version; /** - * Private constructor + * Private constructor. */ - private StdPDPPolicyParams(){ + private StdPDPPolicyParams() { super(); } /** - * Get an instance of builder class + * Get an instance of builder class. + * * @return StdPDPPolicyParamsBuilder */ public static StdPDPPolicyParamsBuilder builder() { @@ -51,15 +53,17 @@ public class StdPDPPolicyParams { } /** - * Return id - * @return id + * Return id. + * + * @return id String */ public String getId() { return id; } /** - * Boolean to indicate root + * Boolean to indicate root. + * * @return isRoot */ public boolean isRoot() { @@ -67,7 +71,8 @@ public class StdPDPPolicyParams { } /** - * Get name of policy + * Get name of policy. + * * @return name */ public String getName() { @@ -75,7 +80,8 @@ public class StdPDPPolicyParams { } /** - * Retrieve the uri + * Retrieve the uri. + * * @return location */ public URI getLocation() { @@ -83,7 +89,8 @@ public class StdPDPPolicyParams { } /** - * Check policy valid + * Check policy valid. + * * @return isValid */ public boolean isValid() { @@ -91,7 +98,8 @@ public class StdPDPPolicyParams { } /** - * Retrieve policy id + * Retrieve policy id. + * * @return policy id */ public String getPolicyId() { @@ -99,7 +107,8 @@ public class StdPDPPolicyParams { } /** - * Description of policy + * Description of policy. + * * @return description */ public String getDescription() { @@ -107,7 +116,8 @@ public class StdPDPPolicyParams { } /** - * Retrieve version of policy + * Retrieve version of policy. + * * @return version */ public String getVersion() { @@ -115,96 +125,105 @@ public class StdPDPPolicyParams { } /** - * Builder class for std pdp policy params class + * Builder class for std pdp policy params class. */ public static class StdPDPPolicyParamsBuilder { - StdPDPPolicyParams m = new StdPDPPolicyParams(); + StdPDPPolicyParams params = new StdPDPPolicyParams(); /** - * Build the policy params + * Build the policy params. + * * @return stdPdpPolicyParams object */ public StdPDPPolicyParams build() { - return m; + return params; } /** - * Set id + * Set id. + * * @param id - provide id * @return builder */ public StdPDPPolicyParamsBuilder id(String id) { - m.id = id; + params.id = id; return this; } /** - * Set whether isRoot + * Set whether isRoot. + * * @param isRoot - true/false * @return builder */ public StdPDPPolicyParamsBuilder isRoot(boolean isRoot) { - m.isRoot = isRoot; + params.isRoot = isRoot; return this; } /** - * Set name + * Set name. + * * @param name - name of policy * @return builder */ public StdPDPPolicyParamsBuilder name(String name) { - m.name = name; + params.name = name; return this; } /** - * Set location uri + * Set location uri. + * * @param uri - for location * @return builder */ public StdPDPPolicyParamsBuilder location(URI uri) { - m.location = uri; + params.location = uri; return this; } /** - * Set valid flag + * Set valid flag. + * * @param isValid - whether the policy is valid * @return builder */ public StdPDPPolicyParamsBuilder isValid(boolean isValid) { - m.isValid = isValid; + params.isValid = isValid; return this; } /** - * Set policy id + * Set policy id. + * * @param policyId - policy id * @return builder */ public StdPDPPolicyParamsBuilder policyId(String policyId) { - m.policyId = policyId; + params.policyId = policyId; return this; } /** - * Set description of policy + * Set description of policy. + * * @param description - of policy * @return builder */ public StdPDPPolicyParamsBuilder description(String description) { - m.description = description; + params.description = description; return this; } /** - * Set version of policy + * Set version of policy. + * * @param version - of policy * @return builder */ public StdPDPPolicyParamsBuilder version(String version) { - m.version = version; + params.version = version; return this; } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java index a39ea3630..4f61cd61b 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,254 +17,240 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.policy.xacml.std.pap; -import java.io.Serializable; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; +package org.onap.policy.xacml.std.pap; import com.att.research.xacml.api.pap.PDPPIPConfig; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.api.pap.PDPStatus; import com.fasterxml.jackson.annotation.JsonIgnore; +import java.io.Serializable; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import lombok.ToString; + +@ToString public class StdPDPStatus implements Serializable, PDPStatus { - private static final long serialVersionUID = 1L; - - private Status status = Status.UNKNOWN; - - private Set<String> loadErrors = new HashSet<>(); - - private Set<String> loadWarnings = new HashSet<>(); - - private transient Set<PDPPolicy> loadedPolicies = new HashSet<>(); - - private transient Set<PDPPolicy> loadedRootPolicies = new HashSet<>(); - - private transient Set<PDPPolicy> failedPolicies = new HashSet<>(); - - private transient Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>(); - - private transient Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>(); - - public StdPDPStatus() { - // - // Default constructor - // - } - - public void set(StdPDPStatus newStatus) { - this.status = newStatus.status; - this.loadErrors.clear(); - this.loadErrors.addAll(newStatus.getLoadErrors()); - this.loadWarnings.clear(); - this.loadWarnings.addAll(newStatus.getLoadWarnings()); - this.loadedPolicies.clear(); - this.loadedPolicies.addAll(newStatus.getLoadedPolicies()); - this.loadedRootPolicies.clear(); - this.loadedRootPolicies.addAll(newStatus.getLoadedRootPolicies()); - this.failedPolicies.clear(); - this.failedPolicies.addAll(newStatus.getFailedPolicies()); - this.loadedPIPConfigs.clear(); - this.loadedPIPConfigs.addAll(newStatus.getLoadedPipConfigs()); - this.failedPIPConfigs.clear(); - this.failedPIPConfigs.addAll(newStatus.getFailedPipConfigs()); - } - - - - @Override - public Status getStatus() { - return this.status; - } - - public void setStatus(Status status) { - this.status = status; - } - - @Override - public Set<String> getLoadErrors() { - return Collections.unmodifiableSet(this.loadErrors); - } - - public void setLoadErrors(Set<String> errors) { - this.loadErrors = errors; - } - - public void addLoadError(String error) { - this.loadErrors.add(error); - } - - @Override - public Set<String> getLoadWarnings() { - return Collections.unmodifiableSet(this.loadWarnings); - } - - public void setLoadWarnings(Set<String> warnings) { - this.loadWarnings = warnings; - } - - public void addLoadWarning(String warning) { - this.loadWarnings.add(warning); - } - - @Override - public Set<PDPPolicy> getLoadedPolicies() { - return Collections.unmodifiableSet(this.loadedPolicies); - } - - public void setLoadedPolicies(Set<PDPPolicy> policies) { - this.loadedPolicies = policies; - } - - public void addLoadedPolicy(PDPPolicy policy) { - this.loadedPolicies.add(policy); - } - - @Override - public Set<PDPPolicy> getLoadedRootPolicies() { - return Collections.unmodifiableSet(this.loadedRootPolicies); - } - - public void setLoadedRootPolicies(Set<PDPPolicy> policies) { - this.loadedRootPolicies = policies; - } - - public void addRootPolicy(PDPPolicy policy) { - this.loadedRootPolicies.add(policy); - } - - public void addAllLoadedRootPolicies(Set<PDPPolicy> policies) { - this.loadedRootPolicies.addAll(policies); - } - - @Override - public Set<PDPPolicy> getFailedPolicies() { - return Collections.unmodifiableSet(this.failedPolicies); - } - - public void setFailedPolicies(Set<PDPPolicy> policies) { - this.failedPolicies = policies; - } - - public void addFailedPolicy(PDPPolicy policy) { - this.failedPolicies.add(policy); - } - - @Override - public boolean policiesOK() { - if (!this.failedPolicies.isEmpty()) { - return false; - } - return true; - } - - @Override - public Set<PDPPIPConfig> getLoadedPipConfigs() { - return Collections.unmodifiableSet(this.loadedPIPConfigs); - } - - public void setLoadedPipConfigs(Set<PDPPIPConfig> configs) { - this.loadedPIPConfigs = configs; - } - - public void addLoadedPipConfig(PDPPIPConfig config) { - this.loadedPIPConfigs.add(config); - } - - @Override - public Set<PDPPIPConfig> getFailedPipConfigs() { - return Collections.unmodifiableSet(this.failedPIPConfigs); - } - - public void setFailedPipConfigs(Set<PDPPIPConfig> configs) { - this.failedPIPConfigs = configs; - } - - public void addFailedPipConfig(PDPPIPConfig config) { - this.failedPIPConfigs.add(config); - } - - @Override - public boolean pipConfigOK() { - if (!this.failedPIPConfigs.isEmpty()) { - return false; - } - return true; - } - - @Override - @JsonIgnore - public boolean isOk() { - if (!this.policiesOK()) { - return false; - } - if (!this.pipConfigOK()) { - return false; - } - return this.status == Status.UP_TO_DATE; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime - * result - + (failedPIPConfigs.hashCode()); - result = prime * result - + (failedPolicies.hashCode()); - result = prime * result - + (loadErrors.hashCode()); - result = prime * result - + (loadWarnings.hashCode()); - result = prime - * result - + (loadedPIPConfigs.hashCode()); - result = prime * result - + (loadedPolicies.hashCode()); - result = prime * result + (status.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDPStatus other = (StdPDPStatus) obj; - if (!failedPIPConfigs.equals(other.failedPIPConfigs)) - return false; - if (!failedPolicies.equals(other.failedPolicies)) - return false; - if (!loadErrors.equals(other.loadErrors)) - return false; - if (!loadWarnings.equals(other.loadWarnings)) - return false; - if (!loadedPIPConfigs.equals(other.loadedPIPConfigs)) - return false; - if (!loadedPolicies.equals(other.loadedPolicies)) - return false; - if (!loadedRootPolicies.equals(other.loadedRootPolicies)) - return false; - if (status != other.status) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDPStatus [status=" + status + ", loadErrors=" + loadErrors - + ", loadWarnings=" + loadWarnings + ", loadedPolicies=" - + loadedPolicies + ", loadedRootPolicies=" + loadedRootPolicies - + ", failedPolicies=" + failedPolicies - + ", loadedPIPConfigs=" + loadedPIPConfigs - + ", failedPIPConfigs=" + failedPIPConfigs + "]"; - } + private static final long serialVersionUID = 1L; + + private Status status = Status.UNKNOWN; + + private Set<String> loadErrors = new HashSet<>(); + + private Set<String> loadWarnings = new HashSet<>(); + + private transient Set<PDPPolicy> loadedPolicies = new HashSet<>(); + + private transient Set<PDPPolicy> loadedRootPolicies = new HashSet<>(); + + private transient Set<PDPPolicy> failedPolicies = new HashSet<>(); + + private transient Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>(); + + private transient Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>(); + + public StdPDPStatus() { + // + // Default constructor + // + } + + public void set(StdPDPStatus newStatus) { + this.status = newStatus.status; + this.loadErrors.clear(); + this.loadErrors.addAll(newStatus.getLoadErrors()); + this.loadWarnings.clear(); + this.loadWarnings.addAll(newStatus.getLoadWarnings()); + this.loadedPolicies.clear(); + this.loadedPolicies.addAll(newStatus.getLoadedPolicies()); + this.loadedRootPolicies.clear(); + this.loadedRootPolicies.addAll(newStatus.getLoadedRootPolicies()); + this.failedPolicies.clear(); + this.failedPolicies.addAll(newStatus.getFailedPolicies()); + this.loadedPIPConfigs.clear(); + this.loadedPIPConfigs.addAll(newStatus.getLoadedPipConfigs()); + this.failedPIPConfigs.clear(); + this.failedPIPConfigs.addAll(newStatus.getFailedPipConfigs()); + } + + @Override + public Status getStatus() { + return this.status; + } + + public void setStatus(Status status) { + this.status = status; + } + + @Override + public Set<String> getLoadErrors() { + return Collections.unmodifiableSet(this.loadErrors); + } + + public void setLoadErrors(Set<String> errors) { + this.loadErrors = errors; + } + + public void addLoadError(String error) { + this.loadErrors.add(error); + } + + @Override + public Set<String> getLoadWarnings() { + return Collections.unmodifiableSet(this.loadWarnings); + } + + public void setLoadWarnings(Set<String> warnings) { + this.loadWarnings = warnings; + } + + public void addLoadWarning(String warning) { + this.loadWarnings.add(warning); + } + + @Override + public Set<PDPPolicy> getLoadedPolicies() { + return Collections.unmodifiableSet(this.loadedPolicies); + } + public void setLoadedPolicies(Set<PDPPolicy> policies) { + this.loadedPolicies = policies; + } + public void addLoadedPolicy(PDPPolicy policy) { + this.loadedPolicies.add(policy); + } + + @Override + public Set<PDPPolicy> getLoadedRootPolicies() { + return Collections.unmodifiableSet(this.loadedRootPolicies); + } + + public void setLoadedRootPolicies(Set<PDPPolicy> policies) { + this.loadedRootPolicies = policies; + } + + public void addRootPolicy(PDPPolicy policy) { + this.loadedRootPolicies.add(policy); + } + + public void addAllLoadedRootPolicies(Set<PDPPolicy> policies) { + this.loadedRootPolicies.addAll(policies); + } + + @Override + public Set<PDPPolicy> getFailedPolicies() { + return Collections.unmodifiableSet(this.failedPolicies); + } + + public void setFailedPolicies(Set<PDPPolicy> policies) { + this.failedPolicies = policies; + } + + public void addFailedPolicy(PDPPolicy policy) { + this.failedPolicies.add(policy); + } + + @Override + public boolean policiesOK() { + return this.failedPolicies.isEmpty(); + } + + @Override + public Set<PDPPIPConfig> getLoadedPipConfigs() { + return Collections.unmodifiableSet(this.loadedPIPConfigs); + } + + public void setLoadedPipConfigs(Set<PDPPIPConfig> configs) { + this.loadedPIPConfigs = configs; + } + + public void addLoadedPipConfig(PDPPIPConfig config) { + this.loadedPIPConfigs.add(config); + } + + @Override + public Set<PDPPIPConfig> getFailedPipConfigs() { + return Collections.unmodifiableSet(this.failedPIPConfigs); + } + + public void setFailedPipConfigs(Set<PDPPIPConfig> configs) { + this.failedPIPConfigs = configs; + } + + public void addFailedPipConfig(PDPPIPConfig config) { + this.failedPIPConfigs.add(config); + } + + @Override + public boolean pipConfigOK() { + return this.failedPIPConfigs.isEmpty(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (failedPIPConfigs.hashCode()); + result = prime * result + (failedPolicies.hashCode()); + result = prime * result + (loadErrors.hashCode()); + result = prime * result + (loadWarnings.hashCode()); + result = prime * result + (loadedPIPConfigs.hashCode()); + result = prime * result + (loadedPolicies.hashCode()); + result = prime * result + (status.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + StdPDPStatus other = (StdPDPStatus) obj; + if (!failedPIPConfigs.equals(other.failedPIPConfigs)) { + return false; + } + if (!failedPolicies.equals(other.failedPolicies)) { + return false; + } + if (!loadErrors.equals(other.loadErrors)) { + return false; + } + if (!loadWarnings.equals(other.loadWarnings)) { + return false; + } + if (!loadedPIPConfigs.equals(other.loadedPIPConfigs)) { + return false; + } + if (!loadedPolicies.equals(other.loadedPolicies)) { + return false; + } + if (!loadedRootPolicies.equals(other.loadedRootPolicies)) { + return false; + } + if (status != other.status) { + return false; + } + return true; + } + + @Override + @JsonIgnore + public boolean isOk() { + if (!this.policiesOK()) { + return false; + } + if (!this.pipConfigOK()) { + return false; + } + return this.status == Status.UP_TO_DATE; + } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/OperationHistoryEngine.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/OperationHistoryEngine.java index 355a6f644..bb7421e94 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/OperationHistoryEngine.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/OperationHistoryEngine.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -20,22 +20,6 @@ package org.onap.policy.xacml.std.pip.engines; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Properties; -import java.util.Set; - -import javax.persistence.EntityManager; -import javax.persistence.Persistence; -import javax.persistence.Query; - -import org.eclipse.persistence.config.PersistenceUnitProperties; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; - import com.att.research.xacml.api.Attribute; import com.att.research.xacml.api.AttributeValue; import com.att.research.xacml.api.Identifier; @@ -54,244 +38,210 @@ import com.att.research.xacml.std.pip.StdPIPResponse; import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; import com.att.research.xacml.util.XACMLProperties; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; + +import javax.persistence.EntityManager; +import javax.persistence.Persistence; +import javax.persistence.Query; + +import org.eclipse.persistence.config.PersistenceUnitProperties; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + /** * PIP Engine for Implementing {@link com.att.research.xacml.std.pip.engines.ConfigurableEngine} interface to provide - * attribute retrieval from Operation History Table. - * + * attribute retrieval from Operation History Table. + * * @version $Revision$ */ -public class OperationHistoryEngine extends StdConfigurableEngine{ - public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB"; - public static final String DEFAULT_ISSUER = "org:onap:xacml:guard:historydb"; - - private static final Logger LOGGER= FlexLogger.getLogger(OperationHistoryEngine.class); - - private static final PIPRequest PIP_REQUEST_ACTOR = new StdPIPRequest( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("actor"), - XACML.ID_DATATYPE_STRING); - - private static final PIPRequest PIP_REQUEST_RECIPE = new StdPIPRequest( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("recipe"), - XACML.ID_DATATYPE_STRING); - - private static final PIPRequest PIP_REQUEST_TARGET = new StdPIPRequest( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("target"), - XACML.ID_DATATYPE_STRING); - - public OperationHistoryEngine() { - super(); - } - - private void addIntegerAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, int value, PIPRequest pipRequest) { - AttributeValue<BigInteger> attributeValue = null; - try { - attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); - } catch (Exception ex) { - LOGGER.error("Failed to convert " + value + " to an AttributeValue<Boolean>", ex); - } - if (attributeValue != null) { - stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false)); - } - } - - @Override - public Collection<PIPRequest> attributesRequired() { - return new ArrayList<>(); - } - - @Override - public Collection<PIPRequest> attributesProvided() { - return new ArrayList<>(); - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { - LOGGER.info("Entering FeqLimiter PIP"); - /* - * First check to see if the issuer is set and then match it - */ - String string; - if ((string = pipRequest.getIssuer()) == null) { - LOGGER.info("FeqLimiter PIP - No issuer in the request!"); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - else{ - //Notice, we are checking here for the base issuer prefix. - if (!string.contains(this.getIssuer())) { - LOGGER.debug("Requested issuer '" + string + "' does not match " + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'")); - LOGGER.info("FeqLimiter PIP - Issuer "+ string +" does not match with: "+this.getIssuer()); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - } - String[] s1 = string.split("tw:"); - String[] s2 = s1[1].split(":"); - int timeWindowVal = Integer.parseInt(s2[0]);// number [of minutes, hours, days...] - String timeWindowScale = s2[1];//e.g., minute, hour, day, week, month, year - String actor = getActor(pipFinder).iterator().next(); - String operation = getRecipe(pipFinder).iterator().next(); - String target = getTarget(pipFinder).iterator().next(); - String timeWindow = timeWindowVal + " " + timeWindowScale; - LOGGER.info("Going to query DB about: "+actor + " " + operation + " " + target + " " + timeWindow); - int countFromDB = getCountFromDB(actor, operation, target, timeWindowVal, timeWindowScale); - StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse(); - this.addIntegerAttribute(stdPIPResponse, - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("count"), - countFromDB, - pipRequest); - return new StdPIPResponse(stdPIPResponse); - } - - @Override - public void configure(String id, Properties properties) throws PIPException { - super.configure(id, properties); - if (this.getDescription() == null) { - this.setDescription(DEFAULT_DESCRIPTION); - } - if (this.getIssuer() == null) { - this.setIssuer(DEFAULT_ISSUER); - } - } - - private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { - PIPResponse pipResponse = null; - try { - pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); - if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { - LOGGER.info("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + pipResponse.getStatus().toString()); - pipResponse = null; - } - if (pipResponse!=null && pipResponse.getAttributes().isEmpty()) { - LOGGER.info("No value for " + pipRequest.getAttributeId().stringValue()); - pipResponse = null; - } - } catch (PIPException ex) { - LOGGER.error("PIPException getting subject-id attribute: " + ex.getMessage(), ex); - } - return pipResponse; - } - - - private Set<String> getActor(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_ACTOR, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection<Attribute> listATTUIDs = pipResponseATTUID.getAttributes(); - Set<String> setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator<AttributeValue<String>> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - return setATTUIDs; - } - - private Set<String> getRecipe(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_RECIPE, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection<Attribute> listATTUIDs = pipResponseATTUID.getAttributes(); - Set<String> setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator<AttributeValue<String>> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - return setATTUIDs; - } - - - private Set<String> getTarget(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_TARGET, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection<Attribute> listATTUIDs = pipResponseATTUID.getAttributes(); - Set<String> setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator<AttributeValue<String>> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - return setATTUIDs; - } - - private static int getCountFromDB(String actor, String operation, String target, int timeWindow, String timeUnits){ - EntityManager em; - try{ - Properties properties = XACMLProperties.getProperties(); - properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/operationHistoryPU.xml"); - em = Persistence.createEntityManagerFactory("OperationsHistoryPU",properties).createEntityManager(); - }catch(Exception e){ - LOGGER.error("Test thread got Exception " + e.getLocalizedMessage() + " Can't connect to Operations History DB.", e); - return -1; - } - // Preventing SQL injection - if(!validTimeUnits(timeUnits)){ - LOGGER.error("given PIP timeUnits is not valid. " + timeUnits); - em.close(); - return -1; - } - String sql = "select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=?" - + " and operation=?" - + " and target=?" - + " and endtime between date_sub(now(),interval ? "+timeUnits+") and now()"; - Query nq = em.createNativeQuery(sql); - nq.setParameter(1, actor); - nq.setParameter(2, operation); - nq.setParameter(3, target); - nq.setParameter(4, timeWindow); - int ret = ((Number)nq.getSingleResult()).intValue(); - LOGGER.info("###########************** History count: " + ret); - em.close(); - return ret; - } - - // Validating Time Units to prevent SQL Injection. - private static boolean validTimeUnits(String timeUnits) { - return ("minute".equalsIgnoreCase(timeUnits) || "hour".equalsIgnoreCase(timeUnits) || "day".equalsIgnoreCase(timeUnits) - || "week".equalsIgnoreCase(timeUnits) || "month".equalsIgnoreCase(timeUnits)|| "year".equalsIgnoreCase(timeUnits))? - true: false; - } +public class OperationHistoryEngine extends StdConfigurableEngine { + public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB"; + public static final String DEFAULT_ISSUER = "org:onap:xacml:guard:historydb"; + + private static final Logger LOGGER = FlexLogger.getLogger(OperationHistoryEngine.class); + + private static final PIPRequest PIP_REQUEST_ACTOR = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("actor"), XACML.ID_DATATYPE_STRING); + + private static final PIPRequest PIP_REQUEST_RECIPE = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("recipe"), XACML.ID_DATATYPE_STRING); + + private static final PIPRequest PIP_REQUEST_TARGET = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("target"), XACML.ID_DATATYPE_STRING); + + public OperationHistoryEngine() { + super(); + } + + private void addIntegerAttribute(StdMutablePIPResponse stdPipResponse, Identifier category, Identifier attributeId, + int value, PIPRequest pipRequest) { + AttributeValue<BigInteger> attributeValue = null; + try { + attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); + } catch (Exception ex) { + LOGGER.error("Failed to convert " + value + " to an AttributeValue<Boolean>", ex); + } + if (attributeValue != null) { + stdPipResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, + pipRequest.getIssuer()/* this.getIssuer() */, false)); + } + } + + @Override + public Collection<PIPRequest> attributesRequired() { + return new ArrayList<>(); + } + + @Override + public Collection<PIPRequest> attributesProvided() { + return new ArrayList<>(); + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { + LOGGER.info("Entering FeqLimiter PIP"); + /* + * First check to see if the issuer is set and then match it + */ + String string; + if ((string = pipRequest.getIssuer()) == null) { + LOGGER.info("FeqLimiter PIP - No issuer in the request!"); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } else { + // Notice, we are checking here for the base issuer prefix. + if (!string.contains(this.getIssuer())) { + LOGGER.debug("Requested issuer '" + string + "' does not match " + + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'")); + LOGGER.info("FeqLimiter PIP - Issuer " + string + " does not match with: " + this.getIssuer()); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + } + String[] s1 = string.split("tw:"); + String[] s2 = s1[1].split(":"); + int timeWindowVal = Integer.parseInt(s2[0]);// number [of minutes, hours, days...] + String timeWindowScale = s2[1];// e.g., minute, hour, day, week, month, year + String actor = getActor(pipFinder).iterator().next(); + String operation = getRecipe(pipFinder).iterator().next(); + String target = getTarget(pipFinder).iterator().next(); + String timeWindow = timeWindowVal + " " + timeWindowScale; + LOGGER.info("Going to query DB about: " + actor + " " + operation + " " + target + " " + timeWindow); + int countFromDB = getCountFromDB(actor, operation, target, timeWindowVal, timeWindowScale); + StdMutablePIPResponse stdPipResponse = new StdMutablePIPResponse(); + this.addIntegerAttribute(stdPipResponse, XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("count"), + countFromDB, pipRequest); + return new StdPIPResponse(stdPipResponse); + } + + @Override + public void configure(String id, Properties properties) throws PIPException { + super.configure(id, properties); + if (this.getDescription() == null) { + this.setDescription(DEFAULT_DESCRIPTION); + } + if (this.getIssuer() == null) { + this.setIssuer(DEFAULT_ISSUER); + } + } + + private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { + PIPResponse pipResponse = null; + try { + pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); + if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { + LOGGER.info("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + + pipResponse.getStatus().toString()); + pipResponse = null; + } + if (pipResponse != null && pipResponse.getAttributes().isEmpty()) { + LOGGER.info("No value for " + pipRequest.getAttributeId().stringValue()); + pipResponse = null; + } + } catch (PIPException ex) { + LOGGER.error("PIPException getting subject-id attribute: " + ex.getMessage(), ex); + } + return pipResponse; + } + + private Set<String> getActor(PIPFinder pipFinder) { + return getUuids(this.getAttribute(PIP_REQUEST_ACTOR, pipFinder)); + } + + private Set<String> getRecipe(PIPFinder pipFinder) { + return getUuids(this.getAttribute(PIP_REQUEST_RECIPE, pipFinder)); + } + + private Set<String> getTarget(PIPFinder pipFinder) { + return getUuids(this.getAttribute(PIP_REQUEST_TARGET, pipFinder)); + } + + private Set<String> getUuids(PIPResponse pipResponseAttUid) { + /* + * Get the UID from either the subject id or the attuid property + */ + if (pipResponseAttUid == null) { + return new HashSet<>(); + } + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Set<String> setAttUids = new HashSet<>(); + for (Attribute attributeAttUid : pipResponseAttUid.getAttributes()) { + Iterator<AttributeValue<String>> iterAttributeValues = attributeAttUid.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setAttUids.add(attuid); + } + } + } + } + return setAttUids; + } + + private static int getCountFromDB(String actor, String operation, String target, int timeWindow, String timeUnits) { + EntityManager em; + try { + Properties properties = XACMLProperties.getProperties(); + properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, + "META-INF/operationHistoryPU.xml"); + em = Persistence.createEntityManagerFactory("OperationsHistoryPU", properties).createEntityManager(); + } catch (Exception e) { + LOGGER.error( + "Test thread got Exception " + e.getLocalizedMessage() + " Can't connect to Operations History DB.", + e); + return -1; + } + // Preventing SQL injection + if (!validTimeUnits(timeUnits)) { + LOGGER.error("given PIP timeUnits is not valid. " + timeUnits); + em.close(); + return -1; + } + String sql = "select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=?" + + " and operation=?" + " and target=?" + " and endtime between date_sub(now(),interval ? " + timeUnits + + ") and now()"; + Query nq = em.createNativeQuery(sql); + nq.setParameter(1, actor); + nq.setParameter(2, operation); + nq.setParameter(3, target); + nq.setParameter(4, timeWindow); + int ret = ((Number) nq.getSingleResult()).intValue(); + LOGGER.info("###########************** History count: " + ret); + em.close(); + return ret; + } + + // Validating Time Units to prevent SQL Injection. + private static boolean validTimeUnits(String timeUnits) { + return ("minute".equalsIgnoreCase(timeUnits) || "hour".equalsIgnoreCase(timeUnits) + || "day".equalsIgnoreCase(timeUnits) || "week".equalsIgnoreCase(timeUnits) + || "month".equalsIgnoreCase(timeUnits) || "year".equalsIgnoreCase(timeUnits)) ? true : false; + } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/aaf/AAFEngine.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/aaf/AAFEngine.java index de35e0eb8..c488e51ef 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/aaf/AAFEngine.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/aaf/AAFEngine.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,21 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.policy.xacml.std.pip.engines.aaf; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.onap.policy.utils.AAFPolicyClient; -import org.onap.policy.utils.AAFPolicyException; +package org.onap.policy.xacml.std.pip.engines.aaf; import com.att.research.xacml.api.Attribute; import com.att.research.xacml.api.AttributeValue; @@ -50,101 +37,129 @@ import com.att.research.xacml.std.pip.StdPIPResponse; import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; import com.att.research.xacml.util.XACMLProperties; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.utils.AAFPolicyClient; +import org.onap.policy.utils.AAFPolicyException; + /** * PIP Engine for Implementing {@link com.att.research.xacml.std.pip.engines.ConfigurableEngine} interface to provide - * attribute retrieval from AAF interface. - * + * attribute retrieval from AAF interface. + * * @version $Revision$ */ public class AAFEngine extends StdConfigurableEngine { - - public static final String DEFAULT_DESCRIPTION = "PIP for authenticating aaf attributes using the AAF REST interface"; - public static final String DEFAULT_ISSUER = "aaf"; - - private static final String SUCCESS = "Success"; - - public static final String AAF_RESULT= "AAF_RESULT"; - public static final String AAF_RESPONSE= "AAF_RESPONSE"; - // - public static final Identifier AAF_RESPONSE_ID = new IdentifierImpl(AAF_RESPONSE); - public static final Identifier AAF_RESULT_ID = new IdentifierImpl(AAF_RESULT); - - // - private static final PIPRequest PIP_REQUEST_UID = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_ID"), XACML3.ID_DATATYPE_STRING); - private static final PIPRequest PIP_REQUEST_PASS = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_PASS"), XACML3.ID_DATATYPE_STRING); - private static final PIPRequest PIP_REQUEST_TYPE = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_TYPE"), XACML3.ID_DATATYPE_STRING); - private static final PIPRequest PIP_REQUEST_INSTANCE = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_INSTANCE"), XACML3.ID_DATATYPE_STRING); - private static final PIPRequest PIP_REQUEST_ACTION = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_ACTION"), XACML3.ID_DATATYPE_STRING); - - private static final List<PIPRequest> mapRequiredAttributes = new ArrayList<>(); - static{ - mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_UID)); - mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_PASS)); - mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_TYPE)); - mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_INSTANCE)); - mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_ACTION)); - } - - private static final Map<PIPRequest, String> mapSupportedAttributes = new HashMap<>(); - static{ - mapSupportedAttributes.put(new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESPONSE_ID, XACML3.ID_DATATYPE_STRING), "response"); - mapSupportedAttributes.put(new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESULT_ID, XACML3.ID_DATATYPE_BOOLEAN), "result"); - } - - protected Log logger = LogFactory.getLog(this.getClass()); - - public AAFEngine(){ - //default constructor - } - - private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { - PIPResponse pipResponse = null; - try { - pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); - if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { - this.logger.warn("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + pipResponse.getStatus().toString()); - pipResponse = null; - } - if (pipResponse != null && pipResponse.getAttributes().isEmpty()) { - this.logger.warn("No value for " + pipRequest.getAttributeId().stringValue()); - pipResponse = null; - } - } catch (PIPException ex) { - this.logger.error("PIPException getting subject-id attribute: " + ex.getMessage(), ex); - } - return pipResponse; - } - - private String getValue(PIPResponse pipResponse){ - String result = null; - Collection<Attribute> listAttributes = pipResponse.getAttributes(); - for(Attribute attribute: listAttributes){ - Iterator<AttributeValue<String>> iterAttributeValues = attribute.findValues(DataTypes.DT_STRING); - if(iterAttributeValues!=null) { - while(iterAttributeValues.hasNext()){ - result = iterAttributeValues.next().getValue(); - break; - } - } - } - return result; - } - - private synchronized String getResult(PIPFinder pipFinder) { - PIPResponse pipResponseUID = this.getAttribute(PIP_REQUEST_UID, pipFinder); - PIPResponse pipResponsePass = this.getAttribute(PIP_REQUEST_PASS, pipFinder); - PIPResponse pipResponseType = this.getAttribute(PIP_REQUEST_TYPE, pipFinder); - PIPResponse pipResponseAction = this.getAttribute(PIP_REQUEST_ACTION, pipFinder); - PIPResponse pipResponseInstance = this.getAttribute(PIP_REQUEST_INSTANCE, pipFinder); - String response = null; - // Evaluate AAF if we have all the required values. - if(pipResponseUID!=null && pipResponsePass!=null && pipResponseType != null && pipResponseAction!= null && pipResponseInstance!=null){ - String userName = getValue(pipResponseUID); - String pass = getValue(pipResponsePass); - - AAFPolicyClient aafClient = null; - Properties properties; - try { + + public static final String DEFAULT_DESCRIPTION = + "PIP for authenticating aaf attributes using the AAF REST interface"; + public static final String DEFAULT_ISSUER = "aaf"; + + private static final String SUCCESS = "Success"; + + public static final String AAF_RESULT = "AAF_RESULT"; + public static final String AAF_RESPONSE = "AAF_RESPONSE"; + // + public static final Identifier AAF_RESPONSE_ID = new IdentifierImpl(AAF_RESPONSE); + public static final Identifier AAF_RESULT_ID = new IdentifierImpl(AAF_RESULT); + + // + private static final PIPRequest PIP_REQUEST_UID = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("AAF_ID"), XACML3.ID_DATATYPE_STRING); + private static final PIPRequest PIP_REQUEST_PASS = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("AAF_PASS"), XACML3.ID_DATATYPE_STRING); + private static final PIPRequest PIP_REQUEST_TYPE = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("AAF_TYPE"), XACML3.ID_DATATYPE_STRING); + private static final PIPRequest PIP_REQUEST_INSTANCE = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("AAF_INSTANCE"), XACML3.ID_DATATYPE_STRING); + private static final PIPRequest PIP_REQUEST_ACTION = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("AAF_ACTION"), XACML3.ID_DATATYPE_STRING); + + private static final List<PIPRequest> mapRequiredAttributes = new ArrayList<>(); + + static { + mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_UID)); + mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_PASS)); + mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_TYPE)); + mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_INSTANCE)); + mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_ACTION)); + } + + private static final Map<PIPRequest, String> mapSupportedAttributes = new HashMap<>(); + + static { + mapSupportedAttributes.put( + new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESPONSE_ID, XACML3.ID_DATATYPE_STRING), + "response"); + mapSupportedAttributes.put( + new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESULT_ID, XACML3.ID_DATATYPE_BOOLEAN), + "result"); + } + + protected Log logger = LogFactory.getLog(this.getClass()); + + public AAFEngine() { + // default constructor + } + + private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { + PIPResponse pipResponse = null; + try { + pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); + if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { + this.logger.warn("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + + pipResponse.getStatus().toString()); + pipResponse = null; + } + if (pipResponse != null && pipResponse.getAttributes().isEmpty()) { + this.logger.warn("No value for " + pipRequest.getAttributeId().stringValue()); + pipResponse = null; + } + } catch (PIPException ex) { + this.logger.error("PIPException getting subject-id attribute: " + ex.getMessage(), ex); + } + return pipResponse; + } + + private String getValue(PIPResponse pipResponse) { + String result = null; + Collection<Attribute> listAttributes = pipResponse.getAttributes(); + for (Attribute attribute : listAttributes) { + Iterator<AttributeValue<String>> iterAttributeValues = attribute.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + result = iterAttributeValues.next().getValue(); + break; + } + } + } + return result; + } + + private synchronized String getResult(PIPFinder pipFinder) { + PIPResponse pipResponseUID = this.getAttribute(PIP_REQUEST_UID, pipFinder); + PIPResponse pipResponsePass = this.getAttribute(PIP_REQUEST_PASS, pipFinder); + PIPResponse pipResponseType = this.getAttribute(PIP_REQUEST_TYPE, pipFinder); + PIPResponse pipResponseAction = this.getAttribute(PIP_REQUEST_ACTION, pipFinder); + PIPResponse pipResponseInstance = this.getAttribute(PIP_REQUEST_INSTANCE, pipFinder); + String response = null; + // Evaluate AAF if we have all the required values. + if (pipResponseUID != null && pipResponsePass != null && pipResponseType != null && pipResponseAction != null + && pipResponseInstance != null) { + String userName = getValue(pipResponseUID); + String pass = getValue(pipResponsePass); + + AAFPolicyClient aafClient = null; + Properties properties; + try { properties = XACMLProperties.getProperties(); logger.debug("environment : " + properties.getProperty("ENVIRONMENT")); } catch (IOException e1) { @@ -152,121 +167,127 @@ public class AAFEngine extends StdConfigurableEngine { properties = new Properties(); properties.setProperty("AAF_LOG_LEVEL", "DEBUG"); } - if(userName!=null && pass!=null){ - try { - aafClient = AAFPolicyClient.getInstance(properties); - } catch (AAFPolicyException e) { - logger.error("AAF configuration failed. " + e.getMessage() +e); - } - if(aafClient!=null){ - if(aafClient.checkAuth(userName, pass)){ - String type = getValue(pipResponseType); - String instance = getValue(pipResponseInstance); - String action = getValue(pipResponseAction); - if(aafClient.checkPerm(userName, pass, type, instance, action)){ - response = SUCCESS + "Permissions Validated"; - }else{ - response = "No Permissions for "+userName+" to: "+type+", "+instance+", "+action; - } - }else{ - response = "Authentication Failed for the given Values"; - } - } - }else{ - response = "ID and Password are not given"; - } - - }else{ - response = "Insufficient Values to Evaluate AAF"; - } - return response; - } - - private void addStringAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, String value) { - if (value != null) { - AttributeValue<String> attributeValue = null; - try { - attributeValue = DataTypes.DT_STRING.createAttributeValue(value); - } catch (Exception ex) { - this.logger.error("Failed to convert " + value + " to an AttributeValue<String>", ex); - } - if (attributeValue != null) { - stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, this.getIssuer(), false)); - } - } - } + if (userName != null && pass != null) { + try { + aafClient = AAFPolicyClient.getInstance(properties); + } catch (AAFPolicyException e) { + logger.error("AAF configuration failed. " + e.getMessage() + e); + } + if (aafClient != null) { + if (aafClient.checkAuth(userName, pass)) { + String type = getValue(pipResponseType); + String instance = getValue(pipResponseInstance); + String action = getValue(pipResponseAction); + if (aafClient.checkPerm(userName, pass, type, instance, action)) { + response = SUCCESS + "Permissions Validated"; + } else { + response = + "No Permissions for " + userName + " to: " + type + ", " + instance + ", " + action; + } + } else { + response = "Authentication Failed for the given Values"; + } + } + } else { + response = "ID and Password are not given"; + } + + } else { + response = "Insufficient Values to Evaluate AAF"; + } + return response; + } + + private void addStringAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, + String value) { + if (value != null) { + AttributeValue<String> attributeValue = null; + try { + attributeValue = DataTypes.DT_STRING.createAttributeValue(value); + } catch (Exception ex) { + this.logger.error("Failed to convert " + value + " to an AttributeValue<String>", ex); + } + if (attributeValue != null) { + stdPIPResponse.addAttribute( + new StdMutableAttribute(category, attributeId, attributeValue, this.getIssuer(), false)); + } + } + } + + private void addBooleanAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, + boolean value) { + AttributeValue<Boolean> attributeValue = null; + try { + attributeValue = DataTypes.DT_BOOLEAN.createAttributeValue(value); + } catch (Exception ex) { + this.logger.error("Failed to convert " + value + " to an AttributeValue<Boolean>", ex); + } + if (attributeValue != null) { + stdPIPResponse.addAttribute( + new StdMutableAttribute(category, attributeId, attributeValue, this.getIssuer(), false)); + } + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { + /* + * First check to see if the issuer is set and then match it + */ + String string; - private void addBooleanAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, boolean value) { - AttributeValue<Boolean> attributeValue = null; - try { - attributeValue = DataTypes.DT_BOOLEAN.createAttributeValue(value); - } catch (Exception ex) { - this.logger.error("Failed to convert " + value + " to an AttributeValue<Boolean>", ex); - } - if (attributeValue != null) { - stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, this.getIssuer(), false)); - } - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { - /* - * First check to see if the issuer is set and then match it - */ - String string; + if ((string = pipRequest.getIssuer()) != null && !string.equals(this.getIssuer())) { + this.logger.debug("Requested issuer '" + string + "' does not match " + + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'")); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } - if((string = pipRequest.getIssuer()) != null && !string.equals(this.getIssuer())) { - this.logger.debug("Requested issuer '" + string + "' does not match " + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'")); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } + /* + * Drop the issuer and see if the request matches any of our supported queries + */ + PIPRequest pipRequestSupported = pipRequest.getIssuer() == null ? pipRequest + : new StdPIPRequest(pipRequest.getCategory(), pipRequest.getAttributeId(), pipRequest.getDataTypeId()); + if (!mapSupportedAttributes.containsKey(pipRequestSupported)) { + this.logger.debug("Requested attribute '" + pipRequest.toString() + "' is not supported"); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse(); + String response = this.getResult(pipFinder); + boolean result = false; + if (response != null && response.contains(SUCCESS)) { + result = true; + } + this.addBooleanAttribute(stdPIPResponse, XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESULT_ID, result); + this.addStringAttribute(stdPIPResponse, XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESPONSE_ID, response); + return new StdPIPResponse(stdPIPResponse); + } + @Override + public void configure(String id, Properties properties) throws PIPException { + super.configure(id, properties); + if (this.getDescription() == null) { + this.setDescription(DEFAULT_DESCRIPTION); + } + if (this.getIssuer() == null) { + this.setIssuer(DEFAULT_ISSUER); + } + } - /* - * Drop the issuer and see if the request matches any of our supported queries - */ - PIPRequest pipRequestSupported = pipRequest.getIssuer() == null ? pipRequest : new StdPIPRequest(pipRequest.getCategory(), pipRequest.getAttributeId(), pipRequest.getDataTypeId()); - if (!mapSupportedAttributes.containsKey(pipRequestSupported)) { - this.logger.debug("Requested attribute '" + pipRequest.toString() + "' is not supported"); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse(); - String response = this.getResult(pipFinder); - boolean result = false; - if(response != null && response.contains(SUCCESS)){ - result = true; - } - this.addBooleanAttribute(stdPIPResponse, XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESULT_ID, result); - this.addStringAttribute(stdPIPResponse, XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESPONSE_ID, response); - return new StdPIPResponse(stdPIPResponse); - } + @Override + public Collection<PIPRequest> attributesRequired() { + List<PIPRequest> attributes = new ArrayList<>(); + for (PIPRequest attribute : mapRequiredAttributes) { + attributes.add(new StdPIPRequest(attribute)); + } + return attributes; + } - @Override - public void configure(String id, Properties properties) throws PIPException { - super.configure(id, properties); - if (this.getDescription() == null) { - this.setDescription(DEFAULT_DESCRIPTION); - } - if (this.getIssuer() == null) { - this.setIssuer(DEFAULT_ISSUER); - } - } - - @Override - public Collection<PIPRequest> attributesRequired() { - List<PIPRequest> attributes = new ArrayList<>(); - for (PIPRequest attribute: mapRequiredAttributes) { - attributes.add(new StdPIPRequest(attribute)); - } - return attributes; - } + @Override + public Collection<PIPRequest> attributesProvided() { + List<PIPRequest> attributes = new ArrayList<>(); + for (PIPRequest attribute : mapSupportedAttributes.keySet()) { + attributes.add(new StdPIPRequest(attribute)); + } + return attributes; + } - @Override - public Collection<PIPRequest> attributesProvided() { - List<PIPRequest> attributes = new ArrayList<>(); - for (PIPRequest attribute : mapSupportedAttributes.keySet()) { - attributes.add(new StdPIPRequest(attribute)); - } - return attributes; - } - -}
\ No newline at end of file +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/MetricsUtil.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/MetricsUtil.java index 58f5a49e1..42dbd851b 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/MetricsUtil.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/MetricsUtil.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,70 +17,71 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.util; public class MetricsUtil { - - private MetricsUtil() { - // - // private constructor to hide the implicit public one for utility class - // - } - - public static class AvgLatency { - private long cumLatency = 0; - private long count = 0; - - public void compute(long latency) { - cumLatency += latency; - count++; - } - - public long avg() { - if (count == 0) - return 0; - - return cumLatency / count; - } - - public void reset() { - cumLatency = 0; - count = 0; - } - } - - public static class MinLatency { - private long min = Long.MAX_VALUE; - - public synchronized void compute(long ts) { - if (ts < min) - min = ts; - } - - public long min() { - return min; - } - - public void reset() { - min = Long.MAX_VALUE; - } - } - - public static class MaxLatency { - private long max = Long.MIN_VALUE; - - public synchronized void compute(long ts) { - if (ts > max) - max = ts; - } - - public long max() { - return max; - } - - public void reset() { - max = Long.MIN_VALUE; - } - } + + private MetricsUtil() { + // + // private constructor to hide the implicit public one for utility class + // + } + + public static class AvgLatency { + private long cumLatency = 0; + private long count = 0; + + public void compute(long latency) { + cumLatency += latency; + count++; + } + + public long avg() { + if (count == 0) + return 0; + + return cumLatency / count; + } + + public void reset() { + cumLatency = 0; + count = 0; + } + } + + public static class MinLatency { + private long min = Long.MAX_VALUE; + + public synchronized void compute(long ts) { + if (ts < min) + min = ts; + } + + public long min() { + return min; + } + + public void reset() { + min = Long.MAX_VALUE; + } + } + + public static class MaxLatency { + private long max = Long.MIN_VALUE; + + public synchronized void compute(long ts) { + if (ts > max) + max = ts; + } + + public long max() { + return max; + } + + public void reset() { + max = Long.MIN_VALUE; + } + } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java index e0ee60ade..228354c4f 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-XACML * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,8 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.xacml.util; +import com.att.research.xacml.api.AttributeAssignment; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAttribute; +import com.att.research.xacml.std.StdAttributeAssignment; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.std.StdMutableAdvice; +import com.att.research.xacml.std.StdMutableObligation; +import com.att.research.xacml.util.XACMLPolicyScanner.Callback; +import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; + import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; @@ -33,24 +44,6 @@ import javax.xml.bind.Unmarshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; - -import com.att.research.xacml.api.AttributeAssignment; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdAttribute; -import com.att.research.xacml.std.StdAttributeAssignment; -import com.att.research.xacml.std.StdAttributeValue; -import com.att.research.xacml.std.StdMutableAdvice; -import com.att.research.xacml.std.StdMutableObligation; -import com.att.research.xacml.util.XACMLPolicyScanner.Callback; -import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; - 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; @@ -69,598 +62,603 @@ 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 org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + /** - * class XACMLPolicyScanner + * class XACMLPolicyScanner. * - * This class traverses the hierarchy of a XACML 3.0 policy. You can optionally pass a Callback class + * <p>This class traverses the hierarchy of a XACML 3.0 policy. You can optionally pass a Callback class * and override any desired methods to retrieve information from a policy. * * */ public class XACMLPolicyScanner { - private static final Log logger = LogFactory.getLog(XACMLPolicyScanner.class); - private Object policyObject = null; - private Callback callback = null; - - public XACMLPolicyScanner(Path filename, Callback callback) { - try (InputStream is = Files.newInputStream(filename)) { - this.policyObject = XACMLPolicyScanner.readPolicy(is); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); - } - this.callback = callback; - } - - public XACMLPolicyScanner(InputStream filename, Callback callback) { - try (InputStream is = filename) { - this.policyObject = XACMLPolicyScanner.readPolicy(is); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); - } - this.callback = callback; - } - - public XACMLPolicyScanner(PolicySetType policySet, Callback callback) { - this.policyObject = policySet; - this.callback = callback; - } - - public XACMLPolicyScanner(PolicySetType policySet) { - this(policySet, null); - } - - public XACMLPolicyScanner(PolicyType policy, Callback callback) { - this.policyObject = policy; - this.callback = callback; - } - - public XACMLPolicyScanner(PolicyType policy) { - this(policy, null); - } - - /** - * Sets the callback interface to be used. - * - * @param cb - */ - public void setCallback(Callback cb) { - this.callback = cb; - } - - /** - * Saves the given callback object then calls the scan() method. - * - * @param cb - * @return - */ - public Object scan(Callback cb) { - this.callback = cb; - return this.scan(); - } - - /** - * - * This begins the scanning of the contained object. - * - * @return - The PolicySet/Policy that was scanned. - */ - public Object scan() { - if (this.policyObject == null) { - return null; - } - if (this.callback != null && this.callback.onBeginScan(this.policyObject) == CallbackResult.STOP) { - return this.policyObject; - } - if (this.policyObject instanceof PolicyType) { - this.scanPolicy(null, (PolicyType) this.policyObject); - } else if (this.policyObject instanceof PolicySetType) { - this.scanPolicySet(null, (PolicySetType) this.policyObject); - } else { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + "Unknown class type: " + this.policyObject.getClass().getCanonicalName()); - } - if (this.callback != null) { - this.callback.onFinishScan(this.policyObject); - } - return this.policyObject; - } - - /** - * This performs the scan of a PolicySet - * - * @param parent - Its parent PolicySet. Can be null if this is the root. - * @param policySet - The PolicySet object. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - /** - * @param parent - * @param policySet - * @return - */ - protected CallbackResult scanPolicySet(PolicySetType parent, PolicySetType policySet) { - if (logger.isTraceEnabled()) { - logger.trace("scanning policy set: " + policySet.getPolicySetId() + " " + policySet.getDescription()); - } - if (this.callback != null && this.callback.onPreVisitPolicySet(parent, policySet) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - // - // Scan its info - // - if (this.scanTarget(policySet, policySet.getTarget()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanObligations(policySet, policySet.getObligationExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanAdvice(policySet, policySet.getAdviceExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - // - // Iterate the policy sets and/or policies - // - List<JAXBElement<?>> list = policySet.getPolicySetOrPolicyOrPolicySetIdReference(); - for (JAXBElement<?> element: list) { - if ("PolicySet".equals(element.getName().getLocalPart()) && - this.scanPolicySet(policySet, (PolicySetType)element.getValue()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } else if ("Policy".equals(element.getName().getLocalPart()) && - this.scanPolicy(policySet, (PolicyType)element.getValue()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } else { - logger.warn("generating policy sets found unsupported element: " + element.getName().getNamespaceURI()); - } - } - if (this.callback != null && this.callback.onPostVisitPolicySet(parent, policySet) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - return CallbackResult.CONTINUE; - } - - /** - * - * This performs scanning of the Policy object. - * - * @param parent - The parent PolicySet of the policy. This can be null if this is a root Policy. - * @param policy - The policy being scanned. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - protected CallbackResult scanPolicy(PolicySetType parent, PolicyType policy) { - if (logger.isTraceEnabled()) { - logger.trace("scanning policy: " + policy.getPolicyId() + " " + policy.getDescription()); - } - if (this.callback != null && this.callback.onPreVisitPolicy(parent, policy) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - // - // Scan its info - // - if (this.scanTarget(policy, policy.getTarget()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanVariables(policy, policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanObligations(policy, policy.getObligationExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanAdvice(policy, policy.getAdviceExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - // - // Iterate the rules - // - List<Object> list = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - for (Object o: list) { - if (o instanceof RuleType) { - RuleType rule = (RuleType) o; - if (logger.isTraceEnabled()) { - logger.trace("scanning rule: " + rule.getRuleId() + " " + rule.getDescription()); - } - if (this.callback != null && this.callback.onPreVisitRule(policy, rule) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanTarget(rule, rule.getTarget()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanConditions(rule, rule.getCondition()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanObligations(rule, rule.getObligationExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanAdvice(rule, rule.getAdviceExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.callback != null && this.callback.onPostVisitRule(policy, rule) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } else if (o instanceof VariableDefinitionType) { - if (this.callback != null && this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("scanning policy rules found unsupported object:" + o.toString()); - } - } - } - if (this.callback != null && this.callback.onPostVisitPolicy(parent, policy) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - return CallbackResult.CONTINUE; - } - - /** - * Scans the given target for attributes. Its sole purpose is to return attributes found. - * - * @param parent - The parent PolicySet/Policy/Rule for the target. - * @param target - The target. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - protected CallbackResult scanTarget(Object parent, TargetType target) { - if (target == null) { - return CallbackResult.CONTINUE; - } - List<AnyOfType> anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - List<AllOfType> allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator<AllOfType> iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - List<MatchType> matchList = allOf.getMatch(); - if (matchList != null) { - Iterator<MatchType> iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Finally down to the actual attribute - // - StdAttribute attribute = null; - AttributeValueType value = match.getAttributeValue(); - if (match.getAttributeDesignator() != null && value != null) { - AttributeDesignatorType designator = match.getAttributeDesignator(); - // - // The content may be tricky - // - attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), - new IdentifierImpl(designator.getAttributeId()), - new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()), - designator.getIssuer(), - false); - } else if (match.getAttributeSelector() != null && value != null) { - AttributeSelectorType selector = match.getAttributeSelector(); - attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), - new IdentifierImpl(selector.getContextSelectorId()), - new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()), - null, - false); - } else { - logger.warn("NULL designator/selector or value for match."); - } - if (attribute != null && this.callback != null && this.callback.onAttribute(parent, target, attribute) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - } - } - } - } - } - return CallbackResult.CONTINUE; - } - - /** - * Scan the list of obligations. - * - * @param parent - The parent PolicySet/Policy/Rule for the obligation. - * @param obligationExpressionsType - All the obligation expressions. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - protected CallbackResult scanObligations(Object parent, ObligationExpressionsType obligationExpressionsType) { - if (obligationExpressionsType == null) { - return CallbackResult.CONTINUE; - } - List<ObligationExpressionType> expressions = obligationExpressionsType.getObligationExpression(); - if (expressions == null || expressions.isEmpty()) { - return CallbackResult.CONTINUE; - } - for (ObligationExpressionType expression : expressions) { - StdMutableObligation ob = new StdMutableObligation(new IdentifierImpl(expression.getObligationId())); - List<AttributeAssignmentExpressionType> assignments = expression.getAttributeAssignmentExpression(); - if (assignments != null) { - for (AttributeAssignmentExpressionType assignment : assignments) { - // category is optional and may be null - IdentifierImpl categoryId = null; - if (assignment.getCategory() != null) { - categoryId = new IdentifierImpl(assignment.getCategory()); - } - AttributeAssignment attribute = new StdAttributeAssignment( - categoryId, - new IdentifierImpl(assignment.getAttributeId()), - assignment.getIssuer(), - new StdAttributeValue<Object>(null, null) - ); - ob.addAttributeAssignment(attribute); - } - } - if (this.callback != null && this.callback.onObligation(parent, expression, ob) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - return CallbackResult.CONTINUE; - } - - /** - * - * Scans the list of advice expressions returning each individually. - * - * @param parent - The parent PolicySet/Policy/Rule for the advice. - * @param adviceExpressionstype - The list of advice expressions. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - protected CallbackResult scanAdvice(Object parent, AdviceExpressionsType adviceExpressionstype) { - if (adviceExpressionstype == null) { - return CallbackResult.CONTINUE; - } - List<AdviceExpressionType> expressions = adviceExpressionstype.getAdviceExpression(); - if (expressions == null || expressions.isEmpty()) { - return CallbackResult.CONTINUE; - } - for (AdviceExpressionType expression : expressions) { - StdMutableAdvice ob = new StdMutableAdvice(new IdentifierImpl(expression.getAdviceId())); - List<AttributeAssignmentExpressionType> assignments = expression.getAttributeAssignmentExpression(); - if (assignments != null) { - for (AttributeAssignmentExpressionType assignment : assignments) { - IdentifierImpl categoryId = null; - if (assignment.getCategory() != null) { - categoryId = new IdentifierImpl(assignment.getCategory()); - } - AttributeAssignment attribute = new StdAttributeAssignment( - categoryId, - new IdentifierImpl(assignment.getAttributeId()), - assignment.getIssuer(), - new StdAttributeValue<Object>(null, null) - ); - ob.addAttributeAssignment(attribute); - } - } - if (this.callback != null && this.callback.onAdvice(parent, expression, ob) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - return CallbackResult.CONTINUE; - } - - /** - * Scans the list of variable definitions. - * - * @param policy - Policy object containing the variable definition. - * @param list - List of variable definitions. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - protected CallbackResult scanVariables(PolicyType policy, List<Object> list) { - if (list == null) { - return CallbackResult.CONTINUE; - } - for (Object o : list) { - if (o instanceof VariableDefinitionType && this.callback != null && this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - - return CallbackResult.CONTINUE; - } - - /** - * Scans the list of conditions. - * - * @param rule - * @param condition - * @return - */ - protected CallbackResult scanConditions(RuleType rule, ConditionType condition) { - if (condition != null && this.callback != null && this.callback.onCondition(rule, condition) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - return CallbackResult.CONTINUE; - } - - /** - * Reads the XACML XML policy file in and returns the version contained in the root Policy/PolicySet element. - * - * @param policy - The policy file. - * @return - The version string from the file (uninterpreted) - * @throws IOException - */ - public static String getVersion(Path policy) throws IOException { - Object data = null; - try (InputStream is = Files.newInputStream(policy)) { - data = XACMLPolicyScanner.readPolicy(is); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); - throw e; - } - if (data == null) { - logger.warn("Version is null."); - return null; - } - return getVersion(data); - } - - /** - * Reads the Policy/PolicySet element object and returns its current version. - * - * @param data - Either a PolicySet or Policy XACML type object. - * @return - The integer version value. -1 if it doesn't exist or was un-parsable. - */ - public static String getVersion(Object data) { - String version = null; - try { - if (data instanceof PolicySetType) { - version = ((PolicySetType)data).getVersion(); - } else if (data instanceof PolicyType) { - version = ((PolicyType)data).getVersion(); - } else { - if (data != null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + data.getClass().getCanonicalName()); - } - return null; - } - if (version != null && version.length() > 0) { - return version; - } else { - logger.warn("No version set in policy"); - } - } catch (NumberFormatException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Invalid version contained in policy: " + version); - return null; - } - return null; - } - - /** - * Returns the Policy or PolicySet ID. - * - * @param data - A XACML 3.0 Policy or PolicySet element object. - * @return The policy/policyset's policy ID - */ - public static String getID(Object data) { - if (data instanceof PolicySetType) { - return ((PolicySetType)data).getPolicySetId(); - } else if (data instanceof PolicyType) { - return ((PolicyType)data).getPolicyId(); - } else { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + data.getClass().getCanonicalName()); - return null; - } - } - - public static List<String> getCreatedByModifiedBy(Path policyPath) throws IOException{ - String createdBy = ""; - String modifiedBy= ""; - String cValue = "@CreatedBy:"; - String mValue = "@ModifiedBy:"; - for(String line: Files.readAllLines(policyPath)){ - line = line.replaceAll("\\s+", ""); - if(line.isEmpty()){ - continue; - } - if(line.contains("<Description>") && line.contains(cValue) && line.contains(mValue)){ - createdBy = line.substring(line.indexOf(cValue) + cValue.length(), line.lastIndexOf(cValue)); - modifiedBy = line.substring(line.indexOf(mValue) + mValue.length(), line.lastIndexOf(mValue)); - break; - } - } - return Arrays.asList(createdBy, modifiedBy); - } - - //get the Created Name of the User on reading the Xml file - public static String getCreatedBy(Path policyPath) throws IOException{ - String userId = ""; - String value = "@CreatedBy:"; - for(String line: Files.readAllLines(policyPath)){ - line = line.replaceAll("\\s+", ""); - if(line.isEmpty()){ - continue; - } - if(line.contains("<Description>") && line.contains(value)){ - userId = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value)); - break; - } - } - return userId; - } - - //get the Modified Name of the User on reading the Xml file - public static String getModifiedBy(Path policyPath) throws IOException{ - String modifiedBy = ""; - String value = "@ModifiedBy:"; - for(String line: Files.readAllLines(policyPath)){ - line = line.replaceAll("\\s+", ""); - if(line.isEmpty()){ - continue; - } - if(line.contains("<Description>") && line.contains(value)){ - modifiedBy = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value)); - break; - } - } - return modifiedBy; - } - - /** - * readPolicy - does the work to read in policy data from a file. - * - * @param policy - The path to the policy file. - * @return - The policy data object. This *should* be either a PolicySet or a Policy. - */ - public static Object readPolicy(InputStream is) { - try { - // - // Create a DOM parser - // - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - // - // Parse the policy file - // - Document doc = db.parse(is); - Element e = doc.getDocumentElement(); - // - // Is it a 3.0 policy? - // - if ("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17".equals(e.getNamespaceURI())) { - // - // A policyset or policy could be the root - // - if (e.getNodeName().endsWith("Policy")) { - // - // Now we can create the context for the policy set - // and unmarshall the policy into a class. - // - JAXBContext context = JAXBContext.newInstance(PolicyType.class); - Unmarshaller um = context.createUnmarshaller(); - JAXBElement<PolicyType> root = um.unmarshal(e, PolicyType.class); - // - // Here is our policy set class - // - return root.getValue(); - } else if (e.getNodeName().endsWith("PolicySet")) { - // - // Now we can create the context for the policy set - // and unmarshall the policy into a class. - // - JAXBContext context = JAXBContext.newInstance(PolicySetType.class); - Unmarshaller um = context.createUnmarshaller(); - JAXBElement<PolicySetType> root = um.unmarshal(e, PolicySetType.class); - // - // Here is our policy set class - // - return root.getValue(); - } else { - if (logger.isDebugEnabled()) { - logger.debug("Not supported yet: " + e.getNodeName()); - } - } - } else { - logger.warn("unsupported namespace: " + e.getNamespaceURI()); - } - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPolicyScanner", "Exception in readPolicy"); - } - return null; - } - - /** - * @return the policyObject - */ - public Object getPolicyObject() { - return policyObject; - } + private static final Log logger = LogFactory.getLog(XACMLPolicyScanner.class); + private Object policyObject = null; + private Callback callback = null; + + /** + * constructor. + * + * @param filename Path + * @param callback Callback + */ + public XACMLPolicyScanner(Path filename, Callback callback) { + try (InputStream is = Files.newInputStream(filename)) { + this.policyObject = XACMLPolicyScanner.readPolicy(is); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); + } + this.callback = callback; + } + + /** + * Constructor. + * + * @param filename InputStream + * @param callback Callback + */ + public XACMLPolicyScanner(InputStream filename, Callback callback) { + try (InputStream is = filename) { + this.policyObject = XACMLPolicyScanner.readPolicy(is); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); + } + this.callback = callback; + } + + public XACMLPolicyScanner(PolicySetType policySet, Callback callback) { + this.policyObject = policySet; + this.callback = callback; + } + + public XACMLPolicyScanner(PolicySetType policySet) { + this(policySet, null); + } + + public XACMLPolicyScanner(PolicyType policy, Callback callback) { + this.policyObject = policy; + this.callback = callback; + } + + public XACMLPolicyScanner(PolicyType policy) { + this(policy, null); + } + + /** + * Sets the callback interface to be used. + * + * @param cb Callback object + */ + public void setCallback(Callback cb) { + this.callback = cb; + } + + /** + * Saves the given callback object then calls the scan() method. + * + * @param cb Callback object + * @return + */ + public Object scan(Callback cb) { + this.callback = cb; + return this.scan(); + } + + /** + * This begins the scanning of the contained object. + * + * @return - The PolicySet/Policy that was scanned. + */ + public Object scan() { + if (this.policyObject == null) { + return null; + } + if (this.callback != null && this.callback.onBeginScan(this.policyObject) == CallbackResult.STOP) { + return this.policyObject; + } + if (this.policyObject instanceof PolicyType) { + this.scanPolicy(null, (PolicyType) this.policyObject); + } else if (this.policyObject instanceof PolicySetType) { + this.scanPolicySet(null, (PolicySetType) this.policyObject); + } else { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + "Unknown class type: " + + this.policyObject.getClass().getCanonicalName()); + } + if (this.callback != null) { + this.callback.onFinishScan(this.policyObject); + } + return this.policyObject; + } + + /** + * This performs the scan of a PolicySet. + * + * @param parent - Its parent PolicySet. Can be null if this is the root. + * @param policySet - The PolicySet object. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanPolicySet(PolicySetType parent, PolicySetType policySet) { + if (logger.isTraceEnabled()) { + logger.trace("scanning policy set: " + policySet.getPolicySetId() + " " + policySet.getDescription()); + } + if (this.callback != null && this.callback.onPreVisitPolicySet(parent, policySet) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + // + // Scan its info + // + if (this.scanTarget(policySet, policySet.getTarget()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanObligations(policySet, policySet.getObligationExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanAdvice(policySet, policySet.getAdviceExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + // + // Iterate the policy sets and/or policies + // + List<JAXBElement<?>> list = policySet.getPolicySetOrPolicyOrPolicySetIdReference(); + for (JAXBElement<?> element : list) { + if ("PolicySet".equals(element.getName().getLocalPart()) + && this.scanPolicySet(policySet, (PolicySetType) element.getValue()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } else if ("Policy".equals(element.getName().getLocalPart()) + && this.scanPolicy(policySet, (PolicyType) element.getValue()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } else { + logger.warn("generating policy sets found unsupported element: " + element.getName().getNamespaceURI()); + } + } + if (this.callback != null && this.callback.onPostVisitPolicySet(parent, policySet) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + return CallbackResult.CONTINUE; + } + + /** + * This performs scanning of the Policy object. + * + * @param parent - The parent PolicySet of the policy. This can be null if this is a root Policy. + * @param policy - The policy being scanned. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanPolicy(PolicySetType parent, PolicyType policy) { + if (logger.isTraceEnabled()) { + logger.trace("scanning policy: " + policy.getPolicyId() + " " + policy.getDescription()); + } + if (this.callback != null && this.callback.onPreVisitPolicy(parent, policy) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + // + // Scan its info + // + if (this.scanTarget(policy, policy.getTarget()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanVariables(policy, + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanObligations(policy, policy.getObligationExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanAdvice(policy, policy.getAdviceExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + // + // Iterate the rules + // + List<Object> list = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + for (Object o : list) { + if (o instanceof RuleType) { + RuleType rule = (RuleType) o; + if (logger.isTraceEnabled()) { + logger.trace("scanning rule: " + rule.getRuleId() + " " + rule.getDescription()); + } + if (this.callback != null && this.callback.onPreVisitRule(policy, rule) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanTarget(rule, rule.getTarget()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanConditions(rule, rule.getCondition()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanObligations(rule, rule.getObligationExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanAdvice(rule, rule.getAdviceExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.callback != null && this.callback.onPostVisitRule(policy, rule) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } else if (o instanceof VariableDefinitionType) { + if (this.callback != null + && this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } else { + if (logger.isDebugEnabled()) { + logger.debug("scanning policy rules found unsupported object:" + o.toString()); + } + } + } + if (this.callback != null && this.callback.onPostVisitPolicy(parent, policy) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + return CallbackResult.CONTINUE; + } + + /** + * Scans the given target for attributes. Its sole purpose is to return attributes found. + * + * @param parent - The parent PolicySet/Policy/Rule for the target. + * @param target - The target. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanTarget(Object parent, TargetType target) { + if (target == null) { + return CallbackResult.CONTINUE; + } + for (AnyOfType anyOf : target.getAnyOf()) { + for (AllOfType allOf : anyOf.getAllOf()) { + for (MatchType match : allOf.getMatch()) { + // + // Finally down to the actual attribute + // + StdAttribute attribute = null; + AttributeValueType value = match.getAttributeValue(); + if (match.getAttributeDesignator() != null && value != null) { + AttributeDesignatorType designator = match.getAttributeDesignator(); + // + // The content may be tricky + // + attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), + new IdentifierImpl(designator.getAttributeId()), + new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), + value.getContent()), + designator.getIssuer(), false); + } else if (match.getAttributeSelector() != null && value != null) { + AttributeSelectorType selector = match.getAttributeSelector(); + attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), + new IdentifierImpl(selector.getContextSelectorId()), + new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), + value.getContent()), + null, false); + } else { + logger.warn("NULL designator/selector or value for match."); + } + if (attribute != null && this.callback != null && this.callback.onAttribute(parent, + target, attribute) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + } + } + return CallbackResult.CONTINUE; + } + + /** + * Scan the list of obligations. + * + * @param parent - The parent PolicySet/Policy/Rule for the obligation. + * @param obligationExpressionsType - All the obligation expressions. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanObligations(Object parent, ObligationExpressionsType obligationExpressionsType) { + if (obligationExpressionsType == null) { + return CallbackResult.CONTINUE; + } + List<ObligationExpressionType> expressions = obligationExpressionsType.getObligationExpression(); + for (ObligationExpressionType expression : expressions) { + StdMutableObligation ob = new StdMutableObligation(new IdentifierImpl(expression.getObligationId())); + for (AttributeAssignmentExpressionType assignment : expression.getAttributeAssignmentExpression()) { + // category is optional and may be null + IdentifierImpl categoryId = null; + if (assignment.getCategory() != null) { + categoryId = new IdentifierImpl(assignment.getCategory()); + } + AttributeAssignment attribute = + new StdAttributeAssignment(categoryId, new IdentifierImpl(assignment.getAttributeId()), + assignment.getIssuer(), new StdAttributeValue<Object>(null, null)); + ob.addAttributeAssignment(attribute); + } + if (this.callback != null && this.callback.onObligation(parent, expression, ob) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + return CallbackResult.CONTINUE; + } + + /** + * Scans the list of advice expressions returning each individually. + * + * @param parent - The parent PolicySet/Policy/Rule for the advice. + * @param adviceExpressionstype - The list of advice expressions. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanAdvice(Object parent, AdviceExpressionsType adviceExpressionstype) { + if (adviceExpressionstype == null) { + return CallbackResult.CONTINUE; + } + List<AdviceExpressionType> expressions = adviceExpressionstype.getAdviceExpression(); + for (AdviceExpressionType expression : expressions) { + StdMutableAdvice ob = new StdMutableAdvice(new IdentifierImpl(expression.getAdviceId())); + for (AttributeAssignmentExpressionType assignment : expression.getAttributeAssignmentExpression()) { + IdentifierImpl categoryId = null; + if (assignment.getCategory() != null) { + categoryId = new IdentifierImpl(assignment.getCategory()); + } + AttributeAssignment attribute = + new StdAttributeAssignment(categoryId, new IdentifierImpl(assignment.getAttributeId()), + assignment.getIssuer(), new StdAttributeValue<Object>(null, null)); + ob.addAttributeAssignment(attribute); + } + if (this.callback != null && this.callback.onAdvice(parent, expression, ob) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + return CallbackResult.CONTINUE; + } + + /** + * Scans the list of variable definitions. + * + * @param policy - Policy object containing the variable definition. + * @param list - List of variable definitions. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanVariables(PolicyType policy, List<Object> list) { + if (list == null) { + return CallbackResult.CONTINUE; + } + for (Object o : list) { + if (o instanceof VariableDefinitionType && this.callback != null + && this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + + return CallbackResult.CONTINUE; + } + + /** + * Scans the list of conditions. + * + * @param rule RuleType + * @param condition ConditionType + * @return CallbackResult + */ + protected CallbackResult scanConditions(RuleType rule, ConditionType condition) { + if (condition != null && this.callback != null + && this.callback.onCondition(rule, condition) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + return CallbackResult.CONTINUE; + } + + /** + * Reads the XACML XML policy file in and returns the version contained in the root Policy/PolicySet element. + * + * @param policy - The policy file. + * @return - The version string from the file (uninterpreted) + * @throws IOException IOException + */ + public static String getVersion(Path policy) throws IOException { + Object data = null; + try (InputStream is = Files.newInputStream(policy)) { + data = XACMLPolicyScanner.readPolicy(is); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); + throw e; + } + if (data == null) { + logger.warn("Version is null."); + return null; + } + return getVersion(data); + } + + /** + * Reads the Policy/PolicySet element object and returns its current version. + * + * @param data - Either a PolicySet or Policy XACML type object. + * @return - The integer version value. -1 if it doesn't exist or was un-parsable. + */ + public static String getVersion(Object data) { + String version = null; + if (data instanceof PolicySetType) { + version = ((PolicySetType) data).getVersion(); + } else if (data instanceof PolicyType) { + version = ((PolicyType) data).getVersion(); + } else { + if (data != null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + + data.getClass().getCanonicalName()); + } + return null; + } + if (version != null && version.length() > 0) { + return version; + } + logger.warn("No version set in policy"); + return null; + } + + /** + * Returns the Policy or PolicySet ID. + * + * @param data - A XACML 3.0 Policy or PolicySet element object. + * @return The policy/policyset's policy ID + */ + public static String getID(Object data) { + if (data instanceof PolicySetType) { + return ((PolicySetType) data).getPolicySetId(); + } else if (data instanceof PolicyType) { + return ((PolicyType) data).getPolicyId(); + } else { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + + data.getClass().getCanonicalName()); + return null; + } + } + + /** + * getCreatedByModifiedBy. + * + * @param policyPath Path + * @return List of String + * @throws IOException IOException + */ + public static List<String> getCreatedByModifiedBy(Path policyPath) throws IOException { + String createdBy = ""; + String modifiedBy = ""; + String createdValue = "@CreatedBy:"; + String modifiedValue = "@ModifiedBy:"; + for (String line : Files.readAllLines(policyPath)) { + line = line.replaceAll("\\s+", ""); + if (line.isEmpty()) { + continue; + } + if (line.contains("<Description>") && line.contains(createdValue) && line.contains(modifiedValue)) { + createdBy = line.substring(line.indexOf(createdValue) + createdValue.length(), + line.lastIndexOf(createdValue)); + modifiedBy = line.substring(line.indexOf(modifiedValue) + modifiedValue.length(), + line.lastIndexOf(modifiedValue)); + break; + } + } + return Arrays.asList(createdBy, modifiedBy); + } + + // get the Created Name of the User on reading the Xml file + /** + * getCreatedBy. + * + * @param policyPath Path + * @return String + * @throws IOException IOException + */ + public static String getCreatedBy(Path policyPath) throws IOException { + String userId = ""; + String value = "@CreatedBy:"; + for (String line : Files.readAllLines(policyPath)) { + line = line.replaceAll("\\s+", ""); + if (line.isEmpty()) { + continue; + } + if (line.contains("<Description>") && line.contains(value)) { + userId = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value)); + break; + } + } + return userId; + } + + // get the Modified Name of the User on reading the Xml file + /** + * getModifiedBy. + * + * @param policyPath Path + * @return String + * @throws IOException IOException + */ + public static String getModifiedBy(Path policyPath) throws IOException { + String modifiedBy = ""; + String value = "@ModifiedBy:"; + for (String line : Files.readAllLines(policyPath)) { + line = line.replaceAll("\\s+", ""); + if (line.isEmpty()) { + continue; + } + if (line.contains("<Description>") && line.contains(value)) { + modifiedBy = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value)); + break; + } + } + return modifiedBy; + } + + /** + * readPolicy - does the work to read in policy data from a file. + * + * @param is - The path to the policy file. + * @return - The policy data object. This *should* be either a PolicySet or a Policy. + */ + public static Object readPolicy(InputStream is) { + try { + // + // Create a DOM parser + // + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + // + // Parse the policy file + // + Document doc = db.parse(is); + Element element = doc.getDocumentElement(); + // + // Is it a 3.0 policy? + // + if ("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17".equals(element.getNamespaceURI())) { + // + // A policyset or policy could be the root + // + if (element.getNodeName().endsWith("Policy")) { + // + // Now we can create the context for the policy set + // and unmarshall the policy into a class. + // + JAXBContext context = JAXBContext.newInstance(PolicyType.class); + Unmarshaller um = context.createUnmarshaller(); + JAXBElement<PolicyType> root = um.unmarshal(element, PolicyType.class); + // + // Here is our policy set class + // + return root.getValue(); + } else if (element.getNodeName().endsWith("PolicySet")) { + // + // Now we can create the context for the policy set + // and unmarshall the policy into a class. + // + JAXBContext context = JAXBContext.newInstance(PolicySetType.class); + Unmarshaller um = context.createUnmarshaller(); + JAXBElement<PolicySetType> root = um.unmarshal(element, PolicySetType.class); + // + // Here is our policy set class + // + return root.getValue(); + } else { + if (logger.isDebugEnabled()) { + logger.debug("Not supported yet: " + element.getNodeName()); + } + } + } else { + logger.warn("unsupported namespace: " + element.getNamespaceURI()); + } + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPolicyScanner", "Exception in readPolicy"); + } + return null; + } + + /** + * getPolicyObject. + * + * @return the policyObject + */ + public Object getPolicyObject() { + return policyObject; + } } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java index fb65bb715..f28d829ee 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java @@ -30,13 +30,13 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; import java.util.List; + import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; + 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; @@ -52,6 +52,9 @@ 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.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + /** * Helper static class for policy writing. * @@ -128,7 +131,6 @@ public class XACMLPolicyWriter { } } - /** * Helper static class that does the work to write a policy to a file on disk. * @@ -148,6 +150,7 @@ public class XACMLPolicyWriter { /** * Helper static class that reads the JAXB element and return policy input stream. + * * @param policyElement * @param className (PolicyType or PolicySetType ?). * @return ByteArrayInputStream. @@ -203,21 +206,24 @@ public class XACMLPolicyWriter { } } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public static String changeFileNameInXmlWhenRenamePolicy(Path filename) { String extension = ""; String domain = null; String repository = "repository"; - if(filename.toString().contains("Config_")){ - domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length()+1), filename.toString().indexOf("Config_")); - }else if(filename.toString().contains("Action_")){ - domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length()+1), filename.toString().indexOf("Action_")); - }else if(filename.toString().contains("Decision_")){ - domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length()+1), filename.toString().indexOf("Decision_")); + if (filename.toString().contains("Config_")) { + domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length() + 1), + filename.toString().indexOf("Config_")); + } else if (filename.toString().contains("Action_")) { + domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length() + 1), + filename.toString().indexOf("Action_")); + } else if (filename.toString().contains("Decision_")) { + domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length() + 1), + filename.toString().indexOf("Decision_")); } - if(domain.contains(File.separator)){ - domain = domain.replace(File.separator, "."); + if (domain.contains(File.separator)) { + domain = domain.replace(File.separator, "."); } try { JAXBContext context = JAXBContext.newInstance(PolicyType.class); @@ -227,73 +233,100 @@ public class XACMLPolicyWriter { if (policyType != null) { TargetType targetType = policyType.getTarget(); List<AnyOfType> anyOfTypes = targetType.getAnyOf(); - for( Iterator anyOfIte = anyOfTypes.iterator(); anyOfIte.hasNext(); ){ + for (Iterator anyOfIte = anyOfTypes.iterator(); anyOfIte.hasNext();) { AnyOfType anyOfType = (AnyOfType) anyOfIte.next(); List<AllOfType> allOf = anyOfType.getAllOf(); - for( Iterator allOfIte = allOf.iterator(); allOfIte.hasNext(); ){ + for (Iterator allOfIte = allOf.iterator(); allOfIte.hasNext();) { AllOfType allOfType = (AllOfType) allOfIte.next(); List<MatchType> match = allOfType.getMatch(); - for( Iterator matchIte = match.iterator(); matchIte.hasNext();) { - MatchType matchType = (MatchType) matchIte.next(); - if("PolicyName".equals(matchType.getAttributeDesignator().getAttributeId())){ + for (Iterator matchIte = match.iterator(); matchIte.hasNext();) { + MatchType matchType = (MatchType) matchIte.next(); + if ("PolicyName".equals(matchType.getAttributeDesignator().getAttributeId())) { AttributeValueType attributeValueType = matchType.getAttributeValue(); List<Object> contents = attributeValueType.getContent(); if (contents != null && !contents.isEmpty()) { - String tmp = filename.getFileName()+""; + String tmp = filename.getFileName() + ""; String newName = tmp.substring(0, tmp.lastIndexOf(".")); attributeValueType.getContent().clear(); - attributeValueType.getContent().add(domain + newName + "." + "xml"); + attributeValueType.getContent().add(domain + newName + "." + "xml"); } } } } } - if(filename.toString().contains("Config_") || filename.toString().contains("Action_")){ - List<Object> objects = policyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + if (filename.toString().contains("Config_") || filename.toString().contains("Action_")) { + List<Object> objects = + policyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); if (objects != null && !objects.isEmpty()) { for (Iterator ite = objects.iterator(); ite.hasNext();) { - RuleType ruleType = (RuleType ) ite.next(); + RuleType ruleType = (RuleType) ite.next(); AdviceExpressionsType adviceExpressionsType = ruleType.getAdviceExpressions(); if (adviceExpressionsType != null) { - List<AdviceExpressionType> adviceExpressionTypes = adviceExpressionsType.getAdviceExpression(); + List<AdviceExpressionType> adviceExpressionTypes = + adviceExpressionsType.getAdviceExpression(); if (adviceExpressionTypes != null && !adviceExpressionTypes.isEmpty()) { - for (Iterator iterator = adviceExpressionTypes - .iterator(); iterator.hasNext();) { - AdviceExpressionType adviceExpressionType = (AdviceExpressionType) iterator - .next(); - if (adviceExpressionType.getAdviceId() != null && !"".equals(adviceExpressionType.getAdviceId()) && ("configID".equals(adviceExpressionType.getAdviceId()) - || "faultID".equals(adviceExpressionType.getAdviceId()) || "PMID".equals(adviceExpressionType.getAdviceId())||"firewallConfigID".equals(adviceExpressionType.getAdviceId()) || "OptimizationID".equals(adviceExpressionType.getAdviceId()) - || "MSID".equals(adviceExpressionType.getAdviceId())) || "GocID".equals(adviceExpressionType.getAdviceId())||"GocHPID".equals(adviceExpressionType.getAdviceId())||"BRMSRAWID".equals(adviceExpressionType.getAdviceId()) - || "BRMSPARAMID".equals(adviceExpressionType.getAdviceId())|| "HPSuppID".equals(adviceExpressionType.getAdviceId()) || "HPFlapID".equals(adviceExpressionType.getAdviceId()) || "HPOverID".equals(adviceExpressionType.getAdviceId())) - { - List<AttributeAssignmentExpressionType> attributeAssignmentExpressionTypes = adviceExpressionType.getAttributeAssignmentExpression(); - if (attributeAssignmentExpressionTypes != null && !attributeAssignmentExpressionTypes.isEmpty()) { - for (Iterator iterator2 = attributeAssignmentExpressionTypes - .iterator(); iterator2.hasNext();) { - AttributeAssignmentExpressionType attributeAssignmentExpressionType = (AttributeAssignmentExpressionType) iterator2 - .next(); - if ("URLID".equals(attributeAssignmentExpressionType.getAttributeId())) { - JAXBElement<AttributeValueType> attributeValueType = (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType.getExpression(); - AttributeValueType attributeValueType1 = attributeValueType.getValue(); + for (Iterator iterator = adviceExpressionTypes.iterator(); iterator.hasNext();) { + AdviceExpressionType adviceExpressionType = + (AdviceExpressionType) iterator.next(); + if (adviceExpressionType.getAdviceId() != null + && !"".equals(adviceExpressionType.getAdviceId()) + && ("configID".equals(adviceExpressionType.getAdviceId()) + || "faultID".equals(adviceExpressionType.getAdviceId()) + || "PMID".equals(adviceExpressionType.getAdviceId()) + || "firewallConfigID".equals(adviceExpressionType.getAdviceId()) + || "OptimizationID".equals(adviceExpressionType.getAdviceId()) + || "MSID".equals(adviceExpressionType.getAdviceId())) + || "GocID".equals(adviceExpressionType.getAdviceId()) + || "GocHPID".equals(adviceExpressionType.getAdviceId()) + || "BRMSRAWID".equals(adviceExpressionType.getAdviceId()) + || "BRMSPARAMID".equals(adviceExpressionType.getAdviceId()) + || "HPSuppID".equals(adviceExpressionType.getAdviceId()) + || "HPFlapID".equals(adviceExpressionType.getAdviceId()) + || "HPOverID".equals(adviceExpressionType.getAdviceId())) { + List<AttributeAssignmentExpressionType> attributeAssignmentExpressionTypes = + adviceExpressionType.getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionTypes != null + && !attributeAssignmentExpressionTypes.isEmpty()) { + for (Iterator iterator2 = + attributeAssignmentExpressionTypes.iterator(); iterator2 + .hasNext();) { + AttributeAssignmentExpressionType attributeAssignmentExpressionType = + (AttributeAssignmentExpressionType) iterator2.next(); + if ("URLID".equals( + attributeAssignmentExpressionType.getAttributeId())) { + JAXBElement<AttributeValueType> attributeValueType = + (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType + .getExpression(); + AttributeValueType attributeValueType1 = + attributeValueType.getValue(); String configUrl = "$URL"; - String urlVal = (String) attributeValueType1.getContent().get(0); - String origExtension = urlVal.substring(urlVal.lastIndexOf('.')+1).trim(); + String urlVal = + (String) attributeValueType1.getContent().get(0); + String origExtension = + urlVal.substring(urlVal.lastIndexOf('.') + 1).trim(); extension = origExtension; attributeValueType1.getContent().clear(); String txtFileName = filename.getFileName().toString(); - txtFileName = txtFileName.substring(0, txtFileName.lastIndexOf(".")+1) + origExtension; - txtFileName = configUrl+ File.separator + "Config" + File.separator + domain + txtFileName; + txtFileName = txtFileName.substring(0, + txtFileName.lastIndexOf(".") + 1) + origExtension; + txtFileName = configUrl + File.separator + "Config" + + File.separator + domain + txtFileName; attributeValueType1.getContent().add(txtFileName); - } else if ("PolicyName".equals(attributeAssignmentExpressionType.getAttributeId())) { - JAXBElement<AttributeValueType> attributeValueType = (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType.getExpression(); - AttributeValueType attributeValueType1 = attributeValueType.getValue(); + } else if ("PolicyName".equals( + attributeAssignmentExpressionType.getAttributeId())) { + JAXBElement<AttributeValueType> attributeValueType = + (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType + .getExpression(); + AttributeValueType attributeValueType1 = + attributeValueType.getValue(); List<Object> contents = attributeValueType1.getContent(); if (contents != null && !contents.isEmpty()) { - String tmp = filename.getFileName()+""; + String tmp = filename.getFileName() + ""; String newName = tmp.substring(0, tmp.lastIndexOf(".")); attributeValueType1.getContent().clear(); - attributeValueType1.getContent().add(domain + newName + "." + "xml"); + attributeValueType1.getContent() + .add(domain + newName + "." + "xml"); } } @@ -308,33 +341,47 @@ public class XACMLPolicyWriter { if (objects != null && !objects.isEmpty()) { for (Iterator ite1 = objects.iterator(); ite1.hasNext();) { - RuleType ruleType1 = (RuleType ) ite1.next(); - ObligationExpressionsType obligationExpressionsType = ruleType1.getObligationExpressions(); + RuleType ruleType1 = (RuleType) ite1.next(); + ObligationExpressionsType obligationExpressionsType = + ruleType1.getObligationExpressions(); if (obligationExpressionsType != null) { - List<ObligationExpressionType> obligationExpressionType = obligationExpressionsType.getObligationExpression(); + List<ObligationExpressionType> obligationExpressionType = + obligationExpressionsType.getObligationExpression(); if (obligationExpressionType != null && !obligationExpressionType.isEmpty()) { - for (Iterator iterator = obligationExpressionType - .iterator(); iterator.hasNext();) { - ObligationExpressionType obligationExpressionTypes = (ObligationExpressionType) iterator - .next(); - if (obligationExpressionTypes.getObligationId() != null && !"".equals(obligationExpressionTypes.getObligationId())) { - List<AttributeAssignmentExpressionType> attributeAssignmentExpressionTypes = obligationExpressionTypes.getAttributeAssignmentExpression(); - if (attributeAssignmentExpressionTypes != null && !attributeAssignmentExpressionTypes.isEmpty()) { - for (Iterator iterator2 = attributeAssignmentExpressionTypes - .iterator(); iterator2.hasNext();) { - AttributeAssignmentExpressionType attributeAssignmentExpressionType = (AttributeAssignmentExpressionType) iterator2 - .next(); - if ("body".equals(attributeAssignmentExpressionType.getAttributeId())) { - JAXBElement<AttributeValueType> attributeValueType = (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType.getExpression(); - AttributeValueType attributeValueType1 = attributeValueType.getValue(); + for (Iterator iterator = obligationExpressionType.iterator(); iterator + .hasNext();) { + ObligationExpressionType obligationExpressionTypes = + (ObligationExpressionType) iterator.next(); + if (obligationExpressionTypes.getObligationId() != null + && !"".equals(obligationExpressionTypes.getObligationId())) { + List<AttributeAssignmentExpressionType> attributeAssignmentExpressionTypes = + obligationExpressionTypes.getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionTypes != null + && !attributeAssignmentExpressionTypes.isEmpty()) { + for (Iterator iterator2 = + attributeAssignmentExpressionTypes.iterator(); iterator2 + .hasNext();) { + AttributeAssignmentExpressionType attributeAssignmentExpressionType = + (AttributeAssignmentExpressionType) iterator2.next(); + if ("body".equals( + attributeAssignmentExpressionType.getAttributeId())) { + JAXBElement<AttributeValueType> attributeValueType = + (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType + .getExpression(); + AttributeValueType attributeValueType1 = + attributeValueType.getValue(); String configUrl = "$URL"; - String urlVal = (String) attributeValueType1.getContent().get(0); - String origExtension = urlVal.substring(urlVal.lastIndexOf('.')+1).trim(); + String urlVal = + (String) attributeValueType1.getContent().get(0); + String origExtension = urlVal + .substring(urlVal.lastIndexOf('.') + 1).trim(); extension = "json"; attributeValueType1.getContent().clear(); String txtFileName = filename.getFileName().toString(); - txtFileName = txtFileName.substring(0, txtFileName.lastIndexOf(".")+1) + origExtension; - txtFileName = configUrl+ File.separator + "Action" + File.separator + domain + txtFileName; + txtFileName = txtFileName.substring(0, + txtFileName.lastIndexOf(".") + 1) + origExtension; + txtFileName = configUrl + File.separator + "Action" + + File.separator + domain + txtFileName; attributeValueType1.getContent().add(txtFileName); } @@ -352,7 +399,7 @@ public class XACMLPolicyWriter { } writePolicyFile(filename, policyType); } - }catch (JAXBException e) { + } catch (JAXBException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); } |