2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2020 Nordix Foundation.
5 * Modifications Copyright (C) 2021 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.gui.editors.apex.rest.handling;
26 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
27 import org.onap.policy.apex.model.modelapi.ApexApiResult;
28 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
29 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
30 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanKeyRef;
31 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanLogic;
32 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanPolicy;
33 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanState;
34 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanStateOutput;
35 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanStateTaskRef;
36 import org.slf4j.ext.XLogger;
37 import org.slf4j.ext.XLoggerFactory;
40 * This class handles commands on policies in Apex models.
42 public class PolicyHandler implements RestCommandHandler {
43 // Get a reference to the logger
44 private static final XLogger LOGGER = XLoggerFactory.getXLogger(PolicyHandler.class);
46 // Recurring string constants
47 private static final String OK = ": OK";
48 private static final String NOT_OK = ": Not OK";
49 private static final String POLICY_WAS_CREATED = "\". The policy was created, ";
50 private static final String POLICY_STATE_CREATED = "\". The policy and state were created, ";
51 private static final String POLICY_PARTIALLY_DEFINED = " The policy has only been partially defined.";
52 private static final String FOR_POLICY = "\" for policy \"";
53 private static final String IN_STATE = "\" in state \"";
54 private static final String POLICY_CREATED_STATE_ERROR = POLICY_WAS_CREATED
55 + "but there was an error adding the state.";
56 private static final String POLICY_STATE_CREATED_OTHER_ERROR = POLICY_STATE_CREATED
57 + "but there was an error adding the";
63 public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
64 final RestCommand command) {
65 return getUnsupportedCommandResultMessage(session, commandType, command);
72 public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
73 final RestCommand command, final String jsonString) {
75 if (!RestCommandType.POLICY.equals(commandType)) {
76 return getUnsupportedCommandResultMessage(session, commandType, command);
81 return createPolicy(session, jsonString);
83 return updatePolicy(session, jsonString);
85 return getUnsupportedCommandResultMessage(session, commandType, command);
93 public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
94 final RestCommand command, final String name, final String version) {
95 if (!RestCommandType.POLICY.equals(commandType)) {
96 return getUnsupportedCommandResultMessage(session, commandType, command);
101 return listPolicies(session, name, version);
103 return deletePolicy(session, name, version);
105 return getUnsupportedCommandResultMessage(session, commandType, command);
110 * Creates a policy with the information in the JSON string passed.
112 * @param session the Apex model editing session
113 * @param jsonString the JSON string to be parsed See {@linkplain BeanPolicy}
114 * @return an ApexAPIResult object. If successful then
115 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
116 * can be retrieved using {@link ApexApiResult#getMessages()}
118 public ApexApiResult createPolicy(final RestSession session, final String jsonString) {
119 LOGGER.entry(jsonString);
121 final var jsonbean = RestUtils.getJsonParameters(jsonString, BeanPolicy.class);
125 ApexApiResult result = session.getApexModelEdited().createPolicy(jsonbean.getName(), jsonbean.getVersion(),
126 jsonbean.getTemplate(), jsonbean.getFirstState(), jsonbean.getUuid(), jsonbean.getDescription());
129 result = createPolicyContent(session, jsonbean);
132 session.finishSession(result.isOk());
134 LOGGER.exit("Policy/Create" + (result.isOk() ? OK : NOT_OK));
139 * Create the content of the policy.
141 * @param session the Apex model editing session
142 * @param jsonString the JSON string to be parsed See {@linkplain BeanPolicy}
143 * @return an ApexAPIResult object. If successful then
144 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
145 * can be retrieved using {@link ApexApiResult#getMessages()}
147 private ApexApiResult createPolicyContent(RestSession session, BeanPolicy jsonbean) {
148 var result = new ApexApiResult();
150 if (jsonbean.getStates() == null || jsonbean.getStates().isEmpty()) {
151 result.setResult(Result.FAILED);
152 result.addMessage("Null or empty state map; no states defined for policy \"" + jsonbean.getName() + ":"
153 + jsonbean.getVersion() + "\". The policy was created, but there was an error adding states."
154 + POLICY_PARTIALLY_DEFINED);
158 // States reference each other so all states must be created before they are
160 for (final Map.Entry<String, BeanState> stateEntry : jsonbean.getStates().entrySet()) {
161 ApexApiResult stateCreateResult = createState(session, jsonbean.getName(), jsonbean.getVersion(),
162 stateEntry.getKey(), stateEntry.getValue());
164 if (stateCreateResult.isNok()) {
165 result.setResult(stateCreateResult.getResult());
166 result.addMessage(stateCreateResult.getMessage());
170 // Bale out if the state creation did not work
171 if (result.isNok()) {
175 // Now create the content of each state
176 for (final Map.Entry<String, BeanState> stateEntry : jsonbean.getStates().entrySet()) {
177 ApexApiResult stateContentCreateResult = createStateContent(session, jsonbean.getName(),
178 jsonbean.getVersion(), stateEntry.getKey(), stateEntry.getValue());
180 if (stateContentCreateResult.isNok()) {
181 result.setResult(stateContentCreateResult.getResult());
182 result.addMessage(stateContentCreateResult.getMessage());
190 * Create a state on the policy.
192 * @param session the Apex model editing session
193 * @param policyName the policy name
194 * @param policVersion the policy version
195 * @param stateName the name of the state
196 * @param stateBean the information on the state to create
197 * @return an ApexAPIResult object. If successful then
198 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
199 * can be retrieved using {@link ApexApiResult#getMessages()}
201 private ApexApiResult createState(final RestSession session, final String policyName, final String policyVersion,
202 final String stateName, final BeanState stateBean) {
204 if (stateBean == null) {
205 return new ApexApiResult(Result.FAILED,
206 "Null or invalid state information for state \"" + stateName + FOR_POLICY + policyName + ":"
207 + policyVersion + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
210 if (stateBean.getTrigger() == null) {
211 return new ApexApiResult(Result.FAILED,
212 "Null or invalid state trigger for state \"" + stateName + FOR_POLICY + policyName + ":" + policyVersion
213 + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
216 if (stateBean.getDefaultTask() == null) {
217 return new ApexApiResult(Result.FAILED, "Null or invalid default task for state \"" + stateName + FOR_POLICY
218 + policyName + ":" + policyVersion + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
221 return session.getApexModelEdited().createPolicyState(policyName, policyVersion, stateName,
222 stateBean.getTrigger().getName(), stateBean.getTrigger().getVersion(), stateBean.getDefaultTask().getName(),
223 stateBean.getDefaultTask().getVersion());
227 * Create the content of a state on the policy.
229 * @param session the Apex model editing session
230 * @param policyName the policy name
231 * @param policVersion the policy version
232 * @param stateName the name of the state
233 * @param stateBean the information on the state to create
234 * @return an ApexAPIResult object. If successful then
235 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
236 * can be retrieved using {@link ApexApiResult#getMessages()}
238 private ApexApiResult createStateContent(final RestSession session, final String policyName,
239 final String policyVersion, final String stateName, final BeanState stateBean) {
241 ApexApiResult ret = createStateTaskSelectionLogic(session, policyName, policyVersion, stateName, stateBean);
244 ret = createStateContextReferences(session, policyName, policyVersion, stateName, stateBean);
248 ret = createStateFinalizers(session, policyName, policyVersion, stateName, stateBean);
252 ret = createStateOutputs(session, policyName, policyVersion, stateName, stateBean);
256 ret = createStateTaskReferences(session, policyName, policyVersion, stateName, stateBean);
263 * Create the task selection logic for the state.
265 * @param session the Apex model editing session
266 * @param policyName the policy name
267 * @param policVersion the policy version
268 * @param stateName the name of the state
269 * @param stateBean the information on the state to create
270 * @return an ApexAPIResult object. If successful then
271 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
272 * can be retrieved using {@link ApexApiResult#getMessages()}
274 private ApexApiResult createStateTaskSelectionLogic(final RestSession session, final String policyName,
275 final String policyVersion, final String stateName, final BeanState stateBean) {
277 final BeanLogic tsl = stateBean.getTaskSelectionLogic();
279 return new ApexApiResult();
282 ApexApiResult result = session.getApexModelEdited().createPolicyStateTaskSelectionLogic(policyName,
283 policyVersion, stateName, tsl.getLogicFlavour(), tsl.getLogic());
285 if (result.isNok()) {
286 result.addMessage("Failed to add task selection logic for state \"" + stateName + "\" for" + " policy \""
287 + policyName + ":" + policyVersion + POLICY_WAS_CREATED
288 + "but there was an error adding the task selection logic "
289 + "for the state. The policy has only been partially defined.");
295 * Create the context references for the state.
297 * @param session the Apex model editing session
298 * @param policyName the policy name
299 * @param policVersion the policy version
300 * @param stateName the name of the state
301 * @param stateBean the information on the state to create
302 * @return an ApexAPIResult object. If successful then
303 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
304 * can be retrieved using {@link ApexApiResult#getMessages()}
306 private ApexApiResult createStateContextReferences(final RestSession session, final String policyName,
307 final String policyVersion, final String stateName, final BeanState stateBean) {
309 var result = new ApexApiResult();
311 final BeanKeyRef[] contextReferences = stateBean.getContexts();
312 if (contextReferences == null || contextReferences.length == 0) {
316 for (final BeanKeyRef contextReference : contextReferences) {
317 if (contextReference == null) {
318 result.setResult(Result.FAILED);
319 result.addMessage("Null or invalid context reference \"" + contextReference + "\" for" + " state \""
320 + stateName + FOR_POLICY + policyName + ":" + policyVersion
321 + "\". The policy was created, but there was an error adding the context "
322 + "reference for the state. The policy has only been partially defined.");
326 ApexApiResult contextRefResult = session.getApexModelEdited().createPolicyStateContextRef(policyName,
327 policyVersion, stateName, contextReference.getName(), contextReference.getVersion());
329 if (contextRefResult.isNok()) {
330 result.setResult(contextRefResult.getResult());
331 result.addMessage("Failed to add context reference \"" + contextReference + "\" for state \""
332 + stateName + FOR_POLICY + policyName + ":" + policyVersion + POLICY_WAS_CREATED
333 + "but there was an error adding the context reference "
334 + "for the state. The policy has only been partially defined.");
342 * Create the state finalizers for the state.
344 * @param session the Apex model editing session
345 * @param policyName the policy name
346 * @param policVersion the policy version
347 * @param stateName the name of the state
348 * @param stateBean the information on the state to create
349 * @return an ApexAPIResult object. If successful then
350 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
351 * can be retrieved using {@link ApexApiResult#getMessages()}
353 private ApexApiResult createStateFinalizers(final RestSession session, final String policyName,
354 final String policyVersion, final String stateName, final BeanState stateBean) {
356 var result = new ApexApiResult();
358 final Map<String, BeanLogic> finalizers = stateBean.getFinalizers();
359 if (finalizers == null || finalizers.isEmpty()) {
363 for (final Map.Entry<String, BeanLogic> finalizerEntry : finalizers.entrySet()) {
364 if (finalizerEntry.getKey() == null || finalizerEntry.getValue() == null) {
365 result.setResult(Result.FAILED);
366 result.addMessage("Null or invalid finalizer information for finalizer " + "named \""
367 + finalizerEntry.getKey() + IN_STATE + stateName + FOR_POLICY + policyName + ":" + policyVersion
368 + POLICY_STATE_CREATED_OTHER_ERROR + " finalizer. The policy has only "
369 + "been partially defined.");
373 ApexApiResult finalizerResult = session.getApexModelEdited().createPolicyStateFinalizerLogic(policyName,
374 policyVersion, stateName, finalizerEntry.getKey(), finalizerEntry.getValue().getLogicFlavour(),
375 finalizerEntry.getValue().getLogic());
377 if (finalizerResult.isNok()) {
378 result.setResult(finalizerResult.getResult());
379 result.addMessage("Failed to add finalizer information for finalizer named \"" + finalizerEntry.getKey()
380 + "\" in" + " state \"" + stateName + FOR_POLICY + policyName + ":" + policyVersion
381 + POLICY_STATE_CREATED_OTHER_ERROR + " finalizer. The policy has only been partially defined.");
389 * Create the state outputs for the state.
391 * @param session the Apex model editing session
392 * @param policyName the policy name
393 * @param policVersion the policy version
394 * @param stateName the name of the state
395 * @param stateBean the information on the state to create
396 * @return an ApexAPIResult object. If successful then
397 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
398 * can be retrieved using {@link ApexApiResult#getMessages()}
400 private ApexApiResult createStateOutputs(final RestSession session, final String policyName,
401 final String policyVersion, final String stateName, final BeanState stateBean) {
403 var result = new ApexApiResult();
405 final Map<String, BeanStateOutput> stateOutputs = stateBean.getStateOutputs();
406 if (stateOutputs == null || stateOutputs.isEmpty()) {
407 result.setResult(Result.FAILED);
408 result.addMessage("No state outputs have been defined in state \"" + stateName + FOR_POLICY + policyName
409 + ":" + policyVersion + "\". The policy and state were created, but there was an error adding state"
410 + " outputs. The policy has only been partially defined.");
414 for (final Map.Entry<String, BeanStateOutput> stateOutput : stateOutputs.entrySet()) {
415 final String outputName = stateOutput.getKey();
416 final BeanStateOutput output = stateOutput.getValue();
418 if (outputName == null || output == null || output.getEvent() == null) {
419 result.setResult(Result.FAILED);
420 result.addMessage("Null or invalid output information for output named \"" + outputName + IN_STATE
421 + stateName + FOR_POLICY + policyName + ":" + policyVersion + POLICY_STATE_CREATED_OTHER_ERROR
422 + " output. The policy has only been partially defined.");
426 ApexApiResult outputResult = session.getApexModelEdited().createPolicyStateOutput(policyName, policyVersion,
427 stateName, outputName, output.getEvent().getName(), output.getEvent().getVersion(),
428 output.getNextState());
430 if (outputResult.isNok()) {
431 result.setResult(outputResult.getResult());
432 result.addMessage("Failed to add output information for output named \"" + outputName + IN_STATE
433 + stateName + FOR_POLICY + policyName + ":" + policyVersion + POLICY_STATE_CREATED
434 + "but there was an error adding the output." + POLICY_PARTIALLY_DEFINED);
442 * Create the task references for the state.
444 * @param session the Apex model editing session
445 * @param policyName the policy name
446 * @param policVersion the policy version
447 * @param stateName the name of the state
448 * @param stateBean the information on the state to create
449 * @return an ApexAPIResult object. If successful then
450 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
451 * can be retrieved using {@link ApexApiResult#getMessages()}
453 private ApexApiResult createStateTaskReferences(final RestSession session, final String policyName,
454 final String policyVersion, final String stateName, final BeanState stateBean) {
456 var result = new ApexApiResult();
458 final Map<String, BeanStateTaskRef> taskMap = stateBean.getTasks();
459 if (taskMap == null || taskMap.isEmpty()) {
460 result.setResult(Result.FAILED);
461 result.addMessage("No tasks have been defined in state \"" + stateName + FOR_POLICY + policyName + ":"
462 + policyVersion + "\". The policy and state were created, but there was an error adding tasks."
463 + POLICY_PARTIALLY_DEFINED);
467 for (final Map.Entry<String, BeanStateTaskRef> taskEntry : taskMap.entrySet()) {
468 final String taskLocalName = taskEntry.getKey();
469 final BeanStateTaskRef taskReference = taskEntry.getValue();
471 if (taskLocalName == null || taskReference == null || taskReference.getTask() == null) {
472 result.setResult(Result.FAILED);
473 result.addMessage("Null or invalid task information for task named \"" + taskLocalName + IN_STATE
474 + stateName + "\" for for policy \"" + policyName + ":" + policyVersion
475 + "\". The policy and state were created, but there was an error adding the "
476 + "task. The policy has only been partially defined.");
480 ApexApiResult taskRefResult = session.getApexModelEdited().createPolicyStateTaskRef(policyName,
481 policyVersion, stateName, taskLocalName, taskReference.getTask().getName(),
482 taskReference.getTask().getVersion(), taskReference.getOutputType(), taskReference.getOutputName());
484 if (taskRefResult.isNok()) {
485 result.setResult(taskRefResult.getResult());
486 result.addMessage("Failed to add task reference \"" + taskEntry + "\" for state \"" + stateName
487 + FOR_POLICY + policyName + ":" + policyVersion + POLICY_WAS_CREATED
488 + "but there was an error adding the task reference for"
489 + " the state. The policy has only been partially defined.");
497 * Update a policy with the information in the JSON string passed.
499 * @param session the Apex model editing session
500 * @param jsonString the JSON string to be parsed. See {@linkplain BeanPolicy}
501 * @return an ApexAPIResult object. If successful then
502 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
503 * can be retrieved using {@link ApexApiResult#getMessages()}
505 private ApexApiResult updatePolicy(final RestSession session, final String jsonString) {
507 LOGGER.entry(jsonString);
509 final var jsonbean = RestUtils.getJsonParameters(jsonString, BeanPolicy.class);
511 if (blank2Null(jsonbean.getName()) == null || blank2Null(jsonbean.getVersion()) == null) {
512 LOGGER.exit("Task/Update" + NOT_OK);
513 return new ApexApiResult(Result.FAILED, "Null/Empty Policy name/version (\"" + jsonbean.getName() + ":"
514 + jsonbean.getVersion() + "\" passed to UpdatePolicy");
519 ApexApiResult result = session.getApexModelEdited().deletePolicy(jsonbean.getName(), jsonbean.getVersion());
522 result = session.getApexModelEdited().createPolicy(jsonbean.getName(), jsonbean.getVersion(),
523 jsonbean.getTemplate(), jsonbean.getFirstState(), jsonbean.getUuid(), jsonbean.getDescription());
526 result = createPolicyContent(session, jsonbean);
530 session.finishSession(result.isOk());
532 LOGGER.exit("Policy/Update" + (result.isOk() ? OK : NOT_OK));
538 * List policies with the given key names/versions. If successful the result(s)
539 * will be available in the result messages. The returned value(s) will be
540 * similar to {@link AxPolicy}, with merged {@linkplain AxKey Info} for the root
543 * @param session the Apex model editing session
544 * @param name the name to search for. If null or empty, then all names will
546 * @param version the version to search for. If null then all versions will be
548 * @return an ApexAPIResult object. If successful then
549 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
550 * can be retrieved using {@link ApexApiResult#getMessages()}
552 private ApexApiResult listPolicies(final RestSession session, final String name, final String version) {
553 LOGGER.entry(name, version);
555 ApexApiResult result = session.getApexModel().listPolicy(blank2Null(name), blank2Null(version));
557 LOGGER.exit("Policy/Get" + (result != null && result.isOk() ? OK : NOT_OK));
562 * Delete policies with the given key names/versions.
564 * @param session the Apex model editing session
565 * @param name the name to search for. If null or empty, then all names will
567 * @param version the version to search for. If null then all versions will be
569 * @return an ApexAPIResult object. If successful then
570 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
571 * can be retrieved using {@link ApexApiResult#getMessages()}
573 private ApexApiResult deletePolicy(final RestSession session, final String name, final String version) {
574 LOGGER.entry(name, version);
578 // all input/output fields, parameters, logic, context references is
581 // deleting the task removes all of these
582 ApexApiResult result = session.getApexModelEdited().deletePolicy(blank2Null(name), blank2Null(version));
584 session.finishSession(result.isOk());
586 LOGGER.exit("Policy/Delete" + (result.isOk() ? OK : NOT_OK));