Update snapshot and/or references of policy/models to latest snapshots
[policy/models.git] / models-interactions / model-simulators / src / main / java / org / onap / policy / simulators / XacmlSimulatorJaxRs.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * simulators
4  * ================================================================================
5  * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019, 2023 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.simulators;
23
24 import jakarta.ws.rs.Consumes;
25 import jakarta.ws.rs.POST;
26 import jakarta.ws.rs.Path;
27 import jakarta.ws.rs.Produces;
28 import jakarta.ws.rs.core.MediaType;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.Map;
32 import java.util.function.Function;
33 import org.onap.policy.common.utils.coder.Coder;
34 import org.onap.policy.common.utils.coder.CoderException;
35 import org.onap.policy.common.utils.coder.StandardCoder;
36 import org.onap.policy.common.utils.resources.ResourceUtils;
37 import org.onap.policy.models.decisions.concepts.DecisionRequest;
38 import org.onap.policy.models.decisions.concepts.DecisionResponse;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 @Path("/policy/pdpx/v1")
44 public class XacmlSimulatorJaxRs {
45     private static final Logger logger = LoggerFactory.getLogger(XacmlSimulatorJaxRs.class);
46
47     public static final String POLICY_CONFIG_OPER_PREFIX = "org/onap/policy/simulators/xacml/xacml.configure.";
48     public static final String DENY_CLNAME = "denyGuard";
49     public static final Coder coder = new StandardCoder();
50
51     // @formatter:off
52     private Map<String, Function<DecisionRequest, DecisionResponse>> action2method = Map.of(
53                 "guard", this::guardDecision,
54                 "configure", this::configureDecision
55                 );
56     // @formatter:on
57
58     /**
59      * Get a XACML decision.
60      *
61      * @param req the request
62      * @return the response
63      */
64     @POST
65     @Path("/decision")
66     @Consumes(MediaType.APPLICATION_JSON)
67     @Produces("application/json")
68     public DecisionResponse getDecision(DecisionRequest req) {
69         Function<DecisionRequest, DecisionResponse> func = action2method.get(req.getAction());
70         if (func != null) {
71             return func.apply(req);
72         }
73
74         var response = new DecisionResponse();
75         response.setMessage("unsupported action: " + req.getAction());
76         return response;
77     }
78
79     private DecisionResponse guardDecision(DecisionRequest req) {
80         @SuppressWarnings("unchecked")
81         Map<String, String> guard = (Map<String, String>) req.getResource().get("guard");
82         String clName = guard.get("clname");
83
84         var response = new DecisionResponse();
85         response.setStatus(DENY_CLNAME.equals(clName) ? "Deny" : "Permit");
86         response.setAdvice(Collections.emptyMap());
87         response.setObligations(Collections.emptyMap());
88         response.setPolicies(Collections.emptyMap());
89         return response;
90     }
91
92     private DecisionResponse configureDecision(DecisionRequest req) {
93         var response = new DecisionResponse();
94         response.setPolicies(new HashMap<>());
95
96         Map<String, Object> resources = req.getResource();
97         var policyId = resources.get("policy-id");
98         if (policyId != null) {
99             String fileName = POLICY_CONFIG_OPER_PREFIX + policyId + ".json";
100             try {
101                 var policyJson = ResourceUtils.getResourceAsString(fileName);
102                 var toscaServiceTemplate = coder.decode(policyJson, ToscaServiceTemplate.class);
103                 toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()
104                                 .forEach(policyMap -> response.getPolicies().putAll(policyMap));
105             } catch (CoderException e) {
106                 logger.warn("cannot decode policy file: {}", fileName, e);
107                 response.setMessage("cannot decode policy");
108             } catch (NullPointerException e) {
109                 logger.warn("cannot read policy simulator file", e);
110                 response.setMessage("cannot read policy simulator file");
111             }
112         } else {
113             // the current simulator only supports searching by policy-id
114             // future changes may support getting policies by policy-type
115             response.setMessage("resource must contain policy-id key");
116         }
117         return response;
118     }
119 }