941838f00e6806fd7d685ad4ecfccb2f624c8a20
[policy/models.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 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
21 package org.onap.policy.controlloop.actor.guard;
22
23 import java.util.LinkedHashMap;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.UUID;
27 import java.util.concurrent.CompletableFuture;
28 import javax.ws.rs.client.Entity;
29 import javax.ws.rs.core.MediaType;
30 import javax.ws.rs.core.Response;
31 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
32 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
33 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
34 import org.onap.policy.controlloop.actorserviceprovider.Util;
35 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
36 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperator;
37 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
38 import org.onap.policy.controlloop.policy.PolicyResult;
39 import org.onap.policy.models.decisions.concepts.DecisionRequest;
40 import org.onap.policy.models.decisions.concepts.DecisionResponse;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * Guard Operation. The outcome message is set to the guard response. If the guard is
46  * permitted or indeterminate, then the outcome is set to SUCCESS.
47  * <p/>
48  * The input to the request is taken from the payload, where properties are mapped to the
49  * field names in the {@link DecisionRequest} object. Properties whose names begin with
50  * "resource." are placed into the "resource" field of the {@link DecisionRequest}. The
51  * following will be provided, if not specified in the payload:
52  * <dl>
53  * <dt>action</dt>
54  * <dd>"guard"</dd>
55  * <dt>request ID</dt>
56  * <dd>generated</dd>
57  * </dl>
58  */
59 public class GuardOperation extends HttpOperation<DecisionResponse> {
60     private static final Logger logger = LoggerFactory.getLogger(GuardOperation.class);
61
62     // operation name
63     public static final String NAME = "Decision";
64
65     public static final String PERMIT = "Permit";
66     public static final String DENY = "Deny";
67     public static final String INDETERMINATE = "Indeterminate";
68
69     private static final String RESOURCE = "resource";
70
71     /**
72      * Prefix for properties in the payload that should be copied to the "resource" field
73      * of the request.
74      */
75     public static final String RESOURCE_PREFIX = "resource.";
76
77
78     /**
79      * Constructs the object.
80      *
81      * @param params operation parameters
82      * @param operator operator that created this operation
83      */
84     public GuardOperation(ControlLoopOperationParams params, HttpOperator operator) {
85         super(params, operator, DecisionResponse.class);
86     }
87
88     @Override
89     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
90
91         DecisionRequest request = Util.translate(getName(), makeRequest(), DecisionRequest.class);
92
93         Entity<DecisionRequest> entity = Entity.entity(request, MediaType.APPLICATION_JSON);
94
95         Map<String, Object> headers = makeHeaders();
96
97         headers.put("Accept", MediaType.APPLICATION_JSON);
98         String url = makeUrl();
99
100         logMessage(EventType.OUT, CommInfrastructure.REST, url, request);
101
102         // @formatter:off
103         return handleResponse(outcome, url,
104             callback -> getOperator().getClient().post(callback, makePath(), entity, headers));
105         // @formatter:on
106     }
107
108     /**
109      * Makes a request from the payload.
110      *
111      * @return a new request map
112      */
113     protected Map<String, Object> makeRequest() {
114         if (params.getPayload() == null) {
115             throw new IllegalArgumentException("missing payload");
116         }
117
118         /*
119          * This code could be easily modified to allow the context and/or resource to be
120          * an encoded JSON string, that is decoded into a Map and stuffed into the
121          * appropriate field.
122          */
123
124         Map<String, Object> req = new LinkedHashMap<>();
125         Map<String, Object> resource = new LinkedHashMap<>();
126
127         for (Entry<String, String> ent : params.getPayload().entrySet()) {
128             String key = ent.getKey();
129
130             if (key.startsWith(RESOURCE_PREFIX)) {
131                 // it's a resource property - put into the resource map
132                 key = key.substring(RESOURCE_PREFIX.length());
133                 resource.put(key, ent.getValue());
134
135             } else if (key.indexOf('.') < 0) {
136                 // it's a normal property - put into the request map
137                 req.put(key, ent.getValue());
138
139             } else {
140                 logger.warn("{}: unused key {} in payload for {}", getFullName(), key, params.getRequestId());
141             }
142         }
143
144         req.putIfAbsent("action", "guard");
145         req.computeIfAbsent("requestId", key -> UUID.randomUUID().toString());
146         req.put(RESOURCE, resource);
147
148         return req;
149     }
150
151     @Override
152     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
153                     Response rawResponse, DecisionResponse response) {
154
155         // determine the result
156         String status = response.getStatus();
157         if (status == null) {
158             outcome.setResult(PolicyResult.FAILURE);
159             outcome.setMessage("response contains no status");
160             return CompletableFuture.completedFuture(outcome);
161         }
162
163         if (PERMIT.equalsIgnoreCase(status) || INDETERMINATE.equalsIgnoreCase(status)) {
164             outcome.setResult(PolicyResult.SUCCESS);
165         } else {
166             outcome.setResult(PolicyResult.FAILURE);
167         }
168
169         // set the message
170         outcome.setMessage(response.getStatus());
171
172         return CompletableFuture.completedFuture(outcome);
173     }
174 }