aboutsummaryrefslogtreecommitdiffstats
path: root/applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTranslator.java
blob: 52f1ec0ab7aeddbfd4f4fcf9fdc492e6840b9b77 (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
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

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

import com.att.research.xacml.api.Advice;
import com.att.research.xacml.api.AttributeAssignment;
import com.att.research.xacml.api.Identifier;
import com.att.research.xacml.api.XACML3;
import com.att.research.xacml.util.XACMLPolicyWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
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 org.apache.commons.lang3.StringUtils;
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.ToscaPolicyTranslatorUtils;
import org.onap.policy.pdp.xacml.application.common.std.StdMatchableTranslator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OptimizationPdpApplicationTranslator extends StdMatchableTranslator {
    private static final Logger LOGGER = LoggerFactory.getLogger(OptimizationPdpApplicationTranslator.class);

    private static final String OPTIMIZATION_POLICYTYPE_SUBSCRIBER =
            "onap.policies.optimization.service.SubscriberPolicy";

    private static final String FIELD_SUBSCRIBER_ROLE = "subscriberRole";
    private static final String FIELD_PROV_STATUS = "provStatus";

    @SuppressWarnings("unchecked")
    @Override
    public Object convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
        //
        // Have our superclass do the work - NOTE we are assuming
        // that we are getting a PolicyType converted.
        //
        PolicyType policy = (PolicyType) super.convertPolicy(toscaPolicy);
        //
        // Check if this is the subscriber policy
        //
        if (OPTIMIZATION_POLICYTYPE_SUBSCRIBER.equals(toscaPolicy.getType())) {
            //
            // Ensure the policy has the subscriber properties
            //
            Map<String, Object> subscriberProperties = (Map<String, Object>) toscaPolicy.getProperties()
                    .get("subscriberProperties");
            if (subscriberProperties == null) {
                throw new ToscaPolicyConversionException("Missing subscriberProperties from subscriber policy");
            }
            //
            // Add subscriber name to the target so the policy
            // only matches for the given subscriberName.
            //
            addSubscriberNameIntoTarget(policy, subscriberProperties);
            //
            // Add subscriber advice
            //
            policy.setAdviceExpressions(generateSubscriberAdvice(subscriberProperties));
            //
            // Dump our revised policy out
            //
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                XACMLPolicyWriter.writePolicyFile(os, policy);
                LOGGER.info("{}", os);
            } catch (IOException e) {
                LOGGER.error("Failed to create byte array stream", e);
            }
        }
        return policy;
    }

    @Override
    protected void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse) {
        for (Advice adv : advice) {
            if (! ToscaDictionary.ID_ADVICE_OPTIMIZATION_SUBSCRIBER.equals(adv.getId())) {
                LOGGER.warn("Unknown advice id {}", adv.getId());
                continue;
            }
            //
            // Get the existing advice if any, we are appending to it.
            //
            Map<String, Object> mapAdvice = decisionResponse.getAdvice();
            //
            // If there's nothing, create a map
            //
            if (mapAdvice == null) {
                mapAdvice = new HashMap<>();
            }
            for (AttributeAssignment assignment : adv.getAttributeAssignments()) {
                if (ToscaDictionary.ID_ADVICE_OPTIMIZATION_SUBSCRIBER_ROLE.equals(assignment.getAttributeId())) {
                    addValuesToMap(assignment.getAttributeValue().getValue(), FIELD_SUBSCRIBER_ROLE, mapAdvice);
                } else if (ToscaDictionary.ID_ADVICE_OPTIMIZATION_SUBSCRIBER_STATUS.equals(
                        assignment.getAttributeId())) {
                    addValuesToMap(assignment.getAttributeValue().getValue(), FIELD_PROV_STATUS, mapAdvice);
                }
            }
            if (! mapAdvice.isEmpty()) {
                decisionResponse.setAdvice(mapAdvice);
            }
        }
    }

    @SuppressWarnings("unchecked")
    private static void addValuesToMap(Object values, String key, Map<String, Object> mapAdvice) {
        if (values instanceof Collection) {
            List<String> valueList = new ArrayList<>();
            ((Collection<Object>) values).forEach(val -> valueList.add(val.toString()));
            mapAdvice.put(key, valueList);
        } else {
            mapAdvice.put(key, values.toString());
        }

    }

    @SuppressWarnings("unchecked")
    private static PolicyType addSubscriberNameIntoTarget(PolicyType policy,
            Map<String, Object> subscriberProperties) throws ToscaPolicyConversionException {
        //
        // Find the subscriber names
        //
        Object subscriberNames = subscriberProperties.get("subscriberName");
        if (subscriberNames == null) {
            throw new ToscaPolicyConversionException("Missing subscriberName property");
        }
        //
        // Iterate through all the subscriber names
        //
        AnyOfType anyOf = new AnyOfType();
        for (Object subscriberName : subscriberNames instanceof Collection ? (List<Object>) subscriberNames :
            Arrays.asList(subscriberNames)) {

            MatchType match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
                    XACML3.ID_FUNCTION_STRING_EQUAL,
                    subscriberName,
                    XACML3.ID_DATATYPE_STRING,
                    ToscaDictionary.ID_SUBJECT_OPTIMIZATION_SUBSCRIBER_NAME,
                    XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT);

            anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(match));
        }
        //
        // Add to the target
        //
        policy.getTarget().getAnyOf().add(anyOf);
        //
        // Return for convenience
        //
        return policy;
    }

    @SuppressWarnings("unchecked")
    private static AdviceExpressionsType generateSubscriberAdvice(Map<String, Object> subscriberProperties)
            throws ToscaPolicyConversionException {
        //
        // Get the subscriber role
        //
        Object role = subscriberProperties.get(FIELD_SUBSCRIBER_ROLE);
        if (role == null || StringUtils.isBlank(role.toString())) {
            throw new ToscaPolicyConversionException("Missing subscriberRole");
        }
        //
        // Create our subscriber advice expression
        //
        AdviceExpressionType adviceExpression = new AdviceExpressionType();
        adviceExpression.setAppliesTo(EffectType.PERMIT);
        adviceExpression.setAdviceId(ToscaDictionary.ID_ADVICE_OPTIMIZATION_SUBSCRIBER.stringValue());
        //
        // Add in subscriber role advice attributes
        //
        generateSubscriberAdviceAttributes(
                adviceExpression,
                ToscaDictionary.ID_ADVICE_OPTIMIZATION_SUBSCRIBER_ROLE,
                role instanceof Collection ? (List<Object>) role : Arrays.asList(role));
        //
        // Get the provision status
        //
        Object provision = subscriberProperties.get(FIELD_PROV_STATUS);
        if (provision == null || StringUtils.isBlank(provision.toString())) {
            throw new ToscaPolicyConversionException("Missing provStatus");
        }
        adviceExpression = generateSubscriberAdviceAttributes(
                adviceExpression,
                ToscaDictionary.ID_ADVICE_OPTIMIZATION_SUBSCRIBER_STATUS,
                role instanceof Collection ? (List<Object>) provision : Arrays.asList(role));
        //
        // Add it to the overall expressions
        //
        AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
        adviceExpressions.getAdviceExpression().add(adviceExpression);
        //
        // Done return our advice expressions
        //
        return adviceExpressions;
    }

    private static AdviceExpressionType generateSubscriberAdviceAttributes(AdviceExpressionType adviceExpression,
            Identifier attributeId, Collection<Object> adviceAttribute) {
        for (Object attribute : adviceAttribute) {
            AttributeValueType value = new AttributeValueType();
            value.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
            value.getContent().add(attribute.toString());

            AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
            assignment.setAttributeId(attributeId.stringValue());
            assignment.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue());
            assignment.setExpression(new ObjectFactory().createAttributeValue(value));

            adviceExpression.getAttributeAssignmentExpression().add(assignment);
        }
        //
        // Return for convenience
        //
        return adviceExpression;
    }
}