2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2018 Ericsson. All rights reserved.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.client.editor.rest.handling;
25 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanKeyRef;
26 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanLogic;
27 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanPolicy;
28 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanState;
29 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanStateOutput;
30 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanStateTaskRef;
31 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
32 import org.onap.policy.apex.model.modelapi.ApexApiResult;
33 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
34 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
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 {@link ApexApiResult#isOk()} will return true. Any
114 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
116 public ApexApiResult createPolicy(final RestSession session, final String jsonString) {
117 LOGGER.entry(jsonString);
119 final BeanPolicy jsonbean = RestUtils.getJsonParameters(jsonString, BeanPolicy.class);
123 ApexApiResult result = session.getApexModelEdited().createPolicy(jsonbean.getName(), jsonbean.getVersion(),
124 jsonbean.getTemplate(), jsonbean.getFirstState(), jsonbean.getUuid(),
125 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 {@link ApexApiResult#isOk()} will return true. Any
143 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
145 private ApexApiResult createPolicyContent(RestSession session, BeanPolicy jsonbean) {
146 ApexApiResult result = new ApexApiResult();
148 if (jsonbean.getStates() == null || jsonbean.getStates().isEmpty()) {
149 result.setResult(Result.FAILED);
150 result.addMessage("Null or empty state map; no states defined for policy \"" + jsonbean.getName() + ":"
151 + jsonbean.getVersion()
152 + "\". 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 populated
158 for (final Map.Entry<String, BeanState> stateEntry : jsonbean.getStates().entrySet()) {
159 ApexApiResult stateCreateResult = createState(session, jsonbean.getName(), jsonbean.getVersion(),
160 stateEntry.getKey(), stateEntry.getValue());
162 if (stateCreateResult.isNok()) {
163 result.setResult(stateCreateResult.getResult());
164 result.addMessage(stateCreateResult.getMessage());
168 // Bale out if the state creation did not work
169 if (result.isNok()) {
173 // Now create the content of each state
174 for (final Map.Entry<String, BeanState> stateEntry : jsonbean.getStates().entrySet()) {
175 ApexApiResult stateContentCreateResult = createStateContent(session, jsonbean.getName(),
176 jsonbean.getVersion(), stateEntry.getKey(), stateEntry.getValue());
178 if (stateContentCreateResult.isNok()) {
179 result.setResult(stateContentCreateResult.getResult());
180 result.addMessage(stateContentCreateResult.getMessage());
188 * Create a state on the policy.
190 * @param session the Apex model editing session
191 * @param policyName the policy name
192 * @param policVersion the policy version
193 * @param stateName the name of the state
194 * @param stateBean the information on the state to create
195 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
196 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
198 private ApexApiResult createState(final RestSession session, final String policyName, final String policyVersion,
199 final String stateName, final BeanState stateBean) {
201 if (stateBean == null) {
202 return new ApexApiResult(Result.FAILED,
203 "Null or invalid state information for state \"" + stateName + FOR_POLICY + policyName + ":"
204 + policyVersion + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
207 if (stateBean.getTrigger() == null) {
208 return new ApexApiResult(Result.FAILED,
209 "Null or invalid state trigger for state \"" + stateName + FOR_POLICY + policyName + ":"
210 + policyVersion + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
213 if (stateBean.getDefaultTask() == null) {
214 return new ApexApiResult(Result.FAILED, "Null or invalid default task for state \"" + stateName + FOR_POLICY
215 + policyName + ":" + policyVersion + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
218 return session.getApexModelEdited().createPolicyState(policyName, policyVersion, stateName,
219 stateBean.getTrigger().getName(), stateBean.getTrigger().getVersion(),
220 stateBean.getDefaultTask().getName(), stateBean.getDefaultTask().getVersion());
224 * Create the content of a state on the policy.
226 * @param session the Apex model editing session
227 * @param policyName the policy name
228 * @param policVersion the policy version
229 * @param stateName the name of the state
230 * @param stateBean the information on the state to create
231 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
232 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
234 private ApexApiResult createStateContent(final RestSession session, final String policyName,
235 final String policyVersion, final String stateName, final BeanState stateBean) {
237 ApexApiResult ret = createStateTaskSelectionLogic(session, policyName, policyVersion, stateName, stateBean);
240 ret = createStateContextReferences(session, policyName, policyVersion, stateName, stateBean);
244 ret = createStateFinalizers(session, policyName, policyVersion, stateName, stateBean);
248 ret = createStateOutputs(session, policyName, policyVersion, stateName, stateBean);
252 ret = createStateTaskReferences(session, policyName, policyVersion, stateName, stateBean);
259 * Create the task selection logic for the state.
261 * @param session the Apex model editing session
262 * @param policyName the policy name
263 * @param policVersion the policy version
264 * @param stateName the name of the state
265 * @param stateBean the information on the state to create
266 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
267 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
269 private ApexApiResult createStateTaskSelectionLogic(final RestSession session, final String policyName,
270 final String policyVersion, final String stateName, final BeanState stateBean) {
272 final BeanLogic tsl = stateBean.getTaskSelectionLogic();
274 return new ApexApiResult();
277 ApexApiResult result = session.getApexModelEdited().createPolicyStateTaskSelectionLogic(policyName,
278 policyVersion, stateName, tsl.getLogicFlavour(), tsl.getLogic());
280 if (result.isNok()) {
281 result.addMessage("Failed to add task selection logic for state \"" + stateName + "\" for" + " policy \""
282 + policyName + ":" + policyVersion + POLICY_WAS_CREATED
283 + "but there was an error adding the task selection logic "
284 + "for the state. The policy has only been partially defined.");
290 * Create the context references for the state.
292 * @param session the Apex model editing session
293 * @param policyName the policy name
294 * @param policVersion the policy version
295 * @param stateName the name of the state
296 * @param stateBean the information on the state to create
297 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
298 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
300 private ApexApiResult createStateContextReferences(final RestSession session, final String policyName,
301 final String policyVersion, final String stateName, final BeanState stateBean) {
303 ApexApiResult result = new ApexApiResult();
305 final BeanKeyRef[] contextReferences = stateBean.getContexts();
306 if (contextReferences == null || contextReferences.length == 0) {
310 for (final BeanKeyRef contextReference : contextReferences) {
311 if (contextReference == null) {
312 result.setResult(Result.FAILED);
313 result.addMessage("Null or invalid context reference \"" + contextReference + "\" for" + " state \""
314 + stateName + FOR_POLICY + policyName + ":" + policyVersion
315 + "\". The policy was created, but there was an error adding the context "
316 + "reference for the state. The policy has only been partially defined.");
320 ApexApiResult contextRefResult = session.getApexModelEdited().createPolicyStateContextRef(policyName,
321 policyVersion, stateName, contextReference.getName(), contextReference.getVersion());
323 if (contextRefResult.isNok()) {
324 result.setResult(contextRefResult.getResult());
325 result.addMessage("Failed to add context reference \"" + contextReference + "\" for state \""
326 + stateName + FOR_POLICY + policyName + ":" + policyVersion + POLICY_WAS_CREATED
327 + "but there was an error adding the context reference "
328 + "for the state. The policy has only been partially defined.");
336 * Create the state finalizers for the state.
338 * @param session the Apex model editing session
339 * @param policyName the policy name
340 * @param policVersion the policy version
341 * @param stateName the name of the state
342 * @param stateBean the information on the state to create
343 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
344 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
346 private ApexApiResult createStateFinalizers(final RestSession session, final String policyName,
347 final String policyVersion, final String stateName, final BeanState stateBean) {
349 ApexApiResult result = new ApexApiResult();
351 final Map<String, BeanLogic> finalizers = stateBean.getFinalizers();
352 if (finalizers == null || finalizers.isEmpty()) {
356 for (final Map.Entry<String, BeanLogic> finalizerEntry : finalizers.entrySet()) {
357 if (finalizerEntry.getKey() == null || finalizerEntry.getValue() == null) {
358 result.setResult(Result.FAILED);
359 result.addMessage("Null or invalid finalizer information for finalizer " + "named \""
360 + finalizerEntry.getKey() + IN_STATE + stateName + FOR_POLICY + policyName + ":"
361 + policyVersion + POLICY_STATE_CREATED_OTHER_ERROR + " finalizer. The policy has only "
362 + "been partially defined.");
366 ApexApiResult finalizerResult = session.getApexModelEdited().createPolicyStateFinalizerLogic(policyName,
367 policyVersion, stateName, finalizerEntry.getKey(),
368 finalizerEntry.getValue().getLogicFlavour(), finalizerEntry.getValue().getLogic());
370 if (finalizerResult.isNok()) {
371 result.setResult(finalizerResult.getResult());
372 result.addMessage("Failed to add finalizer information for finalizer named \"" + finalizerEntry.getKey()
373 + "\" in" + " state \"" + stateName + FOR_POLICY + policyName + ":" + policyVersion
374 + POLICY_STATE_CREATED_OTHER_ERROR
375 + " finalizer. The policy has only been partially defined.");
383 * Create the state outputs for the state.
385 * @param session the Apex model editing session
386 * @param policyName the policy name
387 * @param policVersion the policy version
388 * @param stateName the name of the state
389 * @param stateBean the information on the state to create
390 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
391 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
393 private ApexApiResult createStateOutputs(final RestSession session, final String policyName,
394 final String policyVersion, final String stateName, final BeanState stateBean) {
396 ApexApiResult result = new ApexApiResult();
398 final Map<String, BeanStateOutput> stateOutputs = stateBean.getStateOutputs();
399 if (stateOutputs == null || stateOutputs.isEmpty()) {
400 result.setResult(Result.FAILED);
401 result.addMessage("No state outputs have been defined in state \"" + stateName + FOR_POLICY + policyName
402 + ":" + policyVersion
403 + "\". The policy and state were created, but there was an error adding state"
404 + " outputs. The policy has only been partially defined.");
408 for (final Map.Entry<String, BeanStateOutput> stateOutput : stateOutputs.entrySet()) {
409 final String outputName = stateOutput.getKey();
410 final BeanStateOutput output = stateOutput.getValue();
412 if (outputName == null || output == null || output.getEvent() == null) {
413 result.setResult(Result.FAILED);
414 result.addMessage("Null or invalid output information for output named \"" + outputName + IN_STATE
415 + stateName + FOR_POLICY + policyName + ":" + policyVersion
416 + POLICY_STATE_CREATED_OTHER_ERROR
417 + " output. The policy has only been partially defined.");
421 ApexApiResult outputResult = session.getApexModelEdited().createPolicyStateOutput(policyName, policyVersion,
422 stateName, outputName, output.getEvent().getName(), output.getEvent().getVersion(),
423 output.getNextState());
425 if (outputResult.isNok()) {
426 result.setResult(outputResult.getResult());
427 result.addMessage("Failed to add output information for output named \"" + outputName + IN_STATE
428 + stateName + FOR_POLICY + policyName + ":" + policyVersion + POLICY_STATE_CREATED
429 + "but there was an error adding the output." + POLICY_PARTIALLY_DEFINED);
437 * Create the task references for the state.
439 * @param session the Apex model editing session
440 * @param policyName the policy name
441 * @param policVersion the policy version
442 * @param stateName the name of the state
443 * @param stateBean the information on the state to create
444 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
445 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
447 private ApexApiResult createStateTaskReferences(final RestSession session, final String policyName,
448 final String policyVersion, final String stateName, final BeanState stateBean) {
450 ApexApiResult result = new ApexApiResult();
452 final Map<String, BeanStateTaskRef> taskMap = stateBean.getTasks();
453 if (taskMap == null || taskMap.isEmpty()) {
454 result.setResult(Result.FAILED);
455 result.addMessage("No tasks have been defined in state \"" + stateName + FOR_POLICY + policyName + ":"
457 + "\". The policy and state were created, but there was an error adding tasks."
458 + POLICY_PARTIALLY_DEFINED);
462 for (final Map.Entry<String, BeanStateTaskRef> taskEntry : taskMap.entrySet()) {
463 final String taskLocalName = taskEntry.getKey();
464 final BeanStateTaskRef taskReference = taskEntry.getValue();
466 if (taskLocalName == null || taskReference == null || taskReference.getTask() == null) {
467 result.setResult(Result.FAILED);
468 result.addMessage("Null or invalid task information for task named \"" + taskLocalName + IN_STATE
469 + stateName + "\" for for policy \"" + policyName + ":" + policyVersion
470 + "\". The policy and state were created, but there was an error adding the "
471 + "task. The policy has only been partially defined.");
475 ApexApiResult taskRefResult = session.getApexModelEdited().createPolicyStateTaskRef(policyName,
476 policyVersion, stateName, taskLocalName, taskReference.getTask().getName(),
477 taskReference.getTask().getVersion(), taskReference.getOutputType(),
478 taskReference.getOutputName());
480 if (taskRefResult.isNok()) {
481 result.setResult(taskRefResult.getResult());
482 result.addMessage("Failed to add task reference \"" + taskEntry + "\" for state \"" + stateName
483 + FOR_POLICY + policyName + ":" + policyVersion + POLICY_WAS_CREATED
484 + "but there was an error adding the task reference for"
485 + " the state. The policy has only been partially defined.");
493 * Update a policy with the information in the JSON string passed.
495 * @param session the Apex model editing session
496 * @param jsonString the JSON string to be parsed. See {@linkplain BeanPolicy}
497 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
498 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
500 private ApexApiResult updatePolicy(final RestSession session, final String jsonString) {
502 LOGGER.entry(jsonString);
504 final BeanPolicy jsonbean = RestUtils.getJsonParameters(jsonString, BeanPolicy.class);
506 if (blank2Null(jsonbean.getName()) == null || blank2Null(jsonbean.getVersion()) == null) {
507 LOGGER.exit("Task/Update" + NOT_OK);
508 return new ApexApiResult(Result.FAILED, "Null/Empty Policy name/version (\"" + jsonbean.getName() + ":"
509 + jsonbean.getVersion() + "\" passed to UpdatePolicy");
514 ApexApiResult result = session.getApexModelEdited().deletePolicy(jsonbean.getName(), jsonbean.getVersion());
517 result = session.getApexModelEdited().createPolicy(jsonbean.getName(), jsonbean.getVersion(),
518 jsonbean.getTemplate(), jsonbean.getFirstState(), jsonbean.getUuid(),
519 jsonbean.getDescription());
522 result = createPolicyContent(session, jsonbean);
526 session.finishSession(result.isOk());
528 LOGGER.exit("Policy/Update" + (result != null && result.isOk() ? OK : NOT_OK));
534 * List policies with the given key names/versions. If successful the result(s) will be available in the result
535 * messages. The returned value(s) will be similar to {@link AxPolicy}, with merged {@linkplain AxKey Info} for the
538 * @param session the Apex model editing session
539 * @param name the name to search for. If null or empty, then all names will be queried
540 * @param version the version to search for. If null then all versions will be searched for.
541 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
542 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
544 private ApexApiResult listPolicies(final RestSession session, final String name, final String version) {
545 LOGGER.entry(name, version);
547 ApexApiResult result = session.getApexModel().listPolicy(blank2Null(name), blank2Null(version));
549 LOGGER.exit("Policy/Get" + (result != null && result.isOk() ? OK : NOT_OK));
554 * Delete policies with the given key names/versions.
556 * @param session the Apex model editing session
557 * @param name the name to search for. If null or empty, then all names will be queried
558 * @param version the version to search for. If null then all versions will be searched for.
559 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
560 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
562 private ApexApiResult deletePolicy(final RestSession session, final String name, final String version) {
563 LOGGER.entry(name, version);
567 // all input/output fields, parameters, logic, context references is "owned"/contained
569 // deleting the task removes all of these
570 ApexApiResult result = session.getApexModelEdited().deletePolicy(blank2Null(name), blank2Null(version));
572 session.finishSession(result.isOk());
574 LOGGER.exit("Policy/Delete" + (result != null && result.isOk() ? OK : NOT_OK));