aboutsummaryrefslogtreecommitdiffstats
path: root/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java
blob: 2083e69db80d389f731d4569d74b1f1361e3c493 (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
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.xacml.pdp.application.guard;

import com.att.research.xacml.api.DataTypeException;
import com.att.research.xacml.api.Decision;
import com.att.research.xacml.api.Identifier;
import com.att.research.xacml.api.Request;
import com.att.research.xacml.api.Response;
import com.att.research.xacml.api.Result;
import com.att.research.xacml.api.XACML3;
import com.att.research.xacml.std.IdentifierImpl;
import com.att.research.xacml.std.annotations.RequestParser;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.util.Collection;
import java.util.Map;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
import org.onap.policy.models.decisions.concepts.DecisionResponse;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
import org.onap.policy.pdp.xacml.application.common.operationshistory.CountRecentOperationsPip;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GuardTranslator implements ToscaPolicyTranslator {
    private static final Logger LOGGER = LoggerFactory.getLogger(GuardTranslator.class);

    //
    // common guard property fields
    //
    public static final String FIELD_ACTOR = "actor";
    public static final String FIELD_OPERATION = "operation";
    public static final String FIELD_CONTROLLOOP = "id";
    public static final String FIELD_TIMERANGE = "timeRange";

    //
    // frequency property fields
    //
    public static final String FIELD_TIMEWINDOW = "timeWindow";
    public static final String FIELD_TIMEUNITS = "timeUnits";
    public static final String FIELD_LIMIT = "limit";

    //
    // minmax property fields
    //
    public static final String FIELD_TARGET = "target";
    public static final String FIELD_MIN = "min";
    public static final String FIELD_MAX = "max";

    //
    // blacklist property fields
    //
    public static final String FIELD_BLACKLIST = "blacklist";

    //
    // filter property fields
    //
    public static final String FIELD_FILTER_WHITELIST = "whitelist";
    public static final String FIELD_FILTER_ALGORITHM = "algorithm";
    public static final String FIELD_FILTER_FILTERS = "filters";
    public static final String FIELD_FILTER_FIELD = "field";
    public static final String FIELD_FILTER_FUNCTION = "function";
    public static final String FIELD_FILTER_FILTER = "filter";
    public static final String FIELD_FILTER_BLACKLIST = "blacklist";

    public static final String POLICYTYPE_FREQUENCY = "onap.policies.controlloop.guard.common.FrequencyLimiter";
    public static final String POLICYTYPE_MINMAX = "onap.policies.controlloop.guard.common.MinMax";
    public static final String POLICYTYPE_BLACKLIST = "onap.policies.controlloop.guard.common.Blacklist";
    public static final String POLICYTYPE_FILTER = "onap.policies.controlloop.guard.common.Filter";

    //
    // Variable definitions
    //
    private static final String VARIABLE_TIMEINRANGE = "timeInRange";

    public GuardTranslator() {
        super();
    }

    /**
     * Convert the policy.
     */
    @Override
    public Object convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
        //
        // Policy name should be at the root
        //
        String policyName = toscaPolicy.getMetadata().get("policy-id");
        //
        // Set it as the policy ID
        //
        PolicyType newPolicyType = new PolicyType();
        newPolicyType.setPolicyId(policyName);
        //
        // Optional description
        //
        newPolicyType.setDescription(toscaPolicy.getDescription());
        //
        // There should be a metadata section
        //
        this.fillMetadataSection(newPolicyType, toscaPolicy.getMetadata());
        //
        // There should be properties metadata section
        //
        if (toscaPolicy.getProperties() == null) {
            throw new ToscaPolicyConversionException("no properties specified on guard policy: " + policyName);
        }
        //
        // Generate the TargetType - add true if not blacklist
        //
        newPolicyType.setTarget(this.generateTargetType(toscaPolicy.getProperties(),
                ! POLICYTYPE_BLACKLIST.equals(toscaPolicy.getType())));
        //
        // Add specific's per guard policy type
        //
        if (POLICYTYPE_FREQUENCY.equals(toscaPolicy.getType())) {
            newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_DENY_UNLESS_PERMIT.stringValue());
            generateFrequencyRules(toscaPolicy, policyName, newPolicyType);
        } else if (POLICYTYPE_MINMAX.equals(toscaPolicy.getType())) {
            newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_DENY_UNLESS_PERMIT.stringValue());
            generateMinMaxRules(toscaPolicy, policyName, newPolicyType);
        } else if (POLICYTYPE_BLACKLIST.equals(toscaPolicy.getType())) {
            newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_PERMIT_UNLESS_DENY.stringValue());
            generateBlacklistRules(toscaPolicy, policyName, newPolicyType);
        } else if (POLICYTYPE_FILTER.equals(toscaPolicy.getType())) {
            newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_PERMIT_UNLESS_DENY.stringValue());
            generateFilterRules(toscaPolicy, policyName, newPolicyType);
        } else {
            throw new ToscaPolicyConversionException("Unknown guard policy type " + toscaPolicy.getType());
        }
        //
        // Add in our variable definition
        //
        Object timeRange = toscaPolicy.getProperties().get(FIELD_TIMERANGE);
        if (timeRange != null) {
            VariableReferenceType variable = this.createTimeRangeVariable(timeRange, newPolicyType);
            //
            // Update all the rules to have conditions for this variable
            //
            this.addVariableToConditionTypes(variable, newPolicyType);
        }
        return newPolicyType;
    }

    /**
     * This method iterates through all the existing rules, adding in a conditionType that will test
     * whether the Variable is true or false. Any existing ConditionType will be updated to AND with the
     * Variable.
     *
     * @param variable VariableDefinitionType to add
     * @param newPolicyType PolicyType that will be updated
     */
    protected void addVariableToConditionTypes(VariableReferenceType variable,
            PolicyType newPolicyType) {
        //
        // Iterate through the rules
        //
        for (Object objectType : newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
            if (objectType instanceof RuleType) {
                RuleType rule = (RuleType) objectType;
                if (rule.getCondition() == null) {
                    //
                    // No condition already, just create and add a new one
                    //
                    ConditionType condition = new ConditionType();
                    condition.setExpression(new ObjectFactory().createVariableReference(variable));
                    rule.setCondition(condition);
                } else {
                    //
                    // Need to create a new ConditionType that treats all the expressions as an AND
                    // with the Variable.
                    //
                    rule.setCondition(ToscaPolicyTranslatorUtils.addVariableToCondition(rule.getCondition(), variable,
                            XACML3.ID_FUNCTION_AND));
                }
            }
        }
    }

    /**
     * Convert Request.
     */
    @Override
    public Request convertRequest(DecisionRequest request) throws ToscaPolicyConversionException {
        LOGGER.info("Converting Request {}", request);
        try {
            return RequestParser.parseRequest(GuardPolicyRequest.createInstance(request));
        } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) {
            throw new ToscaPolicyConversionException("Failed to convert DecisionRequest", e);
        }
    }

    /**
     * Convert response.
     */
    @Override
    public DecisionResponse convertResponse(Response xacmlResponse) {
        LOGGER.info("Converting Response {}", xacmlResponse);
        DecisionResponse decisionResponse = new DecisionResponse();
        //
        // Iterate through all the results
        //
        for (Result xacmlResult : xacmlResponse.getResults()) {
            //
            // Check the result
            //
            if (xacmlResult.getDecision() == Decision.PERMIT) {
                //
                // Just simply return a Permit response
                //
                decisionResponse.setStatus(Decision.PERMIT.toString());
            } else if (xacmlResult.getDecision() == Decision.DENY) {
                //
                // Just simply return a Deny response
                //
                decisionResponse.setStatus(Decision.DENY.toString());
            } else {
                //
                // There is no guard policy, so we return a permit
                //
                decisionResponse.setStatus(Decision.PERMIT.toString());
            }
        }

        return decisionResponse;
    }

    /**
     * From the TOSCA metadata section, pull in values that are needed into the XACML policy.
     *
     * @param policy Policy Object to store the metadata
     * @param map The Metadata TOSCA Map
     * @return Same Policy Object
     */
    protected PolicyType fillMetadataSection(PolicyType policy, Map<String, String> map) {
        //
        // NOTE: The models code ensures the metadata section ALWAYS exists
        //
        //
        // Add in the Policy Version
        //
        policy.setVersion(map.get("policy-version"));
        return policy;
    }

    /**
     * Generate the targettype for the policy. Optional to add MatchType for the target. eg. the
     * blacklist policy type uses the target in a different manner.
     *
     * @param properties TOSCA properties object
     * @param addTargets true to go ahead and add target to the match list.
     * @return TargetType object
     * @throws ToscaPolicyConversionException if there is a missing property
     */
    protected TargetType generateTargetType(Map<String, Object> properties, boolean addTargets)
            throws ToscaPolicyConversionException {
        //
        // Go through potential properties
        //
        AllOfType allOf = new AllOfType();
        if (properties.containsKey(FIELD_ACTOR)) {
            addMatch(allOf, properties.get(FIELD_ACTOR), ToscaDictionary.ID_RESOURCE_GUARD_ACTOR);
        }
        if (properties.containsKey(FIELD_OPERATION)) {
            addMatch(allOf, properties.get(FIELD_OPERATION), ToscaDictionary.ID_RESOURCE_GUARD_RECIPE);
        }
        if (addTargets && properties.containsKey(FIELD_TARGET)) {
            addMatch(allOf, properties.get(FIELD_TARGET), ToscaDictionary.ID_RESOURCE_GUARD_TARGETID);
        }
        if (properties.containsKey(FIELD_CONTROLLOOP)) {
            addMatch(allOf, properties.get(FIELD_CONTROLLOOP), ToscaDictionary.ID_RESOURCE_GUARD_CLNAME);
        }
        //
        // Create target
        //
        TargetType target = new TargetType();
        AnyOfType anyOf = new AnyOfType();
        anyOf.getAllOf().add(allOf);
        target.getAnyOf().add(anyOf);
        return target;
    }

    @SuppressWarnings("unchecked")
    protected AllOfType addMatch(AllOfType allOf, Object value, Identifier attributeId) {
        if (value instanceof String) {
            if (".*".equals(value.toString())) {
                //
                // There's no point to even have a match
                //
                return allOf;
            } else {
                //
                // Exact match
                //
                MatchType match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
                    XACML3.ID_FUNCTION_STRING_EQUAL,
                    value,
                    XACML3.ID_DATATYPE_STRING,
                    attributeId,
                    XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);

                allOf.getMatch().add(match);
            }
            return allOf;
        }
        if (value instanceof Collection) {
            ((Collection<String>) value).forEach(val -> {
                MatchType match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
                        XACML3.ID_FUNCTION_STRING_EQUAL,
                        val,
                        XACML3.ID_DATATYPE_STRING,
                        attributeId,
                        XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);

                allOf.getMatch().add(match);
            });
        }
        return allOf;
    }

    @SuppressWarnings("rawtypes")
    protected void addTimeRangeMatch(AllOfType allOf, Object timeRange)
            throws ToscaPolicyConversionException {
        if (! (timeRange instanceof Map)) {
            throw new ToscaPolicyConversionException("timeRange is not a map object " + timeRange.getClass());
        }

        MatchType matchStart = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
                XACML3.ID_FUNCTION_TIME_GREATER_THAN_OR_EQUAL,
                ((Map) timeRange).get("start_time").toString(),
                XACML3.ID_DATATYPE_TIME,
                XACML3.ID_ENVIRONMENT_CURRENT_TIME,
                XACML3.ID_ATTRIBUTE_CATEGORY_ENVIRONMENT);

        allOf.getMatch().add(matchStart);

        MatchType matchEnd = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
                XACML3.ID_FUNCTION_TIME_LESS_THAN_OR_EQUAL,
                ((Map) timeRange).get("end_time").toString(),
                XACML3.ID_DATATYPE_TIME,
                XACML3.ID_ENVIRONMENT_CURRENT_TIME,
                XACML3.ID_ATTRIBUTE_CATEGORY_ENVIRONMENT);

        allOf.getMatch().add(matchEnd);
    }

    @SuppressWarnings("rawtypes")
    protected VariableReferenceType createTimeRangeVariable(Object timeRange, PolicyType newPolicyType)
            throws ToscaPolicyConversionException {
        //
        // Sanity check the properties
        //
        if (! (timeRange instanceof Map)) {
            throw new ToscaPolicyConversionException("timeRange is not a map object " + timeRange.getClass());
        }
        String startTimestamp;
        String endTimestamp;
        try {
            startTimestamp = ((Map) timeRange).get("start_time").toString();
            endTimestamp = ((Map) timeRange).get("end_time").toString();
            if (StringUtils.isBlank(startTimestamp)) {
                throw new ToscaPolicyConversionException("Missing timeRange start_time property");
            }
            if (StringUtils.isBlank(endTimestamp)) {
                throw new ToscaPolicyConversionException("Missing timeRange end_time property");
            }
        } catch (ToscaPolicyConversionException e) {
            throw e;
        } catch (Exception e) {
            throw new ToscaPolicyConversionException("Invalid timeRange", e);
        }
        //
        // Should also be parseable as an ISO8601 timestamp
        //
        Object startTimeObject = parseTimestamp(startTimestamp);
        Object endTimeObject = parseTimestamp(endTimestamp);
        //
        // They should be the same object types. We cannot establish a range
        // between an OffsetDateTime and an OffsetTime
        //
        if (! startTimeObject.getClass().equals(endTimeObject.getClass())) {
            throw new ToscaPolicyConversionException("start_time and end_time class types do not match");
        }
        //
        // Create the inner timeInRange ApplyType
        //
        ApplyType timeInRange = ToscaPolicyTranslatorUtils.generateTimeInRange(startTimestamp, endTimestamp, true);
        VariableDefinitionType variable = new VariableDefinitionType();
        variable.setVariableId(VARIABLE_TIMEINRANGE);
        variable.setExpression(new ObjectFactory().createApply(timeInRange));
        //
        // Add it to the policy
        //
        newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(variable);
        //
        // Create and return the reference to the variable
        //
        VariableReferenceType reference = new VariableReferenceType();
        reference.setVariableId(variable.getVariableId());
        return reference;
    }

    protected Object parseTimestamp(String string) throws ToscaPolicyConversionException {
        //
        // First see if it is a full datetime object
        //
        try {
            return OffsetDateTime.parse(string);
        } catch (Exception e) {
            LOGGER.warn("timestamp {} could not be parsed. This may not be an error.", string, e);
        }
        //
        // May only be a time object
        //
        try {
            return OffsetTime.parse(string);
        } catch (Exception e) {
            throw new ToscaPolicyConversionException("timestamp " + string + " could not be parsed ", e);
        }
    }

    protected void generateFrequencyRules(ToscaPolicy toscaPolicy, String policyName, PolicyType newPolicyType)
            throws ToscaPolicyConversionException {
        //
        // We must have the limit
        //
        if (! toscaPolicy.getProperties().containsKey(FIELD_LIMIT)) {
            throw new ToscaPolicyConversionException("Missing property limit");
        }
        //
        // See if its possible to generate a count
        //
        Integer limit = ToscaPolicyTranslatorUtils.parseInteger(
                toscaPolicy.getProperties().get(FIELD_LIMIT).toString());
        if (limit == null) {
            throw new ToscaPolicyConversionException("Missing limit value");
        }
        String timeWindow = null;
        if (toscaPolicy.getProperties().containsKey(FIELD_TIMEWINDOW)) {
            Integer intTimeWindow = ToscaPolicyTranslatorUtils.parseInteger(
                    toscaPolicy.getProperties().get(FIELD_TIMEWINDOW).toString());
            if (intTimeWindow == null) {
                throw new ToscaPolicyConversionException("timeWindow is not an integer");
            }
            timeWindow = intTimeWindow.toString();
        }
        String timeUnits = null;
        if (toscaPolicy.getProperties().containsKey(FIELD_TIMEUNITS)) {
            timeUnits = toscaPolicy.getProperties().get(FIELD_TIMEUNITS).toString();
        }
        //
        // Generate a count
        //
        final ApplyType countCheck = generateCountCheck(limit, timeWindow, timeUnits);
        //
        // Create our condition
        //
        final ConditionType condition = new ConditionType();
        condition.setExpression(new ObjectFactory().createApply(countCheck));

        //
        // Now we can create our rule
        //
        RuleType frequencyRule = new RuleType();
        frequencyRule.setDescription("Frequency limit permit rule");
        frequencyRule.setRuleId(policyName + ":frequency");
        frequencyRule.setEffect(EffectType.PERMIT);
        frequencyRule.setTarget(new TargetType());
        //
        // Add the condition
        //
        frequencyRule.setCondition(condition);
        //
        // Add the rule to the policy
        //
        newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(frequencyRule);
    }

    protected ApplyType generateCountCheck(Integer limit, String timeWindow, String timeUnits) {
        AttributeDesignatorType designator = new AttributeDesignatorType();
        designator.setAttributeId(ToscaDictionary.ID_RESOURCE_GUARD_OPERATIONCOUNT.stringValue());
        designator.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE.stringValue());
        designator.setDataType(XACML3.ID_DATATYPE_INTEGER.stringValue());
        //
        // Setup issuer - used by the operations PIP to determine
        // how to do the database query.
        //
        String issuer = ToscaDictionary.GUARD_ISSUER_PREFIX
            + CountRecentOperationsPip.ISSUER_NAME
            + ":tw:" + timeWindow + ":" + timeUnits;
        designator.setIssuer(issuer);

        AttributeValueType valueLimit = new AttributeValueType();
        valueLimit.setDataType(XACML3.ID_DATATYPE_INTEGER.stringValue());
        //
        // Yes really use toString(), the marshaller will
        // throw an exception if this is an integer object
        // and not a string.
        //
        valueLimit.getContent().add(limit.toString());

        ObjectFactory factory = new ObjectFactory();

        ApplyType applyOneAndOnly = new ApplyType();
        applyOneAndOnly.setDescription("Unbag the limit");
        applyOneAndOnly.setFunctionId(XACML3.ID_FUNCTION_INTEGER_ONE_AND_ONLY.stringValue());
        applyOneAndOnly.getExpression().add(factory.createAttributeDesignator(designator));

        ApplyType applyLessThan = new ApplyType();
        applyLessThan.setDescription("return true if current count is less than.");
        applyLessThan.setFunctionId(XACML3.ID_FUNCTION_INTEGER_LESS_THAN.stringValue());
        applyLessThan.getExpression().add(factory.createApply(applyOneAndOnly));
        applyLessThan.getExpression().add(factory.createAttributeValue(valueLimit));

        return applyLessThan;
    }

    protected void generateMinMaxRules(ToscaPolicy toscaPolicy, String policyName, PolicyType newPolicyType)
            throws ToscaPolicyConversionException {
        //
        // Add the target
        //
        if (! toscaPolicy.getProperties().containsKey(FIELD_TARGET)) {
            throw new ToscaPolicyConversionException("Missing target field in minmax policy");
        }
        MatchType matchTarget = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
                XACML3.ID_FUNCTION_STRING_EQUAL,
                toscaPolicy.getProperties().get(FIELD_TARGET).toString(),
                XACML3.ID_DATATYPE_STRING,
                ToscaDictionary.ID_RESOURCE_GUARD_TARGETID,
                XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
        //
        // For the min, if the # of instances is less than the minimum
        // then allow the scale.
        //
        Integer min = null;
        if (toscaPolicy.getProperties().containsKey(FIELD_MIN)) {
            min = ToscaPolicyTranslatorUtils.parseInteger(toscaPolicy.getProperties().get(FIELD_MIN).toString());
            MatchType matchMin = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
                    XACML3.ID_FUNCTION_INTEGER_GREATER_THAN,
                    min.toString(),
                    XACML3.ID_DATATYPE_INTEGER,
                    ToscaDictionary.ID_RESOURCE_GUARD_VFCOUNT,
                    XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);

            newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(
                    generateMinMaxRule(matchTarget, matchMin, policyName + ":minrule", "check minimum"));
        }
        Integer max = null;
        if (toscaPolicy.getProperties().containsKey(FIELD_MAX)) {
            max = ToscaPolicyTranslatorUtils.parseInteger(toscaPolicy.getProperties().get(FIELD_MAX).toString());
            MatchType matchMax = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
                    XACML3.ID_FUNCTION_INTEGER_GREATER_THAN,
                    max.toString(),
                    XACML3.ID_DATATYPE_INTEGER,
                    ToscaDictionary.ID_RESOURCE_GUARD_VFCOUNT,
                    XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);

            newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(
                    generateMinMaxRule(matchTarget, matchMax, policyName + ":maxrule", "check maximum"));
        }
        //
        // Do we have at least a min or max?
        //
        if (min == null && max == null) {
            throw new ToscaPolicyConversionException("Missing min or max field in minmax policy");
        }
    }

    protected RuleType generateMinMaxRule(MatchType matchTarget, MatchType matchMinOrMax, String ruleId, String desc) {
        AllOfType allOf = new AllOfType();
        allOf.getMatch().add(matchTarget);
        allOf.getMatch().add(matchMinOrMax);
        AnyOfType anyOf = new AnyOfType();
        anyOf.getAllOf().add(allOf);
        TargetType target = new TargetType();
        target.getAnyOf().add(anyOf);
        RuleType minMaxRule = new RuleType();
        minMaxRule.setEffect(EffectType.PERMIT);
        minMaxRule.setDescription(desc);
        minMaxRule.setRuleId(ruleId);
        minMaxRule.setTarget(target);
        return minMaxRule;
    }

    protected void generateBlacklistRules(ToscaPolicy toscaPolicy, String policyName, PolicyType newPolicyType)
            throws ToscaPolicyConversionException {
        //
        // Validate the blacklist exists
        //
        if (! toscaPolicy.getProperties().containsKey(FIELD_BLACKLIST)) {
            throw new ToscaPolicyConversionException("Missing blacklist field");
        }
        //
        // Get the blacklist, which should be an array or collection.
        //
        Object arrayBlacklisted = toscaPolicy.getProperties().get(FIELD_BLACKLIST);
        if (!(arrayBlacklisted instanceof Collection)) {
            throw new ToscaPolicyConversionException("Blacklist is not a collection");
        }
        //
        // Iterate the entries and create individual AnyOf so each entry is
        // treated as an OR.
        //
        TargetType target = new TargetType();
        AnyOfType anyOf = new AnyOfType();
        for (Object blacklisted : ((Collection<?>) arrayBlacklisted)) {
            AllOfType allOf = new AllOfType();
            this.addMatch(allOf, blacklisted, ToscaDictionary.ID_RESOURCE_GUARD_TARGETID);
            anyOf.getAllOf().add(allOf);
        }
        target.getAnyOf().add(anyOf);
        //
        // Create our rule and add the target
        //
        RuleType blacklistRule = new RuleType();
        blacklistRule.setEffect(EffectType.DENY);
        blacklistRule.setDescription("blacklist the entities");
        blacklistRule.setRuleId(policyName + ":blacklist");
        blacklistRule.setTarget(target);
        //
        // Add the rule to the policy
        //
        newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(blacklistRule);
    }

    @SuppressWarnings("unchecked")
    protected void generateFilterRules(ToscaPolicy toscaPolicy, String policyName, PolicyType newPolicyType)
            throws ToscaPolicyConversionException {
        //
        // Validate the algorithm
        //
        if (! toscaPolicy.getProperties().containsKey(FIELD_FILTER_ALGORITHM)) {
            throw new ToscaPolicyConversionException("Missing algorithm");
        }
        Object algorithm = toscaPolicy.getProperties().get(FIELD_FILTER_ALGORITHM);
        if ("whitelist-overrides".equals(algorithm.toString())) {
            newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue());
        } else if ("blacklist-overrides".equals(algorithm.toString())) {
            newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_DENY_OVERRIDES.stringValue());
        } else {
            throw new ToscaPolicyConversionException(
                    "Unexpected value for algorithm, should be whitelist-overrides or blacklist-overrides");
        }
        //
        // Validate the filters exist and have the right properties
        //
        if (! toscaPolicy.getProperties().containsKey(FIELD_FILTER_FILTERS)) {
            throw new ToscaPolicyConversionException("Missing filters");
        }
        //
        // Get the filters, which should be an array or collection.
        //
        Object arrayFilters = toscaPolicy.getProperties().get(FIELD_FILTER_FILTERS);
        if (!(arrayFilters instanceof Collection)) {
            throw new ToscaPolicyConversionException("Filters is not a collection");
        }
        //
        // Iterate the filters
        //
        int ruleId = 1;
        for (Object filterAttributes : ((Collection<?>) arrayFilters)) {
            if (!(filterAttributes instanceof Map)) {
                throw new ToscaPolicyConversionException("Filter should be a map");
            }
            //
            // All fields must be there
            //
            String field = validateFilterPropertyField((Map<String, Object>) filterAttributes);
            String filter = validateFilterPropertyFilter((Map<String, Object>) filterAttributes);
            Identifier function = validateFilterPropertyFunction((Map<String, Object>) filterAttributes);
            boolean isBlacklisted = validateFilterPropertyBlacklist((Map<String, Object>) filterAttributes);
            //
            // Create our filter rule
            //
            RuleType filterRule = createFilterRule(policyName + ":rule" + ruleId++, field, filter,
                    function, isBlacklisted);
            //
            // Add the rule to the policy
            //
            newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(filterRule);
        }
    }

    protected String validateFilterPropertyField(Map<String, Object> filterAttributes)
            throws ToscaPolicyConversionException {
        Object field = filterAttributes.get(FIELD_FILTER_FIELD);
        if (field != null) {
            switch (field.toString().toLowerCase()) {
                case "generic-vnf.vnf-name":
                case "generic-vnf.vnf-id":
                case "generic-vnf.vnf-type":
                case "generic-vnf.nf-naming-code":
                case "vserver.vserver-id":
                case "cloud-region.cloud-region-id":
                    return field.toString();
                default:
                    throw new ToscaPolicyConversionException("Unexpected value for field in filter");
            }
        }
        throw new ToscaPolicyConversionException("Missing \'field\' from filter");
    }

    protected String validateFilterPropertyFilter(Map<String, Object> filterAttributes)
            throws ToscaPolicyConversionException {
        Object filter = filterAttributes.get(FIELD_FILTER_FILTER);
        if (filter != null) {
            return filter.toString();
        }
        throw new ToscaPolicyConversionException("Missing \'filter\' from filter");
    }

    protected Identifier validateFilterPropertyFunction(Map<String, Object> filterAttributes)
            throws ToscaPolicyConversionException {
        Object function = filterAttributes.get(FIELD_FILTER_FUNCTION);
        if (function != null) {
            switch (function.toString().toLowerCase()) {
                case "string-equal":
                    return XACML3.ID_FUNCTION_STRING_EQUAL;
                case "string-equal-ignore-case":
                    return XACML3.ID_FUNCTION_STRING_EQUAL_IGNORE_CASE;
                case "string-regexp-match":
                    return XACML3.ID_FUNCTION_STRING_REGEXP_MATCH;
                case "string-contains":
                    return XACML3.ID_FUNCTION_STRING_CONTAINS;
                case "string-greater-than":
                    return XACML3.ID_FUNCTION_STRING_GREATER_THAN;
                case "string-greater-than-or-equal":
                    return XACML3.ID_FUNCTION_STRING_GREATER_THAN_OR_EQUAL;
                case "string-less-than":
                    return XACML3.ID_FUNCTION_STRING_LESS_THAN;
                case "string-less-than-or-equal":
                    return XACML3.ID_FUNCTION_STRING_LESS_THAN_OR_EQUAL;
                case "string-starts-with":
                    return XACML3.ID_FUNCTION_STRING_STARTS_WITH;
                case "string-ends-with":
                    return XACML3.ID_FUNCTION_STRING_ENDS_WITH;
                default:
                    throw new ToscaPolicyConversionException("Unexpected value for function in filter");
            }
        }
        throw new ToscaPolicyConversionException("Missing \'function\' from filter");
    }

    protected boolean validateFilterPropertyBlacklist(Map<String, Object> filterAttributes)
            throws ToscaPolicyConversionException {
        Object filter = filterAttributes.get(FIELD_FILTER_BLACKLIST);
        if (filter != null) {
            if ("true".equalsIgnoreCase(filter.toString())) {
                return true;
            }
            if ("false".equalsIgnoreCase(filter.toString())) {
                return false;
            }
            throw new ToscaPolicyConversionException("Unexpected value for blacklist in filter");
        }
        throw new ToscaPolicyConversionException("Missing \'blacklist\' from filter");
    }

    protected RuleType createFilterRule(String ruleId, String field, String filter, Identifier function,
            boolean isBlacklisted) {
        RuleType rule = new RuleType();
        rule.setRuleId(ruleId);

        //
        // Create the Match
        //
        MatchType matchFilter = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
                function,
                filter,
                XACML3.ID_DATATYPE_STRING,
                new IdentifierImpl(GuardPolicyRequest.PREFIX_RESOURCE_ATTRIBUTE_ID + field),
                XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE
                );
        AllOfType allOf = new AllOfType();
        allOf.getMatch().add(matchFilter);
        AnyOfType anyOf = new AnyOfType();
        anyOf.getAllOf().add(allOf);
        TargetType target = new TargetType();
        target.getAnyOf().add(anyOf);

        rule.setTarget(target);

        if (isBlacklisted) {
            rule.setEffect(EffectType.DENY);
        } else {
            rule.setEffect(EffectType.PERMIT);
        }
        return rule;
    }

}