Delete preprocessed flag from actors
[policy/models.git] / models-interactions / model-actors / actor.guard / src / main / java / org / onap / policy / controlloop / actor / guard / DecisionOperation.java
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.Collections;
24 import java.util.Map;
25 import java.util.concurrent.CompletableFuture;
26 import java.util.concurrent.Executor;
27 import javax.ws.rs.client.Entity;
28 import javax.ws.rs.core.MediaType;
29 import javax.ws.rs.core.Response;
30 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
31 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
32 import org.onap.policy.controlloop.actorserviceprovider.CallbackManager;
33 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
34 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
35 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
36 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
37 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
38 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
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 DecisionOperation extends HttpOperation<DecisionResponse> {
60     private static final Logger logger = LoggerFactory.getLogger(DecisionOperation.class);
61
62     // operation name
63     public static final String NAME = OperationPartial.GUARD_OPERATION_NAME;
64
65     public static final String PERMIT = "Permit";
66     public static final String DENY = "Deny";
67     public static final String INDETERMINATE = "Indeterminate";
68
69     /**
70      * Prefix for properties in the payload that should be copied to the "resource" field
71      * of the request.
72      */
73     public static final String RESOURCE_PREFIX = "resource.";
74
75     private final GuardConfig config;
76
77
78     /**
79      * Constructs the object.
80      *
81      * @param params operation parameters
82      * @param config configuration for this operation
83      */
84     public DecisionOperation(ControlLoopOperationParams params, HttpConfig config) {
85         super(params, config, DecisionResponse.class, Collections.emptyList());
86         this.config = (GuardConfig) config;
87     }
88
89     @Override
90     public CompletableFuture<OperationOutcome> start() {
91         if (!config.isDisabled()) {
92             // enabled - do full guard operation
93             return super.start();
94         }
95
96         // guard is disabled, thus it is always treated as a success
97         logger.info("{}: guard disabled, always succeeds for {}", getFullName(), params.getRequestId());
98
99         final Executor executor = params.getExecutor();
100         final CallbackManager callbacks = new CallbackManager();
101
102         return CompletableFuture.completedFuture(makeOutcome())
103                         .whenCompleteAsync(callbackStarted(callbacks), executor)
104                         .whenCompleteAsync(callbackCompleted(callbacks), executor);
105     }
106
107     @Override
108     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
109         DecisionRequest request = makeRequest();
110
111         Map<String, Object> headers = makeHeaders();
112
113         headers.put("Accept", MediaType.APPLICATION_JSON);
114         String url = getUrl();
115
116         String strRequest = prettyPrint(request);
117         logMessage(EventType.OUT, CommInfrastructure.REST, url, strRequest);
118
119         Entity<String> entity = Entity.entity(strRequest, MediaType.APPLICATION_JSON);
120
121         // @formatter:off
122         return handleResponse(outcome, url,
123             callback -> getClient().post(callback, getPath(), entity, headers));
124         // @formatter:on
125     }
126
127     /**
128      * Makes a request from the payload.
129      *
130      * @return a new request
131      */
132     protected DecisionRequest makeRequest() {
133         if (params.getPayload() == null) {
134             throw new IllegalArgumentException("missing payload");
135         }
136
137         DecisionRequest req = config.makeRequest();
138         req.setRequestId(getSubRequestId());
139         req.setResource(Map.of("guard", params.getPayload()));
140
141         return req;
142     }
143
144     @Override
145     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
146                     Response rawResponse, DecisionResponse response) {
147
148         outcome.setResponse(response);
149
150         // determine the result
151         String status = response.getStatus();
152         if (status == null) {
153             outcome.setResult(OperationResult.FAILURE);
154             outcome.setMessage("response contains no status");
155             return CompletableFuture.completedFuture(outcome);
156         }
157
158         if (PERMIT.equalsIgnoreCase(status) || INDETERMINATE.equalsIgnoreCase(status)) {
159             outcome.setResult(OperationResult.SUCCESS);
160         } else {
161             outcome.setResult(OperationResult.FAILURE);
162         }
163
164         // set the message
165         outcome.setMessage(response.getStatus());
166
167         return CompletableFuture.completedFuture(outcome);
168     }
169 }