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;
24 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanKeyRef;
25 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanLogic;
26 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanPolicy;
27 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanState;
28 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanStateOutput;
29 import org.onap.policy.apex.client.editor.rest.handling.bean.BeanStateTaskRef;
30 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
31 import org.onap.policy.apex.model.modelapi.ApexApiResult;
32 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
33 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
34 import org.slf4j.ext.XLogger;
35 import org.slf4j.ext.XLoggerFactory;
38 * This class handles commands on policies in Apex models.
40 public class PolicyHandler implements RestCommandHandler {
41 // Get a reference to the logger
42 private static final XLogger LOGGER = XLoggerFactory.getXLogger(PolicyHandler.class);
44 // Recurring string constants
45 private static final String OK = ": OK";
46 private static final String NOT_OK = ": Not OK";
47 private static final String POLICY_WAS_CREATED = "\". The policy was created, ";
48 private static final String POLICY_STATE_CREATED = "\". The policy and state were created, ";
49 private static final String POLICY_PARTIALLY_DEFINED = " The policy has only been partially defined.";
50 private static final String FOR_POLICY = "\" for policy \"";
51 private static final String IN_STATE = "\" in state \"";
52 private static final String POLICY_CREATED_STATE_ERROR = POLICY_WAS_CREATED
53 + "but there was an error adding the state.";
54 private static final String POLICY_STATE_CREATED_OTHER_ERROR = POLICY_STATE_CREATED
55 + "but there was an error adding the";
61 public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
62 final RestCommand command) {
63 return getUnsupportedCommandResultMessage(session, commandType, command);
70 public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
71 final RestCommand command, final String jsonString) {
73 if (!RestCommandType.POLICY.equals(commandType)) {
74 return getUnsupportedCommandResultMessage(session, commandType, command);
79 return createPolicy(session, jsonString);
81 return updatePolicy(session, jsonString);
83 return getUnsupportedCommandResultMessage(session, commandType, command);
91 public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
92 final RestCommand command, final String name, final String version) {
93 if (!RestCommandType.POLICY.equals(commandType)) {
94 return getUnsupportedCommandResultMessage(session, commandType, command);
99 return listPolicies(session, name, version);
101 return deletePolicy(session, name, version);
103 return getUnsupportedCommandResultMessage(session, commandType, command);
108 * Creates a policy with the information in the JSON string passed.
110 * @param session the Apex model editing session
111 * @param jsonString the JSON string to be parsed See {@linkplain BeanPolicy}
112 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
113 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
115 public ApexApiResult createPolicy(final RestSession session, final String jsonString) {
116 LOGGER.entry(jsonString);
118 final BeanPolicy jsonbean = RestUtils.getJsonParameters(jsonString, BeanPolicy.class);
122 ApexApiResult result = session.getApexModelEdited().createPolicy(jsonbean.getName(), jsonbean.getVersion(),
123 jsonbean.getTemplate(), jsonbean.getFirstState(), jsonbean.getUuid(),
124 jsonbean.getDescription());
127 result = createPolicyContent(session, jsonbean);
130 session.finishSession(result.isOk());
132 LOGGER.exit("Policy/Create" + (result != null && result.isOk() ? OK : NOT_OK));
137 * Create the content of the policy.
139 * @param session the Apex model editing session
140 * @param jsonString the JSON string to be parsed See {@linkplain BeanPolicy}
141 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
142 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
144 private ApexApiResult createPolicyContent(RestSession session, BeanPolicy jsonbean) {
145 ApexApiResult result = new ApexApiResult();
147 if (jsonbean.getStates() == null || jsonbean.getStates().isEmpty()) {
148 result.setResult(Result.FAILED);
149 result.addMessage("Null or empty state map; no states defined for policy \"" + jsonbean.getName() + ":"
150 + jsonbean.getVersion()
151 + "\". The policy was created, but there was an error adding states."
152 + POLICY_PARTIALLY_DEFINED);
156 // States reference each other so all states must be created before they are populated
157 for (final Map.Entry<String, BeanState> stateEntry : jsonbean.getStates().entrySet()) {
158 ApexApiResult stateCreateResult = createState(session, jsonbean.getName(), jsonbean.getVersion(),
159 stateEntry.getKey(), stateEntry.getValue());
161 if (stateCreateResult.isNok()) {
162 result.setResult(stateCreateResult.getResult());
163 result.addMessage(stateCreateResult.getMessage());
167 // Bale out if the state creation did not work
168 if (result.isNok()) {
172 // Now create the content of each state
173 for (final Map.Entry<String, BeanState> stateEntry : jsonbean.getStates().entrySet()) {
174 ApexApiResult stateContentCreateResult = createStateContent(session, jsonbean.getName(),
175 jsonbean.getVersion(), stateEntry.getKey(), stateEntry.getValue());
177 if (stateContentCreateResult.isNok()) {
178 result.setResult(stateContentCreateResult.getResult());
179 result.addMessage(stateContentCreateResult.getMessage());
187 * Create a state on the policy.
189 * @param session the Apex model editing session
190 * @param policyName the policy name
191 * @param policVersion the policy version
192 * @param stateName the name of the state
193 * @param stateBean the information on the state to create
194 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
195 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
197 private ApexApiResult createState(final RestSession session, final String policyName, final String policyVersion,
198 final String stateName, final BeanState stateBean) {
200 if (stateBean == null) {
201 return new ApexApiResult(Result.FAILED,
202 "Null or invalid state information for state \"" + stateName + FOR_POLICY + policyName + ":"
203 + policyVersion + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
206 if (stateBean.getTrigger() == null) {
207 return new ApexApiResult(Result.FAILED,
208 "Null or invalid state trigger for state \"" + stateName + FOR_POLICY + policyName + ":"
209 + policyVersion + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
212 if (stateBean.getDefaultTask() == null) {
213 return new ApexApiResult(Result.FAILED, "Null or invalid default task for state \"" + stateName + FOR_POLICY
214 + policyName + ":" + policyVersion + POLICY_CREATED_STATE_ERROR + POLICY_PARTIALLY_DEFINED);
217 return session.getApexModelEdited().createPolicyState(policyName, policyVersion, stateName,
218 stateBean.getTrigger().getName(), stateBean.getTrigger().getVersion(),
219 stateBean.getDefaultTask().getName(), stateBean.getDefaultTask().getVersion());
223 * Create the content of a state on the policy.
225 * @param session the Apex model editing session
226 * @param policyName the policy name
227 * @param policVersion the policy version
228 * @param stateName the name of the state
229 * @param stateBean the information on the state to create
230 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
231 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
233 private ApexApiResult createStateContent(final RestSession session, final String policyName,
234 final String policyVersion, final String stateName, final BeanState stateBean) {
236 ApexApiResult ret = createStateTaskSelectionLogic(session, policyName, policyVersion, stateName, stateBean);
239 ret = createStateContextReferences(session, policyName, policyVersion, stateName, stateBean);
243 ret = createStateFinalizers(session, policyName, policyVersion, stateName, stateBean);
247 ret = createStateOutputs(session, policyName, policyVersion, stateName, stateBean);
251 ret = createStateTaskReferences(session, policyName, policyVersion, stateName, stateBean);
258 * Create the task selection logic for the state.
260 * @param session the Apex model editing session
261 * @param policyName the policy name
262 * @param policVersion the policy version
263 * @param stateName the name of the state
264 * @param stateBean the information on the state to create
265 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
266 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
268 private ApexApiResult createStateTaskSelectionLogic(final RestSession session, final String policyName,
269 final String policyVersion, final String stateName, final BeanState stateBean) {
271 final BeanLogic tsl = stateBean.getTaskSelectionLogic();
273 return new ApexApiResult();
276 ApexApiResult result = session.getApexModelEdited().createPolicyStateTaskSelectionLogic(policyName,
277 policyVersion, stateName, tsl.getLogicFlavour(), tsl.getLogic());
279 if (result.isNok()) {
280 result.addMessage("Failed to add task selection logic for state \"" + stateName + "\" for" + " policy \""
281 + policyName + ":" + policyVersion + POLICY_WAS_CREATED
282 + "but there was an error adding the task selection logic "
283 + "for the state. The policy has only been partially defined.");
289 * Create the context references for the state.
291 * @param session the Apex model editing session
292 * @param policyName the policy name
293 * @param policVersion the policy version
294 * @param stateName the name of the state
295 * @param stateBean the information on the state to create
296 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
297 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
299 private ApexApiResult createStateContextReferences(final RestSession session, final String policyName,
300 final String policyVersion, final String stateName, final BeanState stateBean) {
302 ApexApiResult result = new ApexApiResult();
304 final BeanKeyRef[] contextReferences = stateBean.getContexts();
305 if (contextReferences == null || contextReferences.length == 0) {
309 for (final BeanKeyRef contextReference : contextReferences) {
310 if (contextReference == null) {
311 result.setResult(Result.FAILED);
312 result.addMessage("Null or invalid context reference \"" + contextReference + "\" for" + " state \""
313 + stateName + FOR_POLICY + policyName + ":" + policyVersion
314 + "\". The policy was created, but there was an error adding the context "
315 + "reference for the state. The policy has only been partially defined.");
319 ApexApiResult contextRefResult = session.getApexModelEdited().createPolicyStateContextRef(policyName,
320 policyVersion, stateName, contextReference.getName(), contextReference.getVersion());
322 if (contextRefResult.isNok()) {
323 result.setResult(contextRefResult.getResult());
324 result.addMessage("Failed to add context reference \"" + contextReference + "\" for state \""
325 + stateName + FOR_POLICY + policyName + ":" + policyVersion + POLICY_WAS_CREATED
326 + "but there was an error adding the context reference "
327 + "for the state. The policy has only been partially defined.");
335 * Create the state finalizers for the state.
337 * @param session the Apex model editing session
338 * @param policyName the policy name
339 * @param policVersion the policy version
340 * @param stateName the name of the state
341 * @param stateBean the information on the state to create
342 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
343 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
345 private ApexApiResult createStateFinalizers(final RestSession session, final String policyName,
346 final String policyVersion, final String stateName, final BeanState stateBean) {
348 ApexApiResult result = new ApexApiResult();
350 final Map<String, BeanLogic> finalizers = stateBean.getFinalizers();
351 if (finalizers == null || finalizers.isEmpty()) {
355 for (final Map.Entry<String, BeanLogic> finalizerEntry : finalizers.entrySet()) {
356 if (finalizerEntry.getKey() == null || finalizerEntry.getValue() == null) {
357 result.setResult(Result.FAILED);
358 result.addMessage("Null or invalid finalizer information for finalizer " + "named \""
359 + finalizerEntry.getKey() + IN_STATE + stateName + FOR_POLICY + policyName + ":"
360 + policyVersion + POLICY_STATE_CREATED_OTHER_ERROR + " finalizer. The policy has only "
361 + "been partially defined.");
365 ApexApiResult finalizerResult = session.getApexModelEdited().createPolicyStateFinalizerLogic(policyName,
366 policyVersion, stateName, finalizerEntry.getKey(),
367 finalizerEntry.getValue().getLogicFlavour(), finalizerEntry.getValue().getLogic());
369 if (finalizerResult.isNok()) {
370 result.setResult(finalizerResult.getResult());
371 result.addMessage("Failed to add finalizer information for finalizer named \"" + finalizerEntry.getKey()
372 + "\" in" + " state \"" + stateName + FOR_POLICY + policyName + ":" + policyVersion
373 + POLICY_STATE_CREATED_OTHER_ERROR
374 + " finalizer. The policy has only been partially defined.");
382 * Create the state outputs for the state.
384 * @param session the Apex model editing session
385 * @param policyName the policy name
386 * @param policVersion the policy version
387 * @param stateName the name of the state
388 * @param stateBean the information on the state to create
389 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
390 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
392 private ApexApiResult createStateOutputs(final RestSession session, final String policyName,
393 final String policyVersion, final String stateName, final BeanState stateBean) {
395 ApexApiResult result = new ApexApiResult();
397 final Map<String, BeanStateOutput> stateOutputs = stateBean.getStateOutputs();
398 if (stateOutputs == null || stateOutputs.isEmpty()) {
399 result.setResult(Result.FAILED);
400 result.addMessage("No state outputs have been defined in state \"" + stateName + FOR_POLICY + policyName
401 + ":" + policyVersion
402 + "\". The policy and state were created, but there was an error adding state"
403 + " outputs. The policy has only been partially defined.");
407 for (final Map.Entry<String, BeanStateOutput> stateOutput : stateOutputs.entrySet()) {
408 final String outputName = stateOutput.getKey();
409 final BeanStateOutput output = stateOutput.getValue();
411 if (outputName == null || output == null || output.getEvent() == null) {
412 result.setResult(Result.FAILED);
413 result.addMessage("Null or invalid output information for output named \"" + outputName + IN_STATE
414 + stateName + FOR_POLICY + policyName + ":" + policyVersion
415 + POLICY_STATE_CREATED_OTHER_ERROR
416 + " output. The policy has only been partially defined.");
420 ApexApiResult outputResult = session.getApexModelEdited().createPolicyStateOutput(policyName, policyVersion,
421 stateName, outputName, output.getEvent().getName(), output.getEvent().getVersion(),
422 output.getNextState());
424 if (outputResult.isNok()) {
425 result.setResult(outputResult.getResult());
426 result.addMessage("Failed to add output information for output named \"" + outputName + IN_STATE
427 + stateName + FOR_POLICY + policyName + ":" + policyVersion + POLICY_STATE_CREATED
428 + "but there was an error adding the output." + POLICY_PARTIALLY_DEFINED);
436 * Create the task references for the state.
438 * @param session the Apex model editing session
439 * @param policyName the policy name
440 * @param policVersion the policy version
441 * @param stateName the name of the state
442 * @param stateBean the information on the state to create
443 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
444 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
446 private ApexApiResult createStateTaskReferences(final RestSession session, final String policyName,
447 final String policyVersion, final String stateName, final BeanState stateBean) {
449 ApexApiResult result = new ApexApiResult();
451 final Map<String, BeanStateTaskRef> taskMap = stateBean.getTasks();
452 if (taskMap == null || taskMap.isEmpty()) {
453 result.setResult(Result.FAILED);
454 result.addMessage("No tasks have been defined in state \"" + stateName + FOR_POLICY + policyName + ":"
456 + "\". The policy and state were created, but there was an error adding tasks."
457 + POLICY_PARTIALLY_DEFINED);
461 for (final Map.Entry<String, BeanStateTaskRef> taskEntry : taskMap.entrySet()) {
462 final String taskLocalName = taskEntry.getKey();
463 final BeanStateTaskRef taskReference = taskEntry.getValue();
465 if (taskLocalName == null || taskReference == null || taskReference.getTask() == null) {
466 result.setResult(Result.FAILED);
467 result.addMessage("Null or invalid task information for task named \"" + taskLocalName + IN_STATE
468 + stateName + "\" for for policy \"" + policyName + ":" + policyVersion
469 + "\". The policy and state were created, but there was an error adding the "
470 + "task. The policy has only been partially defined.");
474 ApexApiResult taskRefResult = session.getApexModelEdited().createPolicyStateTaskRef(policyName,
475 policyVersion, stateName, taskLocalName, taskReference.getTask().getName(),
476 taskReference.getTask().getVersion(), taskReference.getOutputType(),
477 taskReference.getOutputName());
479 if (taskRefResult.isNok()) {
480 result.setResult(taskRefResult.getResult());
481 result.addMessage("Failed to add task reference \"" + taskEntry + "\" for state \"" + stateName
482 + FOR_POLICY + policyName + ":" + policyVersion + POLICY_WAS_CREATED
483 + "but there was an error adding the task reference for"
484 + " the state. The policy has only been partially defined.");
492 * Update a policy with the information in the JSON string passed.
494 * @param session the Apex model editing session
495 * @param jsonString the JSON string to be parsed. See {@linkplain BeanPolicy}
496 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
497 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
499 private ApexApiResult updatePolicy(final RestSession session, final String jsonString) {
501 LOGGER.entry(jsonString);
503 final BeanPolicy jsonbean = RestUtils.getJsonParameters(jsonString, BeanPolicy.class);
505 if (blank2Null(jsonbean.getName()) == null || blank2Null(jsonbean.getVersion()) == null) {
506 LOGGER.exit("Task/Update" + NOT_OK);
507 return new ApexApiResult(Result.FAILED, "Null/Empty Policy name/version (\"" + jsonbean.getName() + ":"
508 + jsonbean.getVersion() + "\" passed to UpdatePolicy");
513 ApexApiResult result = session.getApexModelEdited().deletePolicy(jsonbean.getName(), jsonbean.getVersion());
516 result = session.getApexModelEdited().createPolicy(jsonbean.getName(), jsonbean.getVersion(),
517 jsonbean.getTemplate(), jsonbean.getFirstState(), jsonbean.getUuid(),
518 jsonbean.getDescription());
521 result = createPolicyContent(session, jsonbean);
525 session.finishSession(result.isOk());
527 LOGGER.exit("Policy/Update" + (result != null && result.isOk() ? OK : NOT_OK));
533 * List policies with the given key names/versions. If successful the result(s) will be available in the result
534 * messages. The returned value(s) will be similar to {@link AxPolicy}, with merged {@linkplain AxKey Info} for the
537 * @param session the Apex model editing session
538 * @param name the name to search for. If null or empty, then all names will be queried
539 * @param version the version to search for. If null then all versions will be searched for.
540 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
541 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
543 private ApexApiResult listPolicies(final RestSession session, final String name, final String version) {
544 LOGGER.entry(name, version);
546 ApexApiResult result = session.getApexModel().listPolicy(blank2Null(name), blank2Null(version));
548 LOGGER.exit("Policy/Get" + (result != null && result.isOk() ? OK : NOT_OK));
553 * Delete policies with the given key names/versions.
555 * @param session the Apex model editing session
556 * @param name the name to search for. If null or empty, then all names will be queried
557 * @param version the version to search for. If null then all versions will be searched for.
558 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
559 * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
561 private ApexApiResult deletePolicy(final RestSession session, final String name, final String version) {
562 LOGGER.entry(name, version);
566 // all input/output fields, parameters, logic, context references is "owned"/contained
568 // deleting the task removes all of these
569 ApexApiResult result = session.getApexModelEdited().deletePolicy(blank2Null(name), blank2Null(version));
571 session.finishSession(result.isOk());
573 LOGGER.exit("Policy/Delete" + (result != null && result.isOk() ? OK : NOT_OK));