2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
20 package org.onap.policy.xacml.std.pap;
22 import java.io.FileInputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.nio.file.FileVisitResult;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.nio.file.SimpleFileVisitor;
31 import java.nio.file.attribute.BasicFileAttributes;
32 import java.util.ArrayList;
33 import java.util.Collections;
34 import java.util.Enumeration;
35 import java.util.HashSet;
36 import java.util.List;
37 import java.util.Properties;
39 import java.util.TreeSet;
41 import org.apache.commons.logging.Log;
42 import org.apache.commons.logging.LogFactory;
43 import org.onap.policy.common.logging.eelf.MessageCodes;
44 import org.onap.policy.common.logging.eelf.PolicyLogger;
45 import org.onap.policy.xacml.api.XACMLErrorConstants;
46 import org.onap.policy.xacml.api.pap.OnapPDP;
47 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
48 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
50 import com.att.research.xacml.api.pap.PAPException;
51 import com.att.research.xacml.api.pap.PDP;
52 import com.att.research.xacml.api.pap.PDPGroup;
53 import com.att.research.xacml.api.pap.PDPPIPConfig;
54 import com.att.research.xacml.api.pap.PDPPolicy;
55 import com.att.research.xacml.api.pap.PDPStatus;
56 import com.att.research.xacml.util.XACMLProperties;
57 import com.google.common.base.Joiner;
58 import com.google.common.base.Splitter;
59 import com.google.common.collect.Sets;
62 * This is a simple PAP engine that uses some property files and a simple directory
63 * structure in the file system to manage a policy repository and set of PDP nodes.
67 public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
68 public static final String pipPropertyFile = "pip.properties";
70 private static final String addGroup = "addGroup ";
72 private static Log logger = LogFactory.getLog(StdEngine.class);
74 public static final String PROP_PAP_REPO = "xacml.pap.pdps";
75 public static final String PROP_PAP_GROUPS = "xacml.pap.groups";
76 public static final String PROP_PAP_GROUPS_DEFAULT = "xacml.pap.groups.default";
77 public static final String PROP_PAP_GROUPS_DEFAULT_NAME = "default";
78 //this value will be accessed from XacmlPapServlet so that we know if a default group did not exist
79 //and was just added. This way, we can add the new group to the database.
80 public boolean wasDefaultGroupJustAdded = false;
82 protected final Path repository;
83 protected Set<StdPDPGroup> groups;
85 public StdEngine() throws PAPException, IOException {
87 // Get the location in the file system of our repository
89 this.repository = Paths.get(XACMLProperties.getProperty(PROP_PAP_REPO));
96 public StdEngine(Properties properties) throws PAPException, IOException {
98 // Get the location in the file system of our repository
100 this.repository = Paths.get(properties.getProperty(PROP_PAP_REPO));
107 public StdEngine(Path repository) throws PAPException, IOException {
111 this.repository = repository;
118 private void intialize() throws PAPException, IOException {
120 // Sanity check the repository path
122 if (this.repository == null) {
123 throw new PAPException ("No repository specified.");
125 if (Files.notExists(this.repository)) {
126 Files.createDirectory(repository);
128 if (!Files.isDirectory(this.repository)) {
129 throw new PAPException ("Repository is NOT a directory: " + this.repository.toAbsolutePath());
131 if (!Files.isWritable(this.repository)) {
132 throw new PAPException ("Repository is NOT writable: " + this.repository.toAbsolutePath());
140 private void loadGroups() throws PAPException {
142 // Create a properties object
144 Properties properties = new Properties();
145 Path file = Paths.get(this.repository.toString(), XACMLProperties.XACML_PROPERTIES_NAME);
148 // Load the properties
150 try (InputStream is = new FileInputStream(file.toFile())) {
157 this.groups = this.readProperties(this.repository, properties);
158 } catch (IOException e) {
159 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to load properties file");
160 this.groups = new HashSet<>();
163 // Initialize the default group
165 PDPGroup defaultGroup = this.initializeDefaultGroup(file, properties);
166 logger.info("Default group is: " + defaultGroup.getId() + "=" + defaultGroup.getName());
169 private PDPGroup initializeDefaultGroup(Path file, Properties properties) throws PAPException {
170 wasDefaultGroupJustAdded = false;
172 // Make sure we have the default group
174 PDPGroup group = this.getDefaultGroup();
176 wasDefaultGroupJustAdded = true;
180 // We don't have the default group, create it
182 String defaultId = properties.getProperty(PROP_PAP_GROUPS_DEFAULT, PROP_PAP_GROUPS_DEFAULT_NAME);
183 if("".equals(defaultId)){
184 defaultId = PROP_PAP_GROUPS_DEFAULT_NAME;
186 logger.warn("Default group does NOT exist, creating " + defaultId);
187 Path defaultPath = Paths.get(this.repository.toString(), defaultId);
192 if (Files.notExists(defaultPath)) {
194 // Create its directory
196 Files.createDirectory(defaultPath);
198 // Create property files
201 Properties props = new Properties();
202 props.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
203 props.setProperty(XACMLProperties.PROP_ROOTPOLICIES, "");
204 Path policyPath = Paths.get(defaultPath.toAbsolutePath().toString(), "xacml.policy.properties");
205 Files.createFile(policyPath);
206 try (OutputStream os = Files.newOutputStream(policyPath)) {
208 } catch (IOException e) {
209 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to write default policy properties");
213 Properties props = new Properties();
214 props = setPIPProperties(props);
215 Path pipPath = Paths.get(defaultPath.toAbsolutePath().toString(), "xacml.pip.properties");
216 Files.createFile(pipPath);
217 try (OutputStream os = Files.newOutputStream(pipPath)) {
219 } catch (IOException e) {
220 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to write default pip properties");
225 // Create the default group
227 StdPDPGroup newDefault = new StdPDPGroup(defaultId, true, "default", "The default group where new PDP's are put.", defaultPath);
229 // Add it to our list
231 this.groups.add(newDefault);
233 // Save our properties out since we have
234 // a new default group.
236 StdEngine.setGroupProperties(newDefault, properties);
241 try (OutputStream os = Files.newOutputStream(file)) {
242 properties.store(os, "");
244 } catch (IOException e) {
245 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to save properties with new default group information.");
250 wasDefaultGroupJustAdded = true;
252 } catch (IOException e) {
253 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to create default group");
254 throw new PAPException("Failed to create default group");
259 public OnapPDPGroup getDefaultGroup() throws PAPException{
260 for (OnapPDPGroup group : this.groups) {
261 if (group.isDefaultGroup()) {
266 // Default group doesn't exist
272 public OnapPDPGroup getGroup(String id) throws PAPException {
273 for (OnapPDPGroup g: this.groups) {
274 if (g.getId().equals(id)) {
282 public void newGroup(String name, String description) throws PAPException, NullPointerException{
287 throw new NullPointerException();
290 // Do we already have this group?
292 for (PDPGroup group : this.groups) {
293 if (group.getName().equals(name)) {
294 throw new PAPException("Group with this name=" + name + " already exists.");
299 // create an Id that can be used as a file name and a properties file key.
300 // Ids must not contain \/:*?"<>|=,;
301 // The ID must also be unique within the current set of PDPGroups.
302 String id = createNewPDPGroupId(name);
306 // Construct the directory path
308 Path groupPath = Paths.get(this.repository.toString(), id);
310 // If it exists already
312 if (Files.exists(groupPath)) {
313 logger.warn(addGroup + id + " directory exists");
317 // Create the directory
319 Files.createDirectory(groupPath);
320 } catch (IOException e) {
321 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to create " + groupPath);
322 throw new PAPException("Failed to create " + id);
326 // Create the Policies
329 Path policyProperties = Paths.get(groupPath.toString(), "xacml.policy.properties");
330 if (Files.exists(policyProperties)) {
331 logger.warn(addGroup + id + " file exists");
333 Properties props = new Properties();
334 props.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
335 props.setProperty(XACMLProperties.PROP_ROOTPOLICIES, "");
337 Files.createFile(policyProperties);
338 try (OutputStream os = Files.newOutputStream(policyProperties)) {
341 } catch (IOException e) {
342 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to create policyProperties");
343 throw new PAPException("Failed to create " + id);
347 // Create the PIP config
349 Path pipProperties = Paths.get(groupPath.toString(), "xacml.pip.properties");
350 Properties props = new Properties();
351 if (Files.exists(pipProperties)) {
352 logger.warn(addGroup + id + " file exists.");
355 props = setPIPProperties(props);
356 Files.createFile(pipProperties);
357 try (OutputStream os = Files.newOutputStream(pipProperties)) {
360 } catch (IOException e) {
361 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to create pipProperties");
362 throw new PAPException("Failed to create " + id);
369 StdPDPGroup newGroup = new StdPDPGroup(id, name, description, groupPath);
370 // Add the default PIP configuration.
371 String list = props.getProperty(XACMLProperties.PROP_PIP_ENGINES);
372 if (list != null && list.length() > 0) {
373 Set<PDPPIPConfig> pipConfigs = new HashSet<>();
374 for (String pipID : list.split("[,]")) {
375 StdPDPPIPConfig config = new StdPDPPIPConfig(pipID, props);
376 if (config.isConfigured()) {
377 pipConfigs.add(config);
380 newGroup.setPipConfigs(pipConfigs);
382 if (this.groups.add(newGroup)) {
383 // save the new group in our properties and notify any listeners of the change
384 groupChanged(newGroup);
393 * Helper to create a new Group ID.
394 * Use the Name field to create the Id.
395 * The Name is expected to not be null; if it is then this method throws an exception.
396 * The name is supposed to be unique within the current set of groups,
397 * so creating the ID based on the name will create a unique string.
402 private String createNewPDPGroupId(String name) {
404 // replace "bad" characters with sequences that will be ok for file names and properties keys.
405 id = id.replace(" ", "_sp_");
406 id = id.replace("\t", "_tab_");
407 id = id.replace("\\", "_bksl_");
408 id = id.replace("/", "_sl_");
409 id = id.replace(":", "_col_");
410 id = id.replace("*", "_ast_");
411 id = id.replace("?", "_q_");
412 id = id.replace("\"", "_quo_");
413 id = id.replace("<", "_lt_");
414 id = id.replace(">", "_gt_");
415 id = id.replace("|", "_bar_");
416 id = id.replace("=", "_eq_");
417 id = id.replace(",", "_com_");
418 id = id.replace(";", "_scom_");
425 public OnapPDP getPDP(String pdpId) throws PAPException {
426 for (OnapPDPGroup group : this.groups) {
427 for (OnapPDP pdp : group.getOnapPdps()) {
428 if (pdp.getId().equals(pdpId)) {
438 public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
439 if (newGroup == null) {
440 throw new NullPointerException("You must specify which group the PDP will belong to.");
442 PDPGroup currentGroup = this.getPDPGroup(pdp);
443 if (currentGroup == null) {
444 throw new PAPException("PDP must already belong to a group.");
446 if (currentGroup.equals(newGroup)) {
447 logger.warn("Already in that group.");
450 if (currentGroup instanceof StdPDPGroup && newGroup instanceof StdPDPGroup) {
451 if (((StdPDPGroup) currentGroup).removePDP(pdp)) {
452 boolean result = ((StdPDPGroup) newGroup).addPDP(pdp);
455 // Save the configuration
459 PolicyLogger.error("Failed to add to new group, putting back into original group.");
460 if (!((StdPDPGroup) currentGroup).removePDP(pdp)) {
461 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Failed to put PDP back into original group.");
466 String message = "Unknown PDP group class: " + newGroup.getClass().getCanonicalName() + " and " + currentGroup.getClass().getCanonicalName();
467 logger.warn(message);
468 throw new PAPException(message);
474 public void updatePDP(OnapPDP pdp) throws PAPException {
475 PDP currentPDP = this.getPDP(pdp.getId());
476 if (currentPDP == null) {
477 String message = "Unknown PDP id '" + pdp.getId() + "'";
478 logger.warn(message);
479 throw new PAPException(message);
482 // the only things that the user can change are name and description
483 currentPDP.setDescription(pdp.getDescription());
484 currentPDP.setName(pdp.getName());
485 if (currentPDP instanceof OnapPDP) {
486 ((OnapPDP)currentPDP).setJmxPort(pdp.getJmxPort());
492 public void removePDP(OnapPDP pdp) throws PAPException {
493 PDPGroup group = this.getPDPGroup(pdp);
495 throw new NullPointerException();
497 if (group instanceof StdPDPGroup) {
498 boolean result = ((StdPDPGroup) group).removePDP(pdp);
504 String message = "Unknown PDP group class: " + group.getClass().getCanonicalName();
505 logger.warn(message);
506 throw new PAPException(message);
512 * Should never be called - Detailed status is held on the PDP, not the PAP
514 public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
515 return getPDP(pdp.getId()).getStatus();
519 public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group) throws PAPException {
521 throw new NullPointerException();
523 if (group instanceof StdPDPGroup && this.groups.contains(group)) {
524 ((StdPDPGroup) group).publishPolicy(id, name, isRoot, policy);
527 logger.warn("unknown PDP Group: " + group);
528 throw new PAPException("Unknown PDP Group: " + group.getId());
533 public void copyPolicy(PDPPolicy policy, OnapPDPGroup group)
534 throws PAPException {
536 // Currently not used on the PAP side. This is done by ((StdPDPGroup) group).copyPolicyToFile
542 public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
544 throw new NullPointerException();
546 if (group instanceof StdPDPGroup && this.groups.contains(group)) {
547 ((StdPDPGroup) group).removePolicy(policy);
550 logger.warn("unknown PDP Group: " + group);
551 throw new PAPException("Unknown PDP Group: " + group.getId());
559 private Set<StdPDPGroup> readProperties(Path repository, Properties properties) throws PAPException {
560 Set<StdPDPGroup> pdpGroups = new HashSet<>();
562 // See if there is a groups property
564 String groupList = properties.getProperty(PROP_PAP_GROUPS, "");
565 if (groupList == null) {
566 logger.warn("null group list " + PROP_PAP_GROUPS);
569 if (logger.isDebugEnabled()) {
570 logger.debug("group list: " + groupList);
573 // Iterate the groups, converting to a set ensures we have unique groups.
575 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(groupList)) {
577 // Add our Group Object
579 StdPDPGroup g = new StdPDPGroup(id.trim(),
580 id.equals(properties.getProperty(PROP_PAP_GROUPS_DEFAULT, PROP_PAP_GROUPS_DEFAULT_NAME)),
582 Paths.get(repository.toString(), id));
592 if (logger.isDebugEnabled()) {
593 logger.debug("PDP Group List: " + pdpGroups.toString());
598 private void saveConfiguration() throws PAPException, IOException {
600 // Create our properties object
602 Properties properties = new Properties() {
603 private static final long serialVersionUID = 1L;
604 // For Debugging it is helpful for the file to be in a sorted order,
605 // any by returning the keys in the natural Alpha order for strings we get close enough.
606 // TreeSet is sorted, and this just overrides the normal Properties method to get the keys.
608 public synchronized Enumeration<Object> keys() {
609 return Collections.enumeration(new TreeSet<Object>(super.keySet()));
613 // Iterate our groups
615 List<String> ids = new ArrayList<>();
616 for (PDPGroup group : this.groups) {
617 ids.add(group.getId());
618 properties.setProperty(group.getId() + ".name", group.getName() == null ? "" : group.getName());
619 properties.setProperty(group.getId() + ".description", group.getDescription() == null ? "" : group.getDescription());
623 List<String> pdps = new ArrayList<>();
624 for (PDP pdp : group.getPdps()) {
625 pdps.add(pdp.getId());
626 properties.setProperty(pdp.getId() + ".name", pdp.getName() == null ? "" : pdp.getName());
627 properties.setProperty(pdp.getId() + ".description", pdp.getDescription() == null ? "" : pdp.getDescription());
628 if (pdp instanceof OnapPDP) {
629 properties.setProperty(pdp.getId() + ".jmxport", (((OnapPDP)pdp).getJmxPort()==0 ? "" : ((OnapPDP)pdp).getJmxPort()).toString());
633 if (pdps.size() == 1) {
634 pdpList = pdps.get(0);
635 } else if (pdps.size() > 1) {
636 pdpList = Joiner.on(',').skipNulls().join(pdps);
638 if (logger.isDebugEnabled()) {
639 logger.debug("Group " + group.getId() + " PDPS: " + pdpList);
641 properties.setProperty(group.getId() + ".pdps", pdpList);
644 throw new PAPException("Inconsistency - we have NO groups. We should have at least one.");
646 String groupList = "";
647 if (ids.size() == 1) {
648 groupList = ids.get(0);
649 } else if (ids.size() > 1){
650 groupList = Joiner.on(',').skipNulls().join(ids);
652 logger.info("New Group List: " + groupList);
654 properties.setProperty(PROP_PAP_GROUPS, groupList);
656 // Get the default group
658 PDPGroup defaultGroup = this.getDefaultGroup();
659 if (defaultGroup == null) {
660 throw new PAPException("Invalid state - no default group.");
662 properties.setProperty(PROP_PAP_GROUPS_DEFAULT, defaultGroup.getId());
664 // Now we can save the file
666 Path file = Paths.get(this.repository.toString(), "xacml.properties");
667 try (OutputStream os = Files.newOutputStream(file)) {
668 properties.store(os, "");
672 public static void removeGroupProperties(String id, Properties properties) {
673 for (Object key : properties.keySet()) {
674 if (key.toString().startsWith(id + ".")) {
675 properties.remove(key);
680 public static void setGroupProperties(PDPGroup group, Properties properties) {
682 // make sure its in the list of groups
684 Iterable<String> groups = Splitter.on(',').trimResults().omitEmptyStrings().split( properties.getProperty(PROP_PAP_GROUPS, ""));
685 boolean inList = false;
686 for (String g : groups) {
687 if (g.equals(group.getId())) {
692 Set<String> grps = Sets.newHashSet(groups);
693 grps.add(group.getId());
695 if (grps.size() == 1) {
696 newGroupList = grps.iterator().next();
697 } else if (grps.size() > 1) {
698 newGroupList = Joiner.on(',').skipNulls().join(grps);
702 logger.info("New Group List: " + newGroupList);
703 properties.setProperty(PROP_PAP_GROUPS, newGroupList);
706 // Set its properties
708 properties.setProperty(group.getId() + ".name", group.getName());
709 properties.setProperty(group.getId() + ".description", group.getDescription());
713 if (!group.getPdps().isEmpty()) {
715 if (group.getPdps().size() == 1) {
716 pdpList = group.getPdps().iterator().next().getId();
717 } else if (group.getPdps().size() > 1) {
718 Set<String> ids = new HashSet<>();
719 for (PDP pdp : group.getPdps()) {
720 ids.add(pdp.getId());
722 pdpList = Joiner.on(',').skipNulls().join(ids);
724 properties.setProperty(group.getId() + ".pdps", pdpList);
726 properties.setProperty(group.getId() + ".pdps", "");
731 public void changed() {
732 if (logger.isDebugEnabled()) {
733 logger.debug("changed");
739 public void groupChanged(OnapPDPGroup group) {
740 if (logger.isDebugEnabled()) {
741 logger.debug("groupChanged: " + group);
744 this.firePDPGroupChanged(group);
748 public void pdpChanged(OnapPDP pdp) {
749 if (logger.isDebugEnabled()) {
750 logger.debug("pdpChanged: " + pdp);
753 this.firePDPChanged(pdp);
756 private void doSave() {
759 // Save the configuration
761 this.saveConfiguration();
762 } catch (IOException|PAPException e) {
763 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Failed to save configuration");
767 private Properties setPIPProperties(Properties props){
768 props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "AAF");
769 props.setProperty("AAF.name", "AAFEngine");
770 props.setProperty("AAF.description", "AAFEngine to communicate with AAF to take decisions");
771 props.setProperty("AAF.classname","org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine");
772 // read from PIP properties file.
773 Path file = Paths.get(pipPropertyFile);
774 if (!Files.notExists(file)) {
776 Properties prop = new Properties();
778 in = new FileInputStream(file.toFile());
780 } catch (IOException e) {
781 PolicyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "can not load the pip properties from file" +e);
790 public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException {
791 final Set<OnapPDPGroup> grps = new HashSet<>();
792 for (OnapPDPGroup g : this.groups) {
795 return Collections.unmodifiableSet(grps);
799 public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
800 for (OnapPDPGroup group : this.groups) {
801 if (group.getPdps().contains(pdp)) {
809 public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
810 boolean changesMade = false;
811 for (OnapPDPGroup aGroup : groups) {
812 if (aGroup.getId().equals(group.getId())) {
813 if ( ! aGroup.isDefaultGroup()) {
814 if (aGroup instanceof StdPDPGroup) {
815 ((StdPDPGroup) aGroup).setDefault(true);
818 throw new IllegalArgumentException("Group in groups of unknown type '" + aGroup.getClass().getName() + "'");
822 // not the new default group
823 if (aGroup.isDefaultGroup()) {
824 if (aGroup instanceof StdPDPGroup) {
825 ((StdPDPGroup) aGroup).setDefault(false);
828 throw new IllegalArgumentException("Group in groups of unknown type '" + aGroup.getClass().getName() + "'");
842 public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
843 throws PAPException, NullPointerException {
845 throw new PAPException("You must specify which group the PDP will belong to.");
847 if (!this.groups.contains(group)) {
848 throw new PAPException("Unknown group, not in our list.");
850 for (OnapPDP p : group.getOnapPdps()) {
851 if (p.getId().equals(id)) {
852 throw new PAPException("A PDP with this ID exists.");
855 if (group instanceof StdPDPGroup) {
856 StdPDP pdp = new StdPDP(id, name, description, jmxport);
857 if (((StdPDPGroup) group).addPDP(pdp)) {
859 // Save the properties and notify any listeners
870 public void updateGroup(OnapPDPGroup group) throws PAPException {
871 if (group == null || group.getId() == null) {
872 throw new PAPException("Group or id is null");
874 if (group.getName() == null || group.getName().trim().length() == 0) {
875 throw new PAPException("New name for group cannot be null or blank");
877 StdPDPGroup existingGroup = (StdPDPGroup)getGroup(group.getId());
878 if (existingGroup == null) {
879 throw new PAPException("Update found no existing group with id '" + group.getId() + "'");
883 // We do dramatically different things when the Name changes
884 // 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.
885 if (group.getName().equals(existingGroup.getName())) {
889 ((StdPDPGroup)group).saveGroupConfiguration();
890 } catch (IOException e) {
891 throw new PAPException("Unable to save new configuration for '" + group.getName() + "': " + e.getMessage(), e);
893 // update the group in the set by simply replacing the old instance with the new one
894 this.groups.remove(existingGroup);
895 this.groups.add((StdPDPGroup)group);
898 // the name/identity of the group has changed
899 // generate the new id
900 String newId = createNewPDPGroupId(group.getName());
902 // make sure no other group uses the new id
903 for (OnapPDPGroup g : groups) {
904 if (g.getId().equals(newId)) {
905 throw new PAPException("Replacement name maps to ID '" + newId + "' which is already in use");
908 ((StdPDPGroup)group).setId(newId);
910 // rename the existing directory to the new id
911 Path oldPath = existingGroup.getDirectory();
912 Path newPath = Paths.get(oldPath.getParent().toString(), newId);
913 ((StdPDPGroup)group).setDirectory(newPath);
916 boolean success = oldPath.toFile().renameTo(newPath.toFile());
918 throw new PAPException("Unable to rename directory; reason unknown");
920 } catch (Exception e) {
921 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Unable to rename directory");
922 throw new PAPException("Unable to move directory from '" + oldPath + "' to '" + newPath + "': " + e.getMessage(),e);
926 ((StdPDPGroup)group).saveGroupConfiguration();
927 } catch (IOException e) {
928 throw new PAPException("Unable to save new configuration for '" + group.getName() + "': " + e.getMessage(), e);
931 // save the new group into the Set
932 groups.remove(existingGroup);
933 groups.add((StdPDPGroup)group);
937 // perhaps only the group changed, but if the name/id changed it may look to a listener like more than one group
944 public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException, NullPointerException {
946 throw new NullPointerException();
949 // Does this group exist?
951 if (!this.groups.contains(group)) {
952 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "This group doesn't exist.");
953 throw new PAPException("The group '" + group.getId() + "' does not exist");
956 // Is it the default group?
958 if (group.isDefaultGroup()) {
959 throw new PAPException("You cannot delete the default group.");
961 Set<OnapPDP> pdps = group.getOnapPdps();
963 // Are there PDPs? If so, then we need a target group
965 if (!pdps.isEmpty() && newGroup == null) {
966 throw new NullPointerException("Group targeted for deletion has PDPs, you must provide a new group for them.");
971 if (!pdps.isEmpty()) {
972 if (! (newGroup instanceof StdPDPGroup)) {
973 throw new PAPException("Unexpected class for newGroup: " + newGroup.getClass().getCanonicalName());
975 // The movePDP function will modify the set of PDPs in the group.
976 // To avoid concurrent modification exceptions we need to duplicate the list before calling that function.
977 List<OnapPDP> pdpList = new ArrayList<>();
978 for (OnapPDP pdp : pdps) {
981 // now we can use the PDPs from the list without having ConcurrentAccessExceptions
982 for (OnapPDP pdp : pdpList) {
983 this.movePDP(pdp, newGroup);
987 // remove the directory for the group
989 String id = group.getId();
990 Path groupPath = Paths.get(this.repository.toString(), id);
992 // If it exists already
994 if ( ! Files.exists(groupPath)) {
995 logger.warn("removeGroup " + id + " directory does not exist" + groupPath.toString());
998 Files.walkFileTree(groupPath, new SimpleFileVisitor<Path>() {
1001 public FileVisitResult visitFile(Path file,
1002 BasicFileAttributes attrs) throws IOException {
1004 return super.visitFile(file, attrs);
1009 // delete the directory
1011 Files.delete(groupPath);
1012 } catch (IOException e) {
1013 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to delete " + groupPath);
1014 throw new PAPException("Failed to delete " + id);
1018 // remove the group from the set of all groups
1019 groups.remove(group);