2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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=========================================================
21 package org.onap.policy.components;
24 import java.io.ByteArrayOutputStream;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.PrintWriter;
29 import java.io.StringWriter;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.Collection;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
38 import javax.xml.bind.JAXBElement;
40 import org.apache.commons.io.FilenameUtils;
41 import org.json.JSONObject;
42 import org.onap.policy.common.logging.flexlogger.FlexLogger;
43 import org.onap.policy.common.logging.flexlogger.Logger;
44 import org.onap.policy.controller.PolicyController;
45 import org.onap.policy.rest.jpa.FunctionDefinition;
46 import org.onap.policy.utils.XACMLPolicyWriterWithPapNotify;
47 import org.onap.policy.xacml.api.XACMLErrorConstants;
48 import org.onap.policy.xacml.util.XACMLPolicyScanner;
50 import com.att.research.xacml.api.AttributeValue;
51 import com.att.research.xacml.std.IdentifierImpl;
52 import com.att.research.xacml.std.StdAttribute;
53 import com.att.research.xacml.std.StdAttributeValue;
54 import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult;
55 import com.att.research.xacml.util.XACMLPolicyScanner.SimpleCallback;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeSelectorType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
77 public class HumanPolicyComponent{
79 private static final Logger LOGGER = FlexLogger.getLogger(HumanPolicyComponent.class);
81 // Constants Used in XML Creation
82 public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject";
83 public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource";
84 public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action";
85 public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject";
86 public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id";
87 public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id";
88 public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id";
89 public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only";
90 public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only";
91 public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal";
92 public static final String FUNCTION_STRING_REGEX_MATCH = "org.onap.function.regex-match";
93 public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case";
94 public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer";
95 public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean";
96 public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string";
97 public static final String URI_DATATYPE = "http://www.w3.org/2001/XMLSchema#anyURI";
98 public static final String RULE_VARIABLE = "var:";
99 public static final String EMPTY_STRING = "";
101 private static HtmlProcessor htmlProcessor;
103 private static File policyFile;
105 private HumanPolicyComponent(){
106 //Default Constructor
109 public static JSONObject DescribePolicy(final File policyFile) {
110 if (LOGGER.isTraceEnabled())
111 LOGGER.trace("ENTER");
113 HumanPolicyComponent.policyFile = policyFile;
114 return humanPolicyLayout();
118 private static JSONObject humanPolicyLayout() {
119 if (LOGGER.isTraceEnabled())
120 LOGGER.trace("ENTER");
123 String html = processPolicy();
124 JSONObject result = new JSONObject();
125 result.put("html", html);
128 } catch (IllegalArgumentException e) {
129 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "cannot build html area por policy", e);
134 private static String processPolicy() {
135 if (LOGGER.isTraceEnabled())
136 LOGGER.trace("ENTER");
138 FileInputStream pIS = null;
140 pIS = new FileInputStream(policyFile);
141 Object policy = XACMLPolicyScanner.readPolicy(pIS);
143 throw new IllegalArgumentException("Policy File " + policyFile.getName() +
144 " cannot be unmarshalled");
146 HumanPolicyComponent.htmlProcessor =
147 new HtmlProcessor(HumanPolicyComponent.policyFile, policy);
149 Path policyPath = Paths.get(policyFile.getAbsolutePath());
150 XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor);
152 String html = htmlProcessor.html();
153 if (LOGGER.isDebugEnabled())
154 LOGGER.debug(policyPath + System.lineSeparator() + html);
158 } catch (Exception e) {
159 String msg = "Exception reading policy: " + policyFile.getAbsolutePath() +
160 ": " + e.getMessage();
161 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + msg, e);
162 throw new IllegalArgumentException(msg);
167 } catch (IOException e) {
168 LOGGER.warn(e.getMessage(), e);
176 class HtmlProcessor extends SimpleCallback {
178 private static final Logger LOGGER = FlexLogger.getLogger(HtmlProcessor.class);
180 private static Map<String, String> function2human;
182 function2human = new HashMap<>();
183 function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal");
184 function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL_IGNORE, "equal");
185 function2human.put(HumanPolicyComponent.FUNCTION_STRING_ONE_AND_ONLY, "one-and-only");
186 function2human.put(HumanPolicyComponent.FUNCTION_STRING_REGEX_MATCH, "matching regular expression");
187 function2human.put(HumanPolicyComponent.FUNTION_INTEGER_ONE_AND_ONLY, "one-and-only");
190 private static Map<String, String> combiningAlgo2human;
192 combiningAlgo2human = new HashMap<>();
193 combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to <i>deny</i>");
194 combiningAlgo2human.put("permit-overrides", "to permit if any $placeholder$ below evaluates to <i>permit</i>");
196 combiningAlgo2human.put("ordered-deny-overrides", "to deny if any $placeholder$ below evaluates to <i>deny</i>");
197 combiningAlgo2human.put("ordered-permit-overrides", "to permit if any $placeholder$ below evaluates to <i>permit</i>");
198 combiningAlgo2human.put("deny-unless-permit", "to permit if any $placeholder$ below evaluates to <i>deny</i> and not <i>indeterminate</i>");
200 combiningAlgo2human.put("permit-unless-deny", "to deny if any $placeholder$ below evaluates to is <i>permit</i> and not <i>indeterminate</i>");
201 combiningAlgo2human.put("first-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order");
202 combiningAlgo2human.put("only-one-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order");
205 private Map<String, AttributeIdentifiers> attributeIdentifiersMap = new HashMap<>();
207 private final StringWriter stringWriter = new StringWriter();
208 private final PrintWriter htmlOut = new PrintWriter(stringWriter);
209 private final String policyName;
210 private final Object rootPolicyObject;
212 public HtmlProcessor(File policyFile, Object policyObject) {
213 if (LOGGER.isTraceEnabled())
214 LOGGER.trace("ENTER");
216 if (policyFile == null) {
217 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File");
218 throw new IllegalArgumentException("Null Policy File");
221 if (!policyFile.exists() || !policyFile.canRead()) {
222 String msg = "Can't access " + policyFile.getAbsolutePath();
223 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + msg);
224 throw new IllegalArgumentException(msg);
227 if (policyObject == null ||
228 (!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) {
229 String msg = "Invalid unmarshalled object: " + policyObject;
230 LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + msg);
231 throw new IllegalArgumentException(msg);
234 this.policyName = FilenameUtils.removeExtension(policyFile.getName());
235 this.rootPolicyObject = policyObject;
237 String version = "-";
238 if (policyObject instanceof PolicyType) {
239 PolicyType policy = (PolicyType) policyObject;
240 version = policy.getVersion();
241 htmlOut.println("<h1>Policy: " + policyName +
242 " (version " + version + ") </h1>");
245 PolicySetType policySet = (PolicySetType) policyObject;
246 version = policySet.getVersion();
247 htmlOut.println("<h1>Policy Set: " + policyName +
248 " (v" + version + ") </h1>");
251 htmlOut.println("<h3><b>Location: </b>" + policyFile.getPath() + "</h3>");
252 htmlOut.println("<hr>");
254 if (rootPolicyObject instanceof PolicySetType) {
255 if (policyName.startsWith("Config_")) {
256 htmlOut.println("<p>This is a <b>config</b> policy set.</p>");
257 } else if (policyName.startsWith("Action_")) {
258 htmlOut.println("<p>This is an <b>action</b> policy set.</p>");
260 htmlOut.println("<dl>");
262 if (policyName.startsWith("Config_")) {
263 htmlOut.println("<p>This is a <b>config</b> policy.</p>");
264 } else if (policyName.startsWith("Action_")) {
265 htmlOut.println("<p>This is an <b>action</b> policy.</p>");
267 htmlOut.println("<ol>");
272 * @return the attributeIdentifiersMap
274 public Map<String, AttributeIdentifiers> getAttributeIdentifiersMap() {
275 return attributeIdentifiersMap;
279 public void onFinishScan(Object root) {
280 if (LOGGER.isTraceEnabled())
281 LOGGER.trace("ENTER");
283 if (rootPolicyObject instanceof PolicySetType) {
284 htmlOut.println("</dl>");
286 htmlOut.println("</ol>");
289 htmlOut.println("<hr>");
291 htmlOut.println("<h3>Attribute Table:</h3>");
293 htmlOut.println("<table border=\"3\" style=\"width:100%\">");
294 htmlOut.println("<tr>");
295 htmlOut.print("<th>Category</th>");
296 htmlOut.print("<th>Type</th>");
297 htmlOut.print("<th>Identifier</th>");
298 htmlOut.println("</tr>");
299 for(Map.Entry<String, AttributeIdentifiers> entry : this.attributeIdentifiersMap.entrySet()){
300 AttributeIdentifiers value = entry.getValue();
301 htmlOut.println("<tr>");
302 htmlOut.print("<td><a name=\"" + entry.getKey() + "\"></a>" + value.category + "</td>");
303 htmlOut.print("<td>" + value.getType() + "</td>");
304 htmlOut.print("<td>" + value.id + "</td>");
305 htmlOut.println("</tr>");
307 htmlOut.println("</table>");
309 htmlOut.println("<p></p>");
311 // Not necessary for the user, uncomment if desired at some point
314 super.onFinishScan(root);
317 @SuppressWarnings("unused")
318 private void writeRawXACML() {
319 if (LOGGER.isTraceEnabled())
320 LOGGER.trace("ENTER");
322 htmlOut.println("<hr>");
323 htmlOut.println("<h3>Raw XACML:</h3>");
325 ByteArrayOutputStream bos = new ByteArrayOutputStream();
326 if (rootPolicyObject instanceof PolicySetType) {
327 XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicySetType) rootPolicyObject);
328 } else if (rootPolicyObject instanceof PolicyType) {
329 XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicyType) rootPolicyObject);
332 String xacml = bos.toString();
333 xacml = xacml.replaceAll("<", "<");
334 xacml = xacml.replaceAll(">", ">");
335 htmlOut.println("<pre>");
336 htmlOut.println(xacml);
337 htmlOut.println("</pre>");
341 public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) {
342 if (LOGGER.isTraceEnabled())
343 LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion());
345 if (parent != null && LOGGER.isTraceEnabled())
346 LOGGER.trace("PolicySet: " + policySet.getPolicySetId() +
347 "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion());
349 String description = policySet.getDescription();
350 if (description != null && LOGGER.isTraceEnabled())
351 LOGGER.trace("PolicySet: " + policySet.getPolicySetId() +
352 " Description: " + policySet.getDescription());
354 if (parent == null) // root
355 policySet(policySet, "dl");
357 policySet(policySet, "li");
359 if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty())
360 htmlOut.println("<ol>");
362 return super.onPreVisitPolicySet(parent, policySet);
366 public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) {
367 if (LOGGER.isTraceEnabled())
368 LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion());
370 if (parent != null && LOGGER.isTraceEnabled())
371 LOGGER.trace("PolicySet: " + policySet.getPolicySetId() +
372 "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion());
374 String description = policySet.getDescription();
375 if (description != null && LOGGER.isTraceEnabled())
376 LOGGER.trace("PolicySet: " + policySet.getPolicySetId() +
377 " Description: " + policySet.getDescription());
379 if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty())
380 htmlOut.println("</ol>");
382 htmlOut.println("<p></p>");
384 return super.onPostVisitPolicySet(parent, policySet);
387 public void policySet(PolicySetType policySet, String htmlListElement) {
388 if (LOGGER.isTraceEnabled())
389 LOGGER.trace("PolicySet: " + policySet.getPolicySetId());
391 String combiningAlgorithm = "-";
393 String version = "-";
396 if (policySet.getPolicyCombiningAlgId() != null)
397 combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":");
399 if (policySet.getPolicySetId() != null)
400 id = extractLastIdentifier(policySet.getPolicySetId(), ":");
402 if (policySet.getVersion() != null)
403 version = policySet.getVersion();
406 htmlOut.println("<" + htmlListElement + "><b>Policy Set ID</b>: <i>" + id +
407 "</i> (v" + version + ") " + "</" + htmlListElement + ">");
409 if (policySet.getTarget() == null ||
410 policySet.getTarget().getAnyOf() == null ||
411 policySet.getTarget().getAnyOf().isEmpty()) {
412 htmlOut.println("<p>This policy set applies to all requests.</p>");
414 htmlOut.print("<p>");
415 htmlOut.print("This policy set applies to requests with attributes ");
417 List<AnyOfType> anyOf_s = policySet.getTarget().getAnyOf();
419 htmlOut.println(".</p>");
422 if (policySet.getPolicySetOrPolicyOrPolicySetIdReference() != null &&
423 !policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) {
424 String algoDesc = combiningAlgo2human.get(combiningAlgorithm);
425 if (algoDesc != null) {
426 algoDesc = algoDesc.replace("$placeholder$", "policy") + " (" + "<i>" + combiningAlgorithm + "</i>)";
428 algoDesc = combiningAlgorithm;
431 htmlOut.println("<p>The result is " + algoDesc + ": </p>");
436 public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) {
437 if (LOGGER.isTraceEnabled())
438 LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion());
440 if (parent != null && LOGGER.isTraceEnabled())
441 LOGGER.trace("PolicySet: " + policy.getPolicyId() +
442 "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion());
444 String description = policy.getDescription();
445 if (description != null && LOGGER.isTraceEnabled())
446 LOGGER.trace("PolicySet: " + policy.getPolicyId() +
447 " Description: " + policy.getDescription());
451 if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty())
452 htmlOut.println("<ol type=\"i\">");
454 return super.onPreVisitPolicy(parent, policy);
458 public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) {
459 if (LOGGER.isTraceEnabled())
460 LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion());
462 if (parent != null && LOGGER.isTraceEnabled())
463 LOGGER.trace("PolicySet: " + policy.getPolicyId() +
464 "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion());
466 if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty())
467 htmlOut.println("</ol>");
469 htmlOut.println("<p></p>");
470 return super.onPostVisitPolicy(parent, policy);
473 public void policy(PolicyType policy) {
474 if (LOGGER.isTraceEnabled())
475 LOGGER.trace("Policy: " + policy.getPolicyId());
477 String combiningAlgorithm = "-";
479 String version = "-";
482 if (policy.getRuleCombiningAlgId() != null)
483 combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":");
485 if (policy.getPolicyId() != null)
486 id = extractLastIdentifier(policy.getPolicyId(), ":");
488 if (policy.getVersion() != null)
489 version = policy.getVersion();
491 htmlOut.println("<li><b>Policy ID</b>: <i>" + id +
492 "</i> (v" + version + ") " + "</li>");
494 if (policy.getTarget() == null ||
495 policy.getTarget().getAnyOf() == null ||
496 policy.getTarget().getAnyOf().isEmpty()) {
497 htmlOut.println("<p>This policy applies to all requests.</p>");
499 htmlOut.print("<p>");
500 htmlOut.print("This policy applies to requests with attributes ");
502 List<AnyOfType> anyOf_s = policy.getTarget().getAnyOf();
504 htmlOut.println(".</p>");
507 if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() != null &&
508 !policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) {
509 String algoDesc = combiningAlgo2human.get(combiningAlgorithm);
510 if (algoDesc != null) {
511 algoDesc = algoDesc.replace("$placeholder$", "rule") + " (<i>" + combiningAlgorithm + "</i>)";
513 algoDesc = combiningAlgorithm;
515 htmlOut.println("<p>The result is " + algoDesc + ": </p>");
521 public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) {
522 if (LOGGER.isTraceEnabled())
523 LOGGER.trace("Rule: " + rule.getRuleId());
525 if (parent != null && LOGGER.isTraceEnabled())
526 LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion());
528 String description = rule.getDescription();
529 if (description != null && LOGGER.isTraceEnabled()) {
530 LOGGER.trace("Rule: " + rule.getRuleId() +
531 " Description: " + rule.getDescription());
536 return super.onPreVisitRule(parent, rule);
540 public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) {
541 if (LOGGER.isTraceEnabled())
542 LOGGER.trace("Rule: " + rule.getRuleId());
544 if (parent != null && LOGGER.isTraceEnabled())
545 LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion());
547 return super.onPostVisitRule(parent, rule);
550 public void rule(RuleType rule) {
551 if (LOGGER.isTraceEnabled())
552 LOGGER.trace("Rule: " + rule.getRuleId());
556 if (rule.getRuleId() != null)
557 id = extractLastIdentifier(rule.getRuleId(), ":");
559 htmlOut.println("<li><b>Rule ID</b>: <i>" + id + "</i></li>");
561 htmlOut.println("<dl>");
563 htmlOut.print("<p>");
564 htmlOut.print(rule.getEffect().value());
566 if (rule.getTarget() == null ||
567 rule.getTarget().getAnyOf() == null ||
568 rule.getTarget().getAnyOf().isEmpty()) {
569 htmlOut.print(" for all requests");
571 List<AnyOfType> anyOf_s = rule.getTarget().getAnyOf();
572 htmlOut.print(" for requests with attributes ");
576 if (rule.getCondition() != null) {
577 htmlOut.print(" when ");
578 htmlOut.println(this.stringifyCondition(rule.getCondition()) + " ");
580 htmlOut.print(" with no conditions ");
583 if (rule.getAdviceExpressions() != null) {
584 advice(rule.getAdviceExpressions());
585 if (rule.getObligationExpressions() != null)
586 htmlOut.println(" and ");
589 if (rule.getObligationExpressions() != null) {
590 obligation(rule.getObligationExpressions());
593 htmlOut.println("</p>");
596 private void advice(AdviceExpressionsType adviceExpressions) {
597 if (LOGGER.isTraceEnabled())
598 LOGGER.trace("ENTER");
600 List<AdviceExpressionType> ae = adviceExpressions.getAdviceExpression();
601 for (AdviceExpressionType expression : ae) {
602 htmlOut.println(" with <b>advice</b> (<i>" + expression.getAdviceId() + "</i>) on <i>" +
603 expression.getAppliesTo().value() + "</i>:" );
604 htmlOut.println("<ol type=\"a\">");
605 List<AttributeAssignmentExpressionType> assignments = expression.getAttributeAssignmentExpression();
606 if (assignments != null) {
607 processAttributeAssignments(assignments);
609 htmlOut.println("</ol>");
613 private void obligation(ObligationExpressionsType obligationExpressions) {
614 if (LOGGER.isTraceEnabled())
615 LOGGER.trace("ENTER");
617 List<ObligationExpressionType> oe = obligationExpressions.getObligationExpression();
618 for (ObligationExpressionType expression : oe) {
619 htmlOut.println(" with <b>obligations</b> (<i>" + expression.getObligationId() + "</i>) to be fullfilled on <i>" +
620 expression.getFulfillOn().value() + "</i>:" );
621 htmlOut.println("<ol type=\"a\">");
622 List<AttributeAssignmentExpressionType> assignments = expression.getAttributeAssignmentExpression();
623 if (assignments != null) {
624 processAttributeAssignments(assignments);
626 htmlOut.println("</ol>");
633 private void processAttributeAssignments(List<AttributeAssignmentExpressionType> assignments) {
634 if (LOGGER.isTraceEnabled())
635 LOGGER.trace("ENTER");
637 for (AttributeAssignmentExpressionType assignment : assignments) {
638 String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") +
639 ":" + extractLastIdentifier(assignment.getAttributeId(), ":");
640 AttributeIdentifiers attributeIdentifiers = null;
641 if (!this.attributeIdentifiersMap.containsKey(succintIdentifier)) {
642 // Note Attribute Assignments do not have an Attribute Type, assume string
643 // but note this case is unlikely since attributeMap should have been populated
644 // during parsing of target and conditions, and not in this case for Advice and
646 attributeIdentifiers = new AttributeIdentifiers(assignment.getCategory(),
648 assignment.getAttributeId());
649 this.attributeIdentifiersMap.put(succintIdentifier, attributeIdentifiers);
652 htmlOut.print("<li><i><a href=\"#" + succintIdentifier + "\">" + succintIdentifier + "</a></i> is ");
653 // AttributeValueType
654 JAXBElement<?> jaxbExp = assignment.getExpression();
655 Object assignmentObject = jaxbExp.getValue();
656 if (assignmentObject instanceof AttributeValueType) {
657 AttributeValueType avt = (AttributeValueType) assignmentObject;
658 if (attributeIdentifiers != null) {
659 attributeIdentifiers.setType(avt.getDataType());
661 int numContent = avt.getContent().size();
662 int countContent = 0;
663 for (Object c: avt.getContent()) {
665 htmlOut.print("<i>" + c + "</i>");
666 if (countContent < numContent)
667 htmlOut.print(" or ");
669 htmlOut.println("</li>");
670 } else if (assignmentObject instanceof AttributeDesignatorType) {
671 htmlOut.println("NA");
672 } else if (assignmentObject instanceof AttributeSelectorType) {
673 htmlOut.println("NA");
674 } else if (assignmentObject instanceof ApplyType) {
675 htmlOut.println("NA");
677 htmlOut.println("Unexpected");
686 public void target(List<AnyOfType> anyOfList) {
687 if (LOGGER.isTraceEnabled())
688 LOGGER.trace("ENTER");
690 if (anyOfList != null) {
691 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
692 String targetInHuman = "";
693 while (iterAnyOf.hasNext()) {
694 AnyOfType anyOf = iterAnyOf.next();
695 List<AllOfType> allOfList = anyOf.getAllOf();
696 if (allOfList != null) {
697 Iterator<AllOfType> iterAllOf = allOfList.iterator();
698 while (iterAllOf.hasNext()) {
699 AllOfType allOf = iterAllOf.next();
700 List<MatchType> matchList = allOf.getMatch();
701 if (matchList != null) {
702 Iterator<MatchType> iterMatch = matchList.iterator();
703 if (matchList.size() > 1)
704 targetInHuman += "(";
705 while (iterMatch.hasNext()) {
706 MatchType match = iterMatch.next();
708 // Finally down to the actual attribute
710 StdAttribute attribute = null;
711 AttributeValueType value = match.getAttributeValue();
712 String attributeDataType;
713 if (match.getAttributeDesignator() != null && value != null) {
714 AttributeDesignatorType designator = match.getAttributeDesignator();
715 attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()),
716 new IdentifierImpl(designator.getAttributeId()),
717 new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()),
718 designator.getIssuer(),
720 attributeDataType = designator.getDataType();
721 } else if (match.getAttributeSelector() != null && value != null) {
722 AttributeSelectorType selector = match.getAttributeSelector();
723 attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()),
724 new IdentifierImpl(selector.getContextSelectorId()),
725 new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()),
728 attributeDataType = selector.getDataType();
730 LOGGER.warn("NULL designator/selector or value for match.");
731 attributeDataType = "NA";
734 String functionName = getHumanFunction(match.getMatchId());
735 if(attribute != null){
736 String succintIdentifier = extractLastIdentifier(attribute.getCategory().stringValue(), ":") +
737 ":" + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":");
738 AttributeIdentifiers ai = new AttributeIdentifiers(attribute.getCategory().stringValue(),
740 attribute.getAttributeId().stringValue());
741 this.attributeIdentifiersMap.put(succintIdentifier,ai);
743 targetInHuman += "<i><a href=\"#" + succintIdentifier + "\">" + succintIdentifier + "</a></i> " + functionName + " ";
745 int numAttributes = attribute.getValues().size();
747 for (AttributeValue<?> v: attribute.getValues()) {
749 if (v.getValue() instanceof Collection<?>) {
750 Collection<?> value_s = (Collection<?>) v.getValue();
751 int numValues = value_s.size();
753 for (Object o : value_s) {
755 targetInHuman += " <I>" + o + "</I>";
756 if (countValues < numValues) {
757 targetInHuman += ", or";
761 targetInHuman += " <I>" + v.getValue() + "</I>";
762 if (count < numAttributes) {
763 targetInHuman += ", or ";
769 if (iterMatch.hasNext()) {
770 targetInHuman += " and ";
773 if (matchList.size() > 1) {
774 targetInHuman += ")";
777 if (iterAllOf.hasNext()) {
778 targetInHuman += " or ";
782 if (iterAnyOf.hasNext()) {
783 targetInHuman = "(" + targetInHuman + ")" + " or ";
785 if (anyOfList.size() > 1) {
786 targetInHuman += ")";
790 htmlOut.println(targetInHuman);
794 private String getHumanFunction(String matchId) {
795 if (HtmlProcessor.function2human.containsKey(matchId)) {
796 return HtmlProcessor.function2human.get(matchId);
799 FunctionDefinition function = PolicyController.getFunctionIDMap().get(matchId);
800 String functionName = function.getShortname();
802 if (LOGGER.isDebugEnabled()) {
803 LOGGER.debug(functionName +
804 ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]");
807 return extractLastIdentifier(removePrimitives(functionName), ":");
810 public String html() {
811 this.htmlOut.flush();
812 return this.stringWriter.toString();
815 private String extractLastIdentifier(String in, String separator) {
816 int lastIndex = in.lastIndexOf(separator);
820 return in.substring(lastIndex+1);
823 private String removePrimitives(String in) {
825 newIn = newIn.replace("string-", "");
826 newIn = newIn.replace("integer-", "");
827 newIn = newIn.replace("double-", "");
828 newIn = newIn.replace("boolean-", "");
832 private String stringifyCondition(ConditionType condition) {
833 if (condition.getExpression() == null) {
837 return stringifyExpression(condition.getExpression().getValue());
840 private String stringifyExpression(Object expression) {
841 if (expression instanceof ApplyType) {
842 ApplyType apply = (ApplyType) expression;
843 FunctionDefinition function = PolicyController.getFunctionIDMap().get(apply.getFunctionId());
844 String functionName = function.getShortname();
846 if (LOGGER.isDebugEnabled()) {
847 LOGGER.debug(functionName +
848 ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]");
851 if (functionName.contains("one-and-only")) {
852 if (LOGGER.isDebugEnabled()) {
853 LOGGER.debug("one-and-only found: " + functionName);
856 List<JAXBElement<?>> exps = apply.getExpression();
857 if (exps == null || exps.isEmpty())
860 String forResult = "";
861 for (JAXBElement<?> e : exps) {
862 Object v = e.getValue();
863 if (LOGGER.isDebugEnabled()) {
864 LOGGER.debug("one-and-only children: " + v);
867 forResult += stringifyExpression(v);
874 final int numExpr = (apply.getExpression() == null) ? -1 : apply.getExpression().size();
876 if (LOGGER.isDebugEnabled()) {
877 LOGGER.debug(functionName + " 0 expressions: " + numExpr);
880 } else if (numExpr == 1) {
882 if (LOGGER.isDebugEnabled()) {
883 LOGGER.debug(functionName + " 1 expression: " + numExpr);
885 String applySubresult = "";
886 for (JAXBElement<?> e : apply.getExpression()) {
887 Object v = e.getValue();
889 applySubresult += this.stringifyExpression(e.getValue());
892 return " " + removePrimitives(functionName) + " (" + applySubresult + ")";
895 if (LOGGER.isDebugEnabled()) {
896 LOGGER.debug(functionName + " > 1 expressions: " + numExpr);
898 String applySubresult = "";
900 for (JAXBElement<?> e : apply.getExpression()) {
902 Object ev = e.getValue();
904 if (ev instanceof ApplyType) {
905 if (((ApplyType) ev).getFunctionId().contains("one-and-only")) {
906 applySubresult += this.stringifyExpression(e.getValue());
908 applySubresult += "(" + this.stringifyExpression(e.getValue()) + ")";
911 applySubresult += this.stringifyExpression(e.getValue());
914 if (exprCount < numExpr) {
915 applySubresult += " " + removePrimitives(functionName) + " ";
919 return applySubresult;
922 if (expression instanceof AttributeDesignatorType) {
923 AttributeDesignatorType adt = (AttributeDesignatorType) expression;
925 String succintIdentifier = extractLastIdentifier(adt.getCategory(), ":") +
926 ":" + extractLastIdentifier(adt.getAttributeId(), ":");
927 AttributeIdentifiers ai = new AttributeIdentifiers(adt.getCategory(),
929 adt.getAttributeId());
930 this.attributeIdentifiersMap.put(succintIdentifier,ai);
932 return "<a href=\"#" + succintIdentifier + "\">" + succintIdentifier + "</a>";
934 if (expression instanceof AttributeSelectorType) {
935 AttributeSelectorType ast = (AttributeSelectorType) expression;
937 String attrName = ast.getPath();
938 if (attrName == null || (attrName.length() == 0)) {
942 String textSelector = "/text()";
943 if (attrName.endsWith(textSelector)) {
944 attrName = attrName.substring(0, attrName.length() - textSelector.length());
947 attrName = extractLastIdentifier(attrName, "/");
948 attrName = extractLastIdentifier(attrName, ":");
949 return " " + attrName;
951 if (expression instanceof AttributeValueType) {
952 AttributeValueType avt = (AttributeValueType) expression;
953 List<Object> content = avt.getContent();
955 for (Object o: content) {
956 value_s += " " + o.toString();
958 return " " + value_s;
960 if (expression instanceof VariableReferenceType) {
962 // Really unknown - the variable may or may not have been defined
964 return " VARIABLEREF-NOT-HANDLED";
966 throw new IllegalArgumentException("Unexpected input expression");
972 class AttributeIdentifiers {
973 public final String category;
975 public final String id;
977 public AttributeIdentifiers(String category, String type, String id) {
978 this.category = category;
983 public String getType() {
987 public void setType(String type) {