2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2020 Nordix Foundation.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.gui.editors.apex.rest.handling;
25 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
26 import org.onap.policy.apex.model.modelapi.ApexApiResult;
27 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
28 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
29 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanKeyRef;
30 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanLogic;
31 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanPolicy;
32 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanState;
33 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanStateOutput;
34 import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanStateTaskRef;
35 import org.slf4j.ext.XLogger;
36 import org.slf4j.ext.XLoggerFactory;
39 * This class handles commands on policies in Apex models.
41 public class PolicyHandler implements RestCommandHandler {
42 // Get a reference to the logger
43 private static final XLogger LOGGER = XLoggerFactory.getXLogger(PolicyHandler.class);
45 // Recurring string constants
46 private static final String OK = ": OK";
47 private static final String NOT_OK = ": Not OK";
48 private static final String POLICY_WAS_CREATED = "\". The policy was created, ";
49 private static final String POLICY_STATE_CREATED = "\". The policy and state were created, ";
50 private static final String POLICY_PARTIALLY_DEFINED = " The policy has only been partially defined.";
51 private static final String FOR_POLICY = "\" for policy \"";
52 private static final String IN_STATE = "\" in state \"";
53 private static final String POLICY_CREATED_STATE_ERROR = POLICY_WAS_CREATED
54 + "but there was an error adding the state.";
55 private static final String POLICY_STATE_CREATED_OTHER_ERROR = POLICY_STATE_CREATED
56 + "but there was an error adding the";
62 public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
63 final RestCommand command) {
64 return getUnsupportedCommandResultMessage(session, commandType, command);
71 public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
72 final RestCommand command, final String jsonString) {
74 if (!RestCommandType.POLICY.equals(commandType)) {
75 return getUnsupportedCommandResultMessage(session, commandType, command);
80 return createPolicy(session, jsonString);
82 return updatePolicy(session, jsonString);
84 return getUnsupportedCommandResultMessage(session, commandType, command);
92 public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
93 final RestCommand command, final String name, final String version) {
94 if (!RestCommandType.POLICY.equals(commandType)) {
95 return getUnsupportedCommandResultMessage(session, commandType, command);
100 return listPolicies(session, name, version);
102 return deletePolicy(session, name, version);
104 return getUnsupportedCommandResultMessage(session, commandType, command);
109 * Creates a policy with the information in the JSON string passed.
111 * @param session the Apex model editing session
112 * @param jsonString the JSON string to be parsed See {@linkplain BeanPolicy}
113 * @return an ApexAPIResult object. If successful then
114 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
115 * can be retrieved using {@link ApexApiResult#getMessages()}
117 public ApexApiResult createPolicy(final RestSession session, final String jsonString) {
118 LOGGER.entry(jsonString);
120 final BeanPolicy jsonbean = RestUtils.getJsonParameters(jsonString, BeanPolicy.class);
124 ApexApiResult result = session.getApexModelEdited().createPolicy(jsonbean.getName(), jsonbean.getVersion(),
125 jsonbean.getTemplate(), jsonbean.getFirstState(), jsonbean.getUuid(), jsonbean.getDescription());
128 result = createPolicyContent(session, jsonbean);
131 session.finishSession(result.isOk());
133 LOGGER.exit("Policy/Create" + (result != null && result.isOk() ? OK : NOT_OK));
138 * Create the content of the policy.
140 * @param session the Apex model editing session
141 * @param jsonString the JSON string to be parsed See {@linkplain BeanPolicy}
142 * @return an ApexAPIResult object. If successful then
143 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
144 * can be retrieved using {@link ApexApiResult#getMessages()}
146 private ApexApiResult createPolicyContent(RestSession session, BeanPolicy jsonbean) {
147 ApexApiResult result = new ApexApiResult();
149 if (jsonbean.getStates() == null || jsonbean.getStates().isEmpty()) {
150 result.setResult(Result.FAILED);
151 result.addMessage("Null or empty state map; no states defined for policy \"" + jsonbean.getName() + ":"
152 + jsonbean.getVersion() + "\". The policy was created, but there was an error adding states."
153 + POLICY_PARTIALLY_DEFINED);
157 // States reference each other so all states must be created before they are
159 for (final Map.Entry<String, BeanState> stateEntry : jsonbean.getStates().entrySet()) {
160 ApexApiResult stateCreateResult = createState(session, jsonbean.getName(), jsonbean.getVersion(),
161 stateEntry.getKey(), stateEntry.getValue());
163 if (stateCreateResult.isNok()) {
164 result.setResult(stateCreateResult.getResult());
165 result.addMessage(stateCreateResult.getMessage());
169 // Bale out if the state creation did not work
170 if (result.isNok()) {
174 // Now create the content of each state
175 for (final Map.Entry<String, BeanState> stateEntry : jsonbean.getStates().entrySet()) {
176 ApexApiResult stateContentCreateResult = createStateContent(session, jsonbean.getName(),
177 jsonbean.getVersion(), stateEntry.getKey(), stateEntry.getValue());
179 if (stateContentCreateResult.isNok()) {
180 result.setResult(stateContentCreateResult.getResult());
181 result.addMessage(stateContentCreateResult.getMessage());
189 * Create a state on the policy.
191 * @param session the Apex model editing session
192 * @param policyName the policy name
193 * @param policVersion the policy version
194 * @param stateName the name of the state
195 * @param stateBean the information on the state to create
196 * @return an ApexAPIResult object. If successful then
197 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
198 * can be retrieved using {@link ApexApiResult#getMessages()}
200 private ApexApiResult createState(final RestSession session, final String policyName, final String policyVersion,
201 final String stateName, final BeanState stateBean) {
203 if (stateBean == null) {
204 return new ApexApiResult(Result.FAILED,
205 "Null or invalid state information for state \"" + stateName + FOR_POLICY + policyName + ":"
206 + policyVersion + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
209 if (stateBean.getTrigger() == null) {
210 return new ApexApiResult(Result.FAILED,
211 "Null or invalid state trigger for state \"" + stateName + FOR_POLICY + policyName + ":" + policyVersion
212 + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
215 if (stateBean.getDefaultTask() == null) {
216 return new ApexApiResult(Result.FAILED, "Null or invalid default task for state \"" + stateName + FOR_POLICY
217 + policyName + ":" + policyVersion + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
220 return session.getApexModelEdited().createPolicyState(policyName, policyVersion, stateName,
221 stateBean.getTrigger().getName(), stateBean.getTrigger().getVersion(), stateBean.getDefaultTask().getName(),
222 stateBean.getDefaultTask().getVersion());
226 * Create the content of a state on the policy.
228 * @param session the Apex model editing session
229 * @param policyName the policy name
230 * @param policVersion the policy version
231 * @param stateName the name of the state
232 * @param stateBean the information on the state to create
233 * @return an ApexAPIResult object. If successful then
234 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
235 * can be retrieved using {@link ApexApiResult#getMessages()}
237 private ApexApiResult createStateContent(final RestSession session, final String policyName,
238 final String policyVersion, final String stateName, final BeanState stateBean) {
240 ApexApiResult ret = createStateTaskSelectionLogic(session, policyName, policyVersion, stateName, stateBean);
243 ret = createStateContextReferences(session, policyName, policyVersion, stateName, stateBean);
247 ret = createStateFinalizers(session, policyName, policyVersion, stateName, stateBean);
251 ret = createStateOutputs(session, policyName, policyVersion, stateName, stateBean);
255 ret = createStateTaskReferences(session, policyName, policyVersion, stateName, stateBean);
262 * Create the task selection logic for the state.
264 * @param session the Apex model editing session
265 * @param policyName the policy name
266 * @param policVersion the policy version
267 * @param stateName the name of the state
268 * @param stateBean the information on the state to create
269 * @return an ApexAPIResult object. If successful then
270 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
271 * can be retrieved using {@link ApexApiResult#getMessages()}
273 private ApexApiResult createStateTaskSelectionLogic(final RestSession session, final String policyName,
274 final String policyVersion, final String stateName, final BeanState stateBean) {
276 final BeanLogic tsl = stateBean.getTaskSelectionLogic();
278 return new ApexApiResult();
281 ApexApiResult result = session.getApexModelEdited().createPolicyStateTaskSelectionLogic(policyName,
282 policyVersion, stateName, tsl.getLogicFlavour(), tsl.getLogic());
284 if (result.isNok()) {
285 result.addMessage("Failed to add task selection logic for state \"" + stateName + "\" for" + " policy \""
286 + policyName + ":" + policyVersion + POLICY_WAS_CREATED
287 + "but there was an error adding the task selection logic "
288 + "for the state. The policy has only been partially defined.");
294 * Create the context references for the state.
296 * @param session the Apex model editing session
297 * @param policyName the policy name
298 * @param policVersion the policy version
299 * @param stateName the name of the state
300 * @param stateBean the information on the state to create
301 * @return an ApexAPIResult object. If successful then
302 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
303 * can be retrieved using {@link ApexApiResult#getMessages()}
305 private ApexApiResult createStateContextReferences(final RestSession session, final String policyName,
306 final String policyVersion, final String stateName, final BeanState stateBean) {
308 ApexApiResult result = new ApexApiResult();
310 final BeanKeyRef[] contextReferences = stateBean.getContexts();
311 if (contextReferences == null || contextReferences.length == 0) {
315 for (final BeanKeyRef contextReference : contextReferences) {
316 if (contextReference == null) {
317 result.setResult(Result.FAILED);
318 result.addMessage("Null or invalid context reference \"" + contextReference + "\" for" + " state \""
319 + stateName + FOR_POLICY + policyName + ":" + policyVersion
320 + "\". The policy was created, but there was an error adding the context "
321 + "reference for the state. The policy has only been partially defined.");
325 ApexApiResult contextRefResult = session.getApexModelEdited().createPolicyStateContextRef(policyName,
326 policyVersion, stateName, contextReference.getName(), contextReference.getVersion());
328 if (contextRefResult.isNok()) {
329 result.setResult(contextRefResult.getResult());
330 result.addMessage("Failed to add context reference \"" + contextReference + "\" for state \""
331 + stateName + FOR_POLICY + policyName + ":" + policyVersion + POLICY_WAS_CREATED
332 + "but there was an error adding the context reference "
333 + "for the state. The policy has only been partially defined.");
341 * Create the state finalizers for the state.
343 * @param session the Apex model editing session
344 * @param policyName the policy name
345 * @param policVersion the policy version
346 * @param stateName the name of the state
347 * @param stateBean the information on the state to create
348 * @return an ApexAPIResult object. If successful then
349 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
350 * can be retrieved using {@link ApexApiResult#getMessages()}
352 private ApexApiResult createStateFinalizers(final RestSession session, final String policyName,
353 final String policyVersion, final String stateName, final BeanState stateBean) {
355 ApexApiResult result = new ApexApiResult();
357 final Map<String, BeanLogic> finalizers = stateBean.getFinalizers();
358 if (finalizers == null || finalizers.isEmpty()) {
362 for (final Map.Entry<String, BeanLogic> finalizerEntry : finalizers.entrySet()) {
363 if (finalizerEntry.getKey() == null || finalizerEntry.getValue() == null) {
364 result.setResult(Result.FAILED);
365 result.addMessage("Null or invalid finalizer information for finalizer " + "named \""
366 + finalizerEntry.getKey() + IN_STATE + stateName + FOR_POLICY + policyName + ":" + policyVersion
367 + POLICY_STATE_CREATED_OTHER_ERROR + " finalizer. The policy has only "
368 + "been partially defined.");
372 ApexApiResult finalizerResult = session.getApexModelEdited().createPolicyStateFinalizerLogic(policyName,
373 policyVersion, stateName, finalizerEntry.getKey(), finalizerEntry.getValue().getLogicFlavour(),
374 finalizerEntry.getValue().getLogic());
376 if (finalizerResult.isNok()) {
377 result.setResult(finalizerResult.getResult());
378 result.addMessage("Failed to add finalizer information for finalizer named \"" + finalizerEntry.getKey()
379 + "\" in" + " state \"" + stateName + FOR_POLICY + policyName + ":" + policyVersion
380 + POLICY_STATE_CREATED_OTHER_ERROR + " finalizer. The policy has only been partially defined.");
388 * Create the state outputs for the state.
390 * @param session the Apex model editing session
391 * @param policyName the policy name
392 * @param policVersion the policy version
393 * @param stateName the name of the state
394 * @param stateBean the information on the state to create
395 * @return an ApexAPIResult object. If successful then
396 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
397 * can be retrieved using {@link ApexApiResult#getMessages()}
399 private ApexApiResult createStateOutputs(final RestSession session, final String policyName,
400 final String policyVersion, final String stateName, final BeanState stateBean) {
402 ApexApiResult result = new ApexApiResult();
404 final Map<String, BeanStateOutput> stateOutputs = stateBean.getStateOutputs();
405 if (stateOutputs == null || stateOutputs.isEmpty()) {
406 result.setResult(Result.FAILED);
407 result.addMessage("No state outputs have been defined in state \"" + stateName + FOR_POLICY + policyName
408 + ":" + policyVersion + "\". The policy and state were created, but there was an error adding state"
409 + " outputs. The policy has only been partially defined.");
413 for (final Map.Entry<String, BeanStateOutput> stateOutput : stateOutputs.entrySet()) {
414 final String outputName = stateOutput.getKey();
415 final BeanStateOutput output = stateOutput.getValue();
417 if (outputName == null || output == null || output.getEvent() == null) {
418 result.setResult(Result.FAILED);
419 result.addMessage("Null or invalid output information for output named \"" + outputName + IN_STATE
420 + stateName + FOR_POLICY + policyName + ":" + policyVersion + POLICY_STATE_CREATED_OTHER_ERROR
421 + " output. The policy has only been partially defined.");
425 ApexApiResult outputResult = session.getApexModelEdited().createPolicyStateOutput(policyName, policyVersion,
426 stateName, outputName, output.getEvent().getName(), output.getEvent().getVersion(),
427 output.getNextState());
429 if (outputResult.isNok()) {
430 result.setResult(outputResult.getResult());
431 result.addMessage("Failed to add output information for output named \"" + outputName + IN_STATE
432 + stateName + FOR_POLICY + policyName + ":" + policyVersion + POLICY_STATE_CREATED
433 + "but there was an error adding the output." + POLICY_PARTIALLY_DEFINED);
441 * Create the task references for the state.
443 * @param session the Apex model editing session
444 * @param policyName the policy name
445 * @param policVersion the policy version
446 * @param stateName the name of the state
447 * @param stateBean the information on the state to create
448 * @return an ApexAPIResult object. If successful then
449 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
450 * can be retrieved using {@link ApexApiResult#getMessages()}
452 private ApexApiResult createStateTaskReferences(final RestSession session, final String policyName,
453 final String policyVersion, final String stateName, final BeanState stateBean) {
455 ApexApiResult result = new ApexApiResult();
457 final Map<String, BeanStateTaskRef> taskMap = stateBean.getTasks();
458 if (taskMap == null || taskMap.isEmpty()) {
459 result.setResult(Result.FAILED);
460 result.addMessage("No tasks have been defined in state \"" + stateName + FOR_POLICY + policyName + ":"
461 + policyVersion + "\". The policy and state were created, but there was an error adding tasks."
462 + POLICY_PARTIALLY_DEFINED);
466 for (final Map.Entry<String, BeanStateTaskRef> taskEntry : taskMap.entrySet()) {
467 final String taskLocalName = taskEntry.getKey();
468 final BeanStateTaskRef taskReference = taskEntry.getValue();
470 if (taskLocalName == null || taskReference == null || taskReference.getTask() == null) {
471 result.setResult(Result.FAILED);
472 result.addMessage("Null or invalid task information for task named \"" + taskLocalName + IN_STATE
473 + stateName + "\" for for policy \"" + policyName + ":" + policyVersion
474 + "\". The policy and state were created, but there was an error adding the "
475 + "task. The policy has only been partially defined.");
479 ApexApiResult taskRefResult = session.getApexModelEdited().createPolicyStateTaskRef(policyName,
480 policyVersion, stateName, taskLocalName, taskReference.getTask().getName(),
481 taskReference.getTask().getVersion(), taskReference.getOutputType(), taskReference.getOutputName());
483 if (taskRefResult.isNok()) {
484 result.setResult(taskRefResult.getResult());
485 result.addMessage("Failed to add task reference \"" + taskEntry + "\" for state \"" + stateName
486 + FOR_POLICY + policyName + ":" + policyVersion + POLICY_WAS_CREATED
487 + "but there was an error adding the task reference for"
488 + " the state. The policy has only been partially defined.");
496 * Update a policy with the information in the JSON string passed.
498 * @param session the Apex model editing session
499 * @param jsonString the JSON string to be parsed. See {@linkplain BeanPolicy}
500 * @return an ApexAPIResult object. If successful then
501 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
502 * can be retrieved using {@link ApexApiResult#getMessages()}
504 private ApexApiResult updatePolicy(final RestSession session, final String jsonString) {
506 LOGGER.entry(jsonString);
508 final BeanPolicy jsonbean = RestUtils.getJsonParameters(jsonString, BeanPolicy.class);
510 if (blank2Null(jsonbean.getName()) == null || blank2Null(jsonbean.getVersion()) == null) {
511 LOGGER.exit("Task/Update" + NOT_OK);
512 return new ApexApiResult(Result.FAILED, "Null/Empty Policy name/version (\"" + jsonbean.getName() + ":"
513 + jsonbean.getVersion() + "\" passed to UpdatePolicy");
518 ApexApiResult result = session.getApexModelEdited().deletePolicy(jsonbean.getName(), jsonbean.getVersion());
521 result = session.getApexModelEdited().createPolicy(jsonbean.getName(), jsonbean.getVersion(),
522 jsonbean.getTemplate(), jsonbean.getFirstState(), jsonbean.getUuid(), jsonbean.getDescription());
525 result = createPolicyContent(session, jsonbean);
529 session.finishSession(result.isOk());
531 LOGGER.exit("Policy/Update" + (result != null && result.isOk() ? OK : NOT_OK));
537 * List policies with the given key names/versions. If successful the result(s)
538 * will be available in the result messages. The returned value(s) will be
539 * similar to {@link AxPolicy}, with merged {@linkplain AxKey Info} for the root
542 * @param session the Apex model editing session
543 * @param name the name to search for. If null or empty, then all names will
545 * @param version the version to search for. If null then all versions will be
547 * @return an ApexAPIResult object. If successful then
548 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
549 * can be retrieved using {@link ApexApiResult#getMessages()}
551 private ApexApiResult listPolicies(final RestSession session, final String name, final String version) {
552 LOGGER.entry(name, version);
554 ApexApiResult result = session.getApexModel().listPolicy(blank2Null(name), blank2Null(version));
556 LOGGER.exit("Policy/Get" + (result != null && result.isOk() ? OK : NOT_OK));
561 * Delete policies with the given key names/versions.
563 * @param session the Apex model editing session
564 * @param name the name to search for. If null or empty, then all names will
566 * @param version the version to search for. If null then all versions will be
568 * @return an ApexAPIResult object. If successful then
569 * {@link ApexApiResult#isOk()} will return true. Any messages/errors
570 * can be retrieved using {@link ApexApiResult#getMessages()}
572 private ApexApiResult deletePolicy(final RestSession session, final String name, final String version) {
573 LOGGER.entry(name, version);
577 // all input/output fields, parameters, logic, context references is
580 // deleting the task removes all of these
581 ApexApiResult result = session.getApexModelEdited().deletePolicy(blank2Null(name), blank2Null(version));
583 session.finishSession(result.isOk());
585 LOGGER.exit("Policy/Delete" + (result != null && result.isOk() ? OK : NOT_OK));