0003e12c60a2f700e1ac38a7ef847efa5fc6955b
[policy/engine.git] / ONAP-XACML / src / main / java / org / onap / policy / xacml / util / XACMLPolicyScanner.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-XACML
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20 package org.onap.policy.xacml.util;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.util.Arrays;
27 import java.util.Iterator;
28 import java.util.List;
29
30 import javax.xml.bind.JAXBContext;
31 import javax.xml.bind.JAXBElement;
32 import javax.xml.bind.Unmarshaller;
33 import javax.xml.parsers.DocumentBuilder;
34 import javax.xml.parsers.DocumentBuilderFactory;
35
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.Element;
40 import org.w3c.dom.Node;
41 import org.w3c.dom.NodeList;
42
43 import org.onap.policy.common.logging.eelf.MessageCodes;
44 import org.onap.policy.common.logging.eelf.PolicyLogger;
45
46 import com.att.research.xacml.api.AttributeAssignment;
47 import com.att.research.xacml.std.IdentifierImpl;
48 import com.att.research.xacml.std.StdAttribute;
49 import com.att.research.xacml.std.StdAttributeAssignment;
50 import com.att.research.xacml.std.StdAttributeValue;
51 import com.att.research.xacml.std.StdMutableAdvice;
52 import com.att.research.xacml.std.StdMutableObligation;
53 import com.att.research.xacml.util.XACMLPolicyScanner.Callback;
54 import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult;
55
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeSelectorType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
73
74 /**
75  * class XACMLPolicyScanner
76  * 
77  * This class traverses the hierarchy of a XACML 3.0 policy. You can optionally pass a Callback class
78  * and override any desired methods to retrieve information from a policy. 
79  * 
80  *
81  */
82 public class XACMLPolicyScanner {
83         
84         private static final Log logger                         = LogFactory.getLog(XACMLPolicyScanner.class);
85         private Object policyObject = null;
86         private Callback callback = null;
87         
88         public XACMLPolicyScanner(Path filename, Callback callback) {
89                 try (InputStream is = Files.newInputStream(filename)) {
90                         this.policyObject = XACMLPolicyScanner.readPolicy(is);
91                 } catch (IOException e) {
92                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy");
93                 }
94                 this.callback = callback;
95         }
96         
97         public XACMLPolicyScanner(InputStream filename, Callback callback) {
98                 try (InputStream is = filename) {
99                         this.policyObject = XACMLPolicyScanner.readPolicy(is);
100                 } catch (IOException e) {
101                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy");
102                 }
103                 this.callback = callback;
104         }
105         
106         public XACMLPolicyScanner(PolicySetType policySet, Callback callback) {
107                 this.policyObject = policySet;
108                 this.callback = callback;
109         }
110         
111         public XACMLPolicyScanner(PolicySetType policySet) {
112                 this(policySet, null);
113         }
114         
115         public XACMLPolicyScanner(PolicyType policy, Callback callback) {
116                 this.policyObject = policy;
117                 this.callback = callback;
118         }
119         
120         public XACMLPolicyScanner(PolicyType policy) {
121                 this(policy, null);
122         }
123         
124         /**
125          * Sets the callback interface to be used.
126          * 
127          * @param cb
128          */
129         public void setCallback(Callback cb) {
130                 this.callback = cb;
131         }
132         
133         /**
134          * Saves the given callback object then calls the scan() method.
135          * 
136          * @param cb
137          * @return
138          */
139         public Object scan(Callback cb) {
140                 this.callback = cb;
141                 return this.scan();
142         }
143         
144         /**
145          * 
146          * This begins the scanning of the contained object.
147          * 
148          * @return - The PolicySet/Policy that was scanned.
149          */
150         public Object scan() {
151                 if (this.policyObject == null) {
152                         return null;
153                 }
154                 if (this.callback != null && this.callback.onBeginScan(this.policyObject) == CallbackResult.STOP) {
155                         return this.policyObject;
156                 }
157                 if (this.policyObject instanceof PolicyType) {
158                         this.scanPolicy(null, (PolicyType) this.policyObject);
159                 } else if (this.policyObject instanceof PolicySetType) {
160                         this.scanPolicySet(null, (PolicySetType) this.policyObject);
161                 } else {
162                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + "Unknown class type: " + this.policyObject.getClass().getCanonicalName());
163                 }
164                 if (this.callback != null) {
165                         this.callback.onFinishScan(this.policyObject);
166                 }
167                 return this.policyObject;
168         }
169         
170         /**
171          * This performs the scan of a PolicySet
172          * 
173          * @param parent - Its parent PolicySet. Can be null if this is the root.
174          * @param policySet - The PolicySet object.
175          * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
176          */
177         /**
178          * @param parent
179          * @param policySet
180          * @return
181          */
182         protected CallbackResult scanPolicySet(PolicySetType parent, PolicySetType policySet) {
183                 if (logger.isTraceEnabled()) {
184                         logger.trace("scanning policy set: " + policySet.getPolicySetId() + " " + policySet.getDescription());
185                 }
186                 if (this.callback != null && this.callback.onPreVisitPolicySet(parent, policySet) == CallbackResult.STOP) {
187                         return CallbackResult.STOP;
188                 }
189                 //
190                 // Scan its info
191                 //
192                 if (this.scanTarget(policySet, policySet.getTarget()) == CallbackResult.STOP) {
193                         return CallbackResult.STOP;
194                 }
195                 if (this.scanObligations(policySet, policySet.getObligationExpressions()) == CallbackResult.STOP) {
196                         return CallbackResult.STOP;
197                 }
198                 if (this.scanAdvice(policySet, policySet.getAdviceExpressions()) == CallbackResult.STOP) {
199                         return CallbackResult.STOP;
200                 }
201                 //
202                 // Iterate the policy sets and/or policies
203                 //
204                 List<JAXBElement<?>> list = policySet.getPolicySetOrPolicyOrPolicySetIdReference();
205                 for (JAXBElement<?> element: list) {
206                         if ("PolicySet".equals(element.getName().getLocalPart()) && 
207                                 this.scanPolicySet(policySet, (PolicySetType)element.getValue()) == CallbackResult.STOP) {
208                                 return CallbackResult.STOP;
209                         } else if ("Policy".equals(element.getName().getLocalPart()) &&
210                                            this.scanPolicy(policySet, (PolicyType)element.getValue()) == CallbackResult.STOP) {
211                                 return CallbackResult.STOP;
212                         } else {
213                                 logger.warn("generating policy sets found unsupported element: " + element.getName().getNamespaceURI());
214                         }
215                 }
216                 if (this.callback != null && this.callback.onPostVisitPolicySet(parent, policySet) == CallbackResult.STOP) {
217                         return CallbackResult.STOP;
218                 }
219                 return CallbackResult.CONTINUE;
220         }
221         
222         /**
223          * 
224          * This performs scanning of the Policy object.
225          * 
226          * @param parent - The parent PolicySet of the policy. This can be null if this is a root Policy.
227          * @param policy - The policy being scanned.
228          * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
229          */
230         protected CallbackResult scanPolicy(PolicySetType parent, PolicyType policy) {
231                 if (logger.isTraceEnabled()) {
232                         logger.trace("scanning policy: " + policy.getPolicyId() + " " + policy.getDescription());
233                 }
234                 if (this.callback != null && this.callback.onPreVisitPolicy(parent, policy) == CallbackResult.STOP) {
235                         return CallbackResult.STOP;
236                 }
237                 //
238                 // Scan its info
239                 //
240                 if (this.scanTarget(policy, policy.getTarget()) == CallbackResult.STOP) {
241                         return CallbackResult.STOP;
242                 }
243                 if (this.scanVariables(policy, policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) == CallbackResult.STOP) {
244                         return CallbackResult.STOP;
245                 }
246                 if (this.scanObligations(policy, policy.getObligationExpressions()) == CallbackResult.STOP) {
247                         return CallbackResult.STOP;
248                 }
249                 if (this.scanAdvice(policy, policy.getAdviceExpressions()) == CallbackResult.STOP) {
250                         return CallbackResult.STOP;
251                 }
252                 //
253                 // Iterate the rules
254                 //
255                 List<Object> list = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
256                 for (Object o: list) {
257                         if (o instanceof RuleType) {
258                                 RuleType rule = (RuleType) o;
259                                 if (logger.isTraceEnabled()) {
260                                         logger.trace("scanning rule: " + rule.getRuleId() + " " + rule.getDescription());
261                                 }
262                                 if (this.callback != null && this.callback.onPreVisitRule(policy, rule) == CallbackResult.STOP) {
263                                         return CallbackResult.STOP;
264                                 }
265                                 if (this.scanTarget(rule, rule.getTarget()) == CallbackResult.STOP) {
266                                         return CallbackResult.STOP;
267                                 }
268                                 if (this.scanConditions(rule, rule.getCondition()) == CallbackResult.STOP) {
269                                         return CallbackResult.STOP;
270                                 }
271                                 if (this.scanObligations(rule, rule.getObligationExpressions()) == CallbackResult.STOP) {
272                                         return CallbackResult.STOP;
273                                 }
274                                 if (this.scanAdvice(rule, rule.getAdviceExpressions()) == CallbackResult.STOP) {
275                                         return CallbackResult.STOP;
276                                 }
277                                 if (this.callback != null && this.callback.onPostVisitRule(policy, rule) == CallbackResult.STOP) {
278                                         return CallbackResult.STOP;
279                                 }
280                         } else if (o instanceof VariableDefinitionType) {
281                                 if (this.callback != null && this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) {
282                                         return CallbackResult.STOP;
283                                 }
284                         } else {
285                                 if (logger.isDebugEnabled()) {
286                                         logger.debug("scanning policy rules found unsupported object:" + o.toString());
287                                 }
288                         }
289                 }
290                 if (this.callback != null && this.callback.onPostVisitPolicy(parent, policy) == CallbackResult.STOP) {
291                         return CallbackResult.STOP;
292                 }
293                 return CallbackResult.CONTINUE;
294         }
295         
296         /**
297          * Scans the given target for attributes. Its sole purpose is to return attributes found.
298          * 
299          * @param parent - The parent PolicySet/Policy/Rule for the target.
300          * @param target - The target.
301          * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
302          */
303         protected CallbackResult scanTarget(Object parent, TargetType target) {
304                 if (target == null) {
305                         return CallbackResult.CONTINUE;
306                 }
307                 List<AnyOfType> anyOfList = target.getAnyOf();
308                 if (anyOfList != null) {
309                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
310                         while (iterAnyOf.hasNext()) {
311                                 AnyOfType anyOf = iterAnyOf.next();
312                                 List<AllOfType> allOfList = anyOf.getAllOf();
313                                 if (allOfList != null) {
314                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
315                                         while (iterAllOf.hasNext()) {
316                                                 AllOfType allOf = iterAllOf.next();
317                                                 List<MatchType> matchList = allOf.getMatch();
318                                                 if (matchList != null) {
319                                                         Iterator<MatchType> iterMatch = matchList.iterator();
320                                                         while (iterMatch.hasNext()) {
321                                                                 MatchType match = iterMatch.next();
322                                                                 //
323                                                                 // Finally down to the actual attribute
324                                                                 //
325                                                                 StdAttribute attribute = null;
326                                                                 AttributeValueType value = match.getAttributeValue();
327                                                                 if (match.getAttributeDesignator() != null && value != null) {
328                                                                         AttributeDesignatorType designator = match.getAttributeDesignator();
329                                                                         //
330                                                                         // The content may be tricky
331                                                                         //
332                                                                         attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()),
333                                                                                                                                                         new IdentifierImpl(designator.getAttributeId()),
334                                                                                                                                                         new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()),
335                                                                                                                                                         designator.getIssuer(),
336                                                                                                                                                         false);
337                                                                 } else if (match.getAttributeSelector() != null && value != null) {
338                                                                         AttributeSelectorType selector = match.getAttributeSelector();
339                                                                         attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()),
340                                                                                                                                                         new IdentifierImpl(selector.getContextSelectorId()),
341                                                                                                                                                         new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()),
342                                                                                                                                                         null,
343                                                                                                                                                         false);
344                                                                 } else {
345                                                                         logger.warn("NULL designator/selector or value for match.");
346                                                                 }
347                                                                 if (attribute != null && this.callback != null && this.callback.onAttribute(parent, target, attribute) == CallbackResult.STOP) {
348                                                                         return CallbackResult.STOP;
349                                                                 }
350                                                         }
351                                                 }
352                                         }
353                                 }
354                         }
355                 }
356                 return CallbackResult.CONTINUE;
357         }
358         
359         /**
360          * Scan the list of obligations.
361          * 
362          * @param parent - The parent PolicySet/Policy/Rule for the obligation.
363          * @param obligationExpressionsType - All the obligation expressions.
364          * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
365          */
366         protected CallbackResult scanObligations(Object parent, ObligationExpressionsType obligationExpressionsType) {
367                 if (obligationExpressionsType == null) {
368                         return CallbackResult.CONTINUE;
369                 }
370                 List<ObligationExpressionType> expressions = obligationExpressionsType.getObligationExpression();
371                 if (expressions == null || expressions.isEmpty()) {
372                         return CallbackResult.CONTINUE;
373                 }
374                 for (ObligationExpressionType expression : expressions) {
375                         StdMutableObligation ob = new StdMutableObligation(new IdentifierImpl(expression.getObligationId()));
376                         List<AttributeAssignmentExpressionType> assignments = expression.getAttributeAssignmentExpression();
377                         if (assignments != null) {
378                                 for (AttributeAssignmentExpressionType assignment : assignments) {
379                                         // category is optional and may be null
380                                         IdentifierImpl categoryId = null;
381                                         if (assignment.getCategory() != null) {
382                                                 categoryId = new IdentifierImpl(assignment.getCategory());
383                                         }
384                                         AttributeAssignment attribute = new StdAttributeAssignment(
385                                                                                                 categoryId,
386                                                                                                 new IdentifierImpl(assignment.getAttributeId()),
387                                                                                                 assignment.getIssuer(),
388                                                                                                 new StdAttributeValue<Object>(null, null)
389                                                                                                 );
390                                         ob.addAttributeAssignment(attribute);
391                                 }
392                         }
393                         if (this.callback != null && this.callback.onObligation(parent, expression, ob) == CallbackResult.STOP) {
394                                 return CallbackResult.STOP;
395                         }
396                 }
397                 return CallbackResult.CONTINUE;
398         }
399
400         /**
401          * 
402          * Scans the list of advice expressions returning each individually.
403          * 
404          * @param parent - The parent PolicySet/Policy/Rule for the advice.
405          * @param adviceExpressionstype - The list of advice expressions.
406          * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
407          */
408         protected CallbackResult scanAdvice(Object parent, AdviceExpressionsType adviceExpressionstype) {
409                 if (adviceExpressionstype == null) {
410                         return CallbackResult.CONTINUE;
411                 }
412                 List<AdviceExpressionType> expressions = adviceExpressionstype.getAdviceExpression();
413                 if (expressions == null || expressions.isEmpty()) {
414                         return CallbackResult.CONTINUE;
415                 }
416                 for (AdviceExpressionType expression : expressions) {
417                         StdMutableAdvice ob = new StdMutableAdvice(new IdentifierImpl(expression.getAdviceId()));
418                         List<AttributeAssignmentExpressionType> assignments = expression.getAttributeAssignmentExpression();
419                         if (assignments != null) {
420                                 for (AttributeAssignmentExpressionType assignment : assignments) {
421                                         IdentifierImpl categoryId = null;
422                                         if (assignment.getCategory() != null) {
423                                                 categoryId = new IdentifierImpl(assignment.getCategory());
424                                         }
425                                         AttributeAssignment attribute = new StdAttributeAssignment(
426                                                                                                 categoryId,
427                                                                                                 new IdentifierImpl(assignment.getAttributeId()),
428                                                                                                 assignment.getIssuer(),
429                                                                                                 new StdAttributeValue<Object>(null, null)
430                                                                                                 );
431                                         ob.addAttributeAssignment(attribute);
432                                 }
433                         }
434                         if (this.callback != null && this.callback.onAdvice(parent, expression, ob) == CallbackResult.STOP) {
435                                 return CallbackResult.STOP;
436                         }
437                 }
438                 return CallbackResult.CONTINUE;
439         }
440         
441         /**
442          * Scans the list of variable definitions.
443          * 
444          * @param policy - Policy object containing the variable definition.
445          * @param list - List of variable definitions.
446          * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
447          */
448         protected CallbackResult scanVariables(PolicyType policy, List<Object> list) {
449                 if (list == null) {
450                         return CallbackResult.CONTINUE;
451                 }
452                 for (Object o : list) {
453                         if (o instanceof VariableDefinitionType && this.callback != null && this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) {
454                                 return CallbackResult.STOP;
455                         }
456                 }
457                 
458                 return CallbackResult.CONTINUE;
459         }
460         
461         /**
462          * Scans the list of conditions.
463          * 
464          * @param rule
465          * @param condition
466          * @return
467          */
468         protected CallbackResult scanConditions(RuleType rule, ConditionType condition) {
469                 if (condition != null && this.callback != null && this.callback.onCondition(rule, condition) == CallbackResult.STOP) {
470                         return CallbackResult.STOP;
471                 }
472                 return CallbackResult.CONTINUE;
473         }
474         
475         /**
476          * Reads the XACML XML policy file in and returns the version contained in the root Policy/PolicySet element.
477          * 
478          * @param policy - The policy file.
479          * @return - The version string from the file (uninterpreted)
480          * @throws IOException 
481          */
482         public static String    getVersion(Path policy) throws IOException {
483                 Object data = null;
484                 try (InputStream is = Files.newInputStream(policy)) {
485                         data = XACMLPolicyScanner.readPolicy(is);
486                 } catch (IOException e) {
487                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy");
488                         throw e;
489                 }
490                 if (data == null) {
491                         logger.warn("Version is null.");
492                         return null;
493                 }
494                 return getVersion(data);
495         }
496                 
497         /**
498          * Reads the Policy/PolicySet element object and returns its current version.
499          * 
500          * @param data - Either a PolicySet or Policy XACML type object.
501          * @return - The integer version value. -1 if it doesn't exist or was un-parsable.
502          */
503         public static String    getVersion(Object data) {
504                 String version = null;
505                 try {
506                         if (data instanceof PolicySetType) {
507                                 version = ((PolicySetType)data).getVersion();
508                         } else if (data instanceof PolicyType) {
509                                 version = ((PolicyType)data).getVersion();
510                         } else {
511                                 if (data != null) {
512                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + data.getClass().getCanonicalName());
513                                 }
514                                 return null;
515                         }
516                         if (version != null && version.length() > 0) {
517                                 return version;
518                         } else {
519                                 logger.warn("No version set in policy");
520                         }
521                 } catch (NumberFormatException e) {
522                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Invalid version contained in policy: " + version);
523                         return null;
524                 }
525                 return null;
526         }
527         
528         /**
529          * Returns the Policy or PolicySet ID.
530          * 
531          * @param data - A XACML 3.0 Policy or PolicySet element object.
532          * @return The policy/policyset's policy ID
533          */
534         public static String getID(Object data) {
535                 if (data instanceof PolicySetType) {
536                         return ((PolicySetType)data).getPolicySetId();
537                 } else if (data instanceof PolicyType) {
538                         return ((PolicyType)data).getPolicyId();
539                 } else {
540                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + data.getClass().getCanonicalName());
541                         return null;
542                 }
543         }
544         
545         public static List<String> getCreatedByModifiedBy(Path policyPath) throws IOException{
546                 String createdBy = "";
547                 String modifiedBy= "";
548                 String cValue = "@CreatedBy:";
549                 String mValue = "@ModifiedBy:";
550                 for(String line: Files.readAllLines(policyPath)){
551                         line = line.replaceAll("\\s+", "");
552                         if(line.isEmpty()){
553                                 continue;
554                         }
555                         if(line.contains("<Description>") && line.contains(cValue) && line.contains(mValue)){
556                                 createdBy = line.substring(line.indexOf(cValue) + cValue.length(), line.lastIndexOf(cValue));
557                                 modifiedBy = line.substring(line.indexOf(mValue) + mValue.length(), line.lastIndexOf(mValue));
558                                 break;
559                         }
560                 }
561                 return Arrays.asList(createdBy, modifiedBy);
562         }
563         
564         //get the Created Name of the User on reading the Xml file
565         public static String getCreatedBy(Path policyPath) throws IOException{
566                 String userId = "";
567                 String value = "@CreatedBy:";
568                 for(String line: Files.readAllLines(policyPath)){
569                         line = line.replaceAll("\\s+", "");
570                         if(line.isEmpty()){
571                                 continue;
572                         }
573                         if(line.contains("<Description>") && line.contains(value)){
574                                 userId = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value));
575                                 break;
576                         }
577                 }
578                 return userId;
579         }
580         
581         //get the Modified Name of the User on reading the Xml file
582         public static String getModifiedBy(Path policyPath) throws IOException{
583                 String modifiedBy = "";
584                 String value = "@ModifiedBy:";
585                 for(String line: Files.readAllLines(policyPath)){
586                         line = line.replaceAll("\\s+", "");
587                         if(line.isEmpty()){
588                                 continue;
589                         }
590                         if(line.contains("<Description>") && line.contains(value)){
591                                 modifiedBy = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value));
592                                 break;
593                         }
594                 }
595                 return modifiedBy;
596         }
597
598         /**
599          * readPolicy - does the work to read in policy data from a file.
600          * 
601          * @param policy - The path to the policy file.
602          * @return - The policy data object. This *should* be either a PolicySet or a Policy.
603          */
604         public static Object readPolicy(InputStream is) {
605                 try {
606                         //
607                         // Create a DOM parser
608                         //
609                         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
610                     dbf.setNamespaceAware(true);
611                     DocumentBuilder db = dbf.newDocumentBuilder();
612                     //
613                     // Parse the policy file
614                     //
615                     Document doc = db.parse(is);
616                     Element e = doc.getDocumentElement();
617                         //
618                         // Is it a 3.0 policy?
619                         //
620                         if ("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17".equals(e.getNamespaceURI())) {
621                                 //
622                                 // A policyset or policy could be the root
623                                 //
624                                 if (e.getNodeName().endsWith("Policy")) {
625                                         //
626                                         // Now we can create the context for the policy set
627                                         // and unmarshall the policy into a class.
628                                         //
629                                         JAXBContext context = JAXBContext.newInstance(PolicyType.class);
630                                         Unmarshaller um = context.createUnmarshaller();
631                                         JAXBElement<PolicyType> root = um.unmarshal(e, PolicyType.class);
632                                         //
633                                         // Here is our policy set class
634                                         //
635                                         return root.getValue();
636                                 } else if (e.getNodeName().endsWith("PolicySet")) {
637                                         //
638                                         // Now we can create the context for the policy set
639                                         // and unmarshall the policy into a class.
640                                         //
641                                         JAXBContext context = JAXBContext.newInstance(PolicySetType.class);
642                                         Unmarshaller um = context.createUnmarshaller();
643                                         JAXBElement<PolicySetType> root = um.unmarshal(e, PolicySetType.class);
644                                         //
645                                         // Here is our policy set class
646                                         //
647                                         return root.getValue();
648                                 } else {
649                                         if (logger.isDebugEnabled()) {
650                                                 logger.debug("Not supported yet: " + e.getNodeName());
651                                         }
652                                 }
653                         } else {
654                                 logger.warn("unsupported namespace: " + e.getNamespaceURI());
655                         }
656                 } catch (Exception e) {
657                         PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPolicyScanner", "Exception in readPolicy");
658                 }
659                 return null;
660         }
661
662         /**
663          * @return the policyObject
664          */
665         public Object getPolicyObject() {
666                 return policyObject;
667         }
668 }