aboutsummaryrefslogtreecommitdiffstats
path: root/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPGroup.java
blob: ae4a43db6e218ff1c667d1efc05196b417ae92bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
/*-
 * ============LICENSE_START=======================================================
 * ECOMP-XACML
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.openecomp.policy.xacml.std.pap;

import org.openecomp.policy.common.logging.eelf.MessageCodes;
import org.openecomp.policy.common.logging.eelf.PolicyLogger;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
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.openecomp.policy.xacml.api.pap.EcompPDP;
import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
import org.openecomp.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.PDPGroup;
//import com.att.research.xacml.api.pap.PDPGroup;
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;

public class StdPDPGroup extends StdPDPItemSetChangeNotifier implements EcompPDPGroup, StdItemSetChangeListener, Comparable<Object>, Serializable {
	private static final long serialVersionUID = 1L;
	private static Log	logger	= LogFactory.getLog(StdPDPGroup.class);
	
	private String id;
	
	private boolean isDefault = false;
	
	private String name;
	
	private String description;
	
	private StdPDPGroupStatus status = new StdPDPGroupStatus(Status.UNKNOWN);
	
	private Set<EcompPDP>	pdps = new HashSet<EcompPDP>();
	
	private Set<PDPPolicy> policies = new HashSet<PDPPolicy>();
	
	private Set<PDPPIPConfig> pipConfigs = new HashSet<PDPPIPConfig>();
	
	@JsonIgnore
	private  Path directory;
	
	@JsonIgnore
	private Integer jmxport;
	
	
	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 id : Splitter.on(',').omitEmptyStrings().trimResults().split(pdpList)) {
							StdPDP pdp = new StdPDP(id, 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("Group directory does NOT exist");
			} catch (IOException e) {
				//TODO:EELF Cleanup - Remove logger
				//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Group directory does NOT exist");
				this.status.addLoadError("Group directory does NOT exist");
				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 +"'");
			}
		} 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
			// TODO: Adding Default PIP engine(s) while Loading initially. We don't want 
			// Programmer intervention with the PIP engines. 
			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 +"'");
			}
		} 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(pipProperties.get(XACMLProperties.PROP_PIP_ENGINES).toString().trim().equals("")){
					pipProperties = setPIPProperties(pipProperties);
					try (OutputStream os = Files.newOutputStream(file)) {
						pipProperties.store(os, "");
					}
				}
				//
				// Parse the pips
				//
				this.readPIPProperties(directory, 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() {
//		//
//		// If we are updating, don't allow reset
//		//
//		if (this.status.getStatus() == Status.UPDATING_CONFIGURATION) {
//			logger.warn("We are updating, chill.");
//			return;
//		}
//		//
//		// Load errors take precedence
//		//
//		if (this.status.getStatus() == Status.LOAD_ERRORS) {
//			logger.warn("We had load errors.");
//			return;
//		}
		//
		// 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().size() > 0) {
			this.status.setStatus(Status.UNKNOWN);
		} else if (this.status.getFailedPDPs().size() > 0 || this.status.getLastUpdateFailedPDPs().size() > 0) {
			this.status.setStatus(Status.LOAD_ERRORS);
		} else if (this.status.getOutOfSynchPDPs().size() > 0) {
			this.status.setStatus(Status.OUT_OF_SYNCH);
		} else if (this.status.getUpdatingPDPs().size() > 0) {
			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.
		//this.firePDPGroupChanged(this);
	}

	@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<PDP> getPdps() {
		return Collections.unmodifiableSet(pdps);
	}

	public void setEcompPdps(Set<EcompPDP> pdps) {
		this.pdps = pdps;
	}
	
	public Set<EcompPDP> getEcompPdps(){
		return Collections.unmodifiableSet(pdps);
	}
	
	public boolean addPDP(EcompPDP 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;
	}

	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<String>();
		List<String> refs = new ArrayList<String>();
		
		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() == false) {
				try {
					Files.delete(tempFile);
				} catch(Exception ee) {
					//TODO:EELF Cleanup - Remove logger
					//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy was invalid, could NOT delete it.", 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) {
			//TODO:EELF Cleanup - Remove logger
			//logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to publishPolicy: ", 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);
			
			//
			// THERE IS A WEIRD PROBLEM ON WINDOWS...
			// The file is already "in use" when we try to access it.  
			// Looking at the file externally while this is halted here does not show the file in use,
			// so there is no indication what is causing the problem.
			//
			// As a way to by-pass the issue, I simply check if the input and the existing file are identical
			// and generate an exception if they are not.
			//
			

			
//			if (Files.exists(policyFilePath)) {
//				// compare the 
//				String incomingPolicyString = null;
//				try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
//					num = ByteStreams.copy(policy, os);
//					incomingPolicyString = new String(os.toByteArray(), "UTF-8"); 
//				}
//				String existingPolicyString = null;
//				try {
//					byte[] bytes =  Files.readAllBytes(policyFilePath);
//					existingPolicyString = new String(bytes, "UTF-8"); 
//				} catch (Exception e) {
//					//TODO:EELF Cleanup - Remove logger
//					logger.error("Unable to read existing file '" + policyFilePath + "': " + e, e);
//					PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdPDPGroup", "Unable to read existing policy file");
//					throw new PAPException("Unable to read policy file for comparison: " + e);
//				}
//				if (incomingPolicyString.equals(existingPolicyString)) {
//					throw new PAPException("Policy '" + policyFilePath + "' does not match existing policy on server");
//				}
//				// input is same as existing file
//				return;
//			}
			
			
			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() == false) {
				try {
					Files.delete(policyFile);
				} catch(Exception ee) {
					//TODO:EELF Cleanup - Remove logger
					//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy was invalid, could NOT delete it.", 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) {
			//TODO:EELF Cleanup - Remove logger
			//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed to copyPolicyToFile: ", 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) {
		StdPDPPolicy currentPolicy = (StdPDPPolicy) this.getPolicy(policy.getId());
		if (currentPolicy == null) {
			//TODO:EELF Cleanup - Remove logger
			//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy " + policy.getId() + " does not exist.");
			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) {
			//TODO:EELF Cleanup - Remove logger
			//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed to delete policy " + policy);
			PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy");
		}
		return false;
	}
	
	public boolean removePolicy(PDPPolicy policy) {
		StdPDPPolicy currentPolicy = (StdPDPPolicy) this.getPolicy(policy.getId());
		if (currentPolicy == null) {
			//TODO:EELF Cleanup - Remove logger
			//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy " + policy.getId() + " does not exist.");
			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) {
			//TODO:EELF Cleanup - Remove logger
			//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed to delete policy " + policy);
			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);
	}
	
	public Properties getPipConfigProperties() {
		Properties properties = new Properties();
		List<String> configs = new ArrayList<String>();
		
		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) {
				//TODO:EELF Cleanup - Remove logger
				//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + 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) {
				//TODO:EELF Cleanup - Remove logger
				//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + 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) {
				//TODO:EELF Cleanup - Remove logger
				//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + 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 id : policyList) {
				//
				// Construct the policy filename
				//
				Path policyPath = Paths.get(directory.toString(), id );
				//
				// Create the Policy Object
				//
				StdPDPPolicy policy;
				try {
					policy = new StdPDPPolicy(id, isRoot, policyPath.toUri(), properties);
				} catch (IOException e) {
					//TODO:EELF Cleanup - Remove logger
					//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed to create policy object", 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.getName() == null) {
					policy.setName(policy.getId());
				}
			}
			isRoot = false;
		}
	}

	private void	readPIPProperties(Path directory, Properties properties) {
		String list = properties.getProperty(XACMLProperties.PROP_PIP_ENGINES);
		if (list == null || list.length() == 0) {
			return;
		}
		for (String id : list.split("[,]")) {
			StdPDPPIPConfig config = new StdPDPPIPConfig(id, 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 + "]";
	}

	@Override
	public void changed() {

		// save the (changed) properties
		try {
			saveGroupConfiguration();
		} catch (PAPException | IOException e) {
			//TODO:EELF Cleanup - Remove logger
			//logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to save group configuration change");
			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(EcompPDPGroup group) {
		this.changed();
	}

	@Override
	public void pdpChanged(EcompPDP pdp) {
		//
		// If one of the group's PDP's changed, then the group changed
		//
		// TODO Really?
		//
		this.changed();
	}

	
	//
	// Methods needed for JSON deserialization
	//
	public StdPDPGroup() {
		
	}
	
	public StdPDPGroup(EcompPDPGroup group) {
		this.id = group.getId();
		this.name = group.getName();
		this.description = group.getDescription();
		this.isDefault = group.isDefaultGroup();
		this.pdps = group.getEcompPdps();
		this.policies = group.getPolicies();
		this.pipConfigs = group.getPipConfigs();
	}

	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 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) {
			//TODO:EELF Cleanup - Remove logger
			//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Group Policies Config save failed: " + e, 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) {
			//TODO:EELF Cleanup - Remove logger
			//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Group PIP Config save failed: " + e, 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);
	}
	
	// TODO: 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.openecomp.policy.xacml.std.pip.engines.aaf.AAFEngine");
		props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "AAF");
		return props;
	}


}