2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-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;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonObject;
27 import java.util.ArrayList;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.TreeMap;
33 import javax.ws.rs.Consumes;
34 import javax.ws.rs.DELETE;
35 import javax.ws.rs.GET;
36 import javax.ws.rs.POST;
37 import javax.ws.rs.PUT;
38 import javax.ws.rs.Path;
39 import javax.ws.rs.PathParam;
40 import javax.ws.rs.Produces;
41 import javax.ws.rs.QueryParam;
42 import javax.ws.rs.core.MediaType;
44 import org.onap.policy.apex.client.editor.rest.bean.BeanContextAlbum;
45 import org.onap.policy.apex.client.editor.rest.bean.BeanContextSchema;
46 import org.onap.policy.apex.client.editor.rest.bean.BeanEvent;
47 import org.onap.policy.apex.client.editor.rest.bean.BeanField;
48 import org.onap.policy.apex.client.editor.rest.bean.BeanKeyRef;
49 import org.onap.policy.apex.client.editor.rest.bean.BeanLogic;
50 import org.onap.policy.apex.client.editor.rest.bean.BeanModel;
51 import org.onap.policy.apex.client.editor.rest.bean.BeanPolicy;
52 import org.onap.policy.apex.client.editor.rest.bean.BeanState;
53 import org.onap.policy.apex.client.editor.rest.bean.BeanStateOutput;
54 import org.onap.policy.apex.client.editor.rest.bean.BeanStateTaskRef;
55 import org.onap.policy.apex.client.editor.rest.bean.BeanTask;
56 import org.onap.policy.apex.client.editor.rest.bean.BeanTaskParameter;
57 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
58 import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo;
59 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
60 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
61 import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
62 import org.onap.policy.apex.model.modelapi.ApexApiResult;
63 import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
64 import org.onap.policy.apex.model.modelapi.ApexModel;
65 import org.onap.policy.apex.model.modelapi.ApexModelFactory;
66 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
67 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
68 import org.onap.policy.apex.model.policymodel.concepts.AxTask;
69 import org.slf4j.ext.XLogger;
70 import org.slf4j.ext.XLoggerFactory;
73 * The class represents the root resource exposed at the base URL<br>
74 * The url to access this resource would be in the form {@code <baseURL>/rest/<session>/....} <br>
75 * For example: a PUT request to the following URL
76 * {@code http://localhost:8080/apex/rest/109/ContextSchema/Update}, with a JSON string payload
77 * containing the new {@code Schema} in the body, can be explained as:
79 * <li>The server or servlet is running at the base URL {@code http://localhost:8080/apex}
80 * <li>This resource {@code ApexRestEditorResource} is used because the path {@code rest/109}
81 * matches the {@code Path} filter specification for this Resource
82 * ({@code @Path("rest/{session}")}), where the {@code int} path parameter {@code session} is
83 * assigned the {@code int} value {@code 109}
84 * <li>The path {@code ContextSchema/Update} redirects this call to the method
85 * {@link #updateContextSchema(String)}, which should be a {@link javax.ws.rs.PUT}, with a single
86 * String in the body/payload which gets mapped to the single String parameter for the method.
87 * <li>So, in summary, the REST request updates a {@code ContextSchema} as specified in the payload
88 * for {@code session} number {@code 109}
91 * <b>Note:</b> An allocated {@code Session} identifier must be included in (almost) all requests.
92 * Models for different {@code Session} identifiers are completely isolated from one another.
94 * <b>Note:</b> To create a new {@code Session}, and have a new session ID allocated use
95 * {@link javax.ws.rs.GET} request to {@code <baseURL>/rest/-1/Session/Create} (for example:
96 * {@code http://localhost:8080/apex/rest/-1/Session/Create} )
99 @Path("editor/{session}")
100 @Produces({MediaType.APPLICATION_JSON})
101 @Consumes({MediaType.APPLICATION_JSON})
103 public class ApexEditorRestResource {
104 // Get a reference to the logger
105 private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEditorRestResource.class);
107 // The next session will have this number, stating at 0
108 private static int nextSession = 0;
110 // All REST editor sessions being handled by the server
111 private static final Map<Integer, ApexModel> SESSIONMODELMAP = new TreeMap<>();
113 // The ID of this session. This gets injected from the URL.
114 @PathParam("session")
115 private int sessionID = -1;
117 // The Apex model for the session
118 private ApexModel sessionApexModel = null;
121 * This method sets the Apex model for the current editor session. Don't forget to call
122 * {@link #commitChanges()} when finished! This makes requests atomic.
124 * @return the result of finding the session Apex model and setting it
126 private ApexApiResult initialiseSessionForChanges() {
128 return new ApexApiResult(Result.FAILED, "Session ID \"" + sessionID + "\" is negative");
131 if (!SESSIONMODELMAP.containsKey(sessionID)) {
132 return new ApexApiResult(Result.FAILED, "A session with session ID \"" + sessionID + "\" does not exist");
135 if (sessionApexModel == null) {
136 sessionApexModel = SESSIONMODELMAP.get(sessionID).clone();
138 return new ApexApiResult();
142 * This method sets the Apex model for the current editor session. Don't make any changes to the
145 * @return the result of finding the session Apex model and setting it
147 private ApexApiResult initialiseSessionForReadOnly() {
149 return new ApexApiResult(Result.FAILED, "Session ID \"" + sessionID + "\" is negative");
152 if (!SESSIONMODELMAP.containsKey(sessionID)) {
153 return new ApexApiResult(Result.FAILED, "A session with session ID \"" + sessionID + "\" does not exist");
156 if (sessionApexModel == null) {
157 sessionApexModel = SESSIONMODELMAP.get(sessionID);
159 return new ApexApiResult();
163 * This method commits changes to the Apex model for the current editor session. This should
164 * only be called once, at the end of a successful change to the model for this session
166 * @return the result of committing the session Apex model
168 private ApexApiResult commitChanges() {
170 if (sessionApexModel == null) {
171 return new ApexApiResult(Result.FAILED, "Cannot commit a changes for Session ID \"" + sessionID
172 + "\", because it has not been initialised / started");
175 SESSIONMODELMAP.put(sessionID, sessionApexModel);
177 return new ApexApiResult();
181 * Creates a new session. Always call this method with sessionID -1, whereby a new sessionID
182 * will be allocated. If successful the new sessionID will be available in the first message in
185 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
186 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}.
187 * This includes the session id for this session.
190 @Path("Session/Create")
191 public ApexApiResult createSession() {
192 ApexApiResult ret = null;
195 if (sessionID != -1) {
196 ret = new ApexApiResult(Result.FAILED, "Session ID must be set to -1 to create sessions: " + sessionID);
200 final int newSessionID = nextSession;
202 if (SESSIONMODELMAP.containsKey(newSessionID)) {
203 ret = new ApexApiResult(Result.FAILED, "Session already exists for session: " + newSessionID);
207 SESSIONMODELMAP.put(newSessionID, new ApexModelFactory().createApexModel(null, true));
210 ret = new ApexApiResult(Result.SUCCESS, Integer.toString(newSessionID));
212 } catch (final Exception e) {
216 LOGGER.exit((ret == null ? false : ret.isOk()));
217 LOGGER.info("Session/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
222 * Load the model from a JSON string for this session.
224 * @param jsonString the JSON string to be parsed. The returned value(s) will be similar to
225 * {@link AxPolicyModel}, with merged {@linkplain AxKeyInfo} for the root object.
226 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
227 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
231 public ApexApiResult loadFromString(final String jsonString) {
232 ApexApiResult ret = null;
233 LOGGER.entry(jsonString);
235 ret = initialiseSessionForChanges();
240 ret = sessionApexModel.loadFromString(jsonString);
245 } catch (final Exception e) {
249 LOGGER.exit((ret == null ? false : ret.isOk()));
250 LOGGER.info("Model/Load" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
255 * Analyse the model and return analysis results. If successful the analysis results will be
256 * available in the messages in the result.
258 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
259 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
262 @Path("Model/Analyse")
263 public ApexApiResult analyse() {
264 ApexApiResult ret = null;
267 ret = initialiseSessionForReadOnly();
272 ret = sessionApexModel.analyse();
274 } catch (final Exception e) {
278 LOGGER.exit((ret == null ? false : ret.isOk()));
279 LOGGER.info("Model/Analyse" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
284 * Validate the model and return validation results. If successful the validation results will
285 * be available in the messages in the result.
287 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
288 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
291 @Path("Model/Validate")
292 public ApexApiResult validate() {
293 ApexApiResult ret = null;
296 ret = initialiseSessionForReadOnly();
301 ret = sessionApexModel.validate();
303 ret = addKeyInfo2Messages(ret);
305 } catch (final Exception e) {
309 LOGGER.exit((ret == null ? false : ret.isOk()));
310 LOGGER.info("Model/Validate" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
315 * Creates the new model model for this session.
317 * @param jsonString the JSON string to be parsed containing the new model. See
318 * {@linkplain BeanModel}
319 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
320 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
323 @Path("Model/Create")
324 public ApexApiResult createModel(final String jsonString) {
325 ApexApiResult ret = null;
326 LOGGER.entry(jsonString);
328 ret = initialiseSessionForChanges();
333 final BeanModel jsonbean = RestUtils.getJSONParameters(jsonString, BeanModel.class);
334 ret = sessionApexModel.createModel(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getUuid(),
335 jsonbean.getDescription());
338 ret = addKeyInfo2Messages(ret);
344 } catch (final Exception e) {
348 LOGGER.exit((ret == null ? false : ret.isOk()));
349 LOGGER.info("Model/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
354 * Update the model for this session.
356 * @param jsonString the JSON string to be parsed containing the updated model. See
357 * {@linkplain BeanModel}
358 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
359 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
362 @Path("Model/Update")
363 public ApexApiResult updateModel(final String jsonString) {
364 ApexApiResult ret = null;
365 LOGGER.entry(jsonString);
367 ret = initialiseSessionForChanges();
372 final BeanModel jsonbean = RestUtils.getJSONParameters(jsonString, BeanModel.class);
373 ret = sessionApexModel.updateModel(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getUuid(),
374 jsonbean.getDescription());
379 } catch (final Exception e) {
383 LOGGER.exit((ret == null ? false : ret.isOk()));
384 LOGGER.info("Model/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
389 * Gets the key for the model for this session. If successful the model key will be available in
390 * the first message in the result. See {@linkplain AxKey}
392 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
393 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
396 @Path("Model/GetKey")
397 public ApexApiResult getModelKey() {
398 ApexApiResult ret = null;
401 ret = initialiseSessionForReadOnly();
406 ret = sessionApexModel.getModelKey();
408 } catch (final Exception e) {
412 LOGGER.exit((ret == null ? false : ret.isOk()));
413 LOGGER.info("Model/GetKey" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
418 * Retrieve the model for this session. If successful the model will be available in the first
419 * message in the result. The returned value will be similar to a {@link AxPolicyModel}, with
420 * merged {@linkplain AxKeyInfo} for the root object.
422 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
423 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
427 public ApexApiResult listModel() {
428 ApexApiResult ret = null;
431 ret = initialiseSessionForReadOnly();
436 ret = sessionApexModel.listModel();
441 ret = addKeyInfo2Messages(ret);
443 } catch (final Exception e) {
447 LOGGER.exit((ret == null ? false : ret.isOk()));
448 LOGGER.info("Model/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
453 * Download the model for this session as a String.
455 * @return the model represented as a JSON string. See {@linkplain AxPolicyModel}
458 @Path("Model/Download")
459 public String downloadModel() {
460 ApexApiResult ret = null;
464 ret = initialiseSessionForReadOnly();
466 throw new IllegalStateException("Cannot download file: " + ret.getMessage());
469 ret = sessionApexModel.listModel();
471 throw new IllegalStateException("Cannot download file: " + ret.getMessage());
474 return ret.getMessage();
475 } catch (final Exception e) {
480 LOGGER.exit(ret.isOk());
482 LOGGER.info("Model/Download" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
487 * Delete the model for this session.
489 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
490 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
493 @Path("Model/Delete")
494 public ApexApiResult deleteModel() {
495 ApexApiResult ret = null;
498 ret = initialiseSessionForChanges();
503 ret = sessionApexModel.deleteModel();
508 } catch (final Exception e) {
512 LOGGER.exit((ret == null ? false : ret.isOk()));
513 LOGGER.info("Model/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
518 * List key information with the given key names/versions. If successful the result(s) will be
519 * available in the result messages. See {@linkplain AxKeyInfo}
521 * @param name the name to search for. If null or empty, then all names will be queried
522 * @param version the version to search for. If null then all versions will be searched for.
523 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
524 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
527 @Path("KeyInformation/Get")
528 public ApexApiResult listKeyInformation(@QueryParam("name") final String name,
529 @QueryParam("version") final String version) {
530 ApexApiResult ret = null;
532 String version1 = version;
533 LOGGER.entry(name1, version1);
535 ret = initialiseSessionForReadOnly();
540 if (name1 == null || name1.equals("")) {
543 if (version1 == null || version1.equals("")) {
547 ret = sessionApexModel.listKeyInformation(name1, version1);
549 } catch (final Exception e) {
553 LOGGER.exit((ret == null ? false : ret.isOk()));
554 LOGGER.info("KeyInformation/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
559 * Creates a context schema with the information in the JSON string passed.
561 * @param jsonString the JSON string to be parsed. See {@linkplain BeanContextSchema}
562 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
563 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
566 @Path("ContextSchema/Create")
567 public ApexApiResult createContextSchema(final String jsonString) {
568 ApexApiResult ret = null;
569 LOGGER.entry(jsonString);
571 ret = initialiseSessionForChanges();
576 final BeanContextSchema jsonbean = RestUtils.getJSONParameters(jsonString, BeanContextSchema.class);
577 ret = sessionApexModel.createContextSchema(jsonbean.getName(), jsonbean.getVersion(),
578 jsonbean.getSchemaFlavour(), jsonbean.getSchemaDefinition(), jsonbean.getUuid(),
579 jsonbean.getDescription());
584 } catch (final Exception e) {
588 LOGGER.exit((ret == null ? false : ret.isOk()));
589 LOGGER.info("ContextSchema/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
594 * Update a context schema with the information in the JSON string passed.
596 * @param jsonString the JSON string to be parsed. See {@linkplain BeanContextSchema}
597 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
598 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
601 @Path("ContextSchema/Update")
602 public ApexApiResult updateContextSchema(final String jsonString) {
603 ApexApiResult ret = null;
604 LOGGER.entry(jsonString);
606 ret = initialiseSessionForChanges();
611 final BeanContextSchema jsonbean = RestUtils.getJSONParameters(jsonString, BeanContextSchema.class);
613 ret = sessionApexModel.updateContextSchema(jsonbean.getName(), jsonbean.getVersion(),
614 jsonbean.getSchemaFlavour(), jsonbean.getSchemaDefinition(), jsonbean.getUuid(),
615 jsonbean.getDescription());
620 } catch (final Exception e) {
624 LOGGER.exit((ret == null ? false : ret.isOk()));
625 LOGGER.info("ContextSchema/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
630 * List context schemas with the given key names/versions. If successful the result(s) will be
631 * available in the result messages. The returned value(s) will be similar to
632 * {@link AxContextSchema}, with merged {@linkplain AxKeyInfo} for the root object.
634 * @param name the name to search for. If null or empty, then all names will be queried
635 * @param version the version to search for. If null then all versions will be searched for.
636 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
637 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
640 @Path("ContextSchema/Get")
641 public ApexApiResult listContextSchemas(@QueryParam("name") final String name,
642 @QueryParam("version") final String version) {
643 ApexApiResult ret = null;
645 String version1 = version;
646 LOGGER.entry(name1, version1);
648 ret = initialiseSessionForReadOnly();
653 if (name1 == null || name1.equals("")) {
656 if (version1 == null || version1.equals("")) {
660 ret = sessionApexModel.listContextSchemas(name1, version1);
665 ret = addKeyInfo2Messages(ret);
667 } catch (final Exception e) {
671 LOGGER.exit((ret == null ? false : ret.isOk()));
672 LOGGER.info("ContextSchema/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
677 * Delete context schemas with the given key names/versions.
679 * @param name the name to search for. If null or empty, then all names will be queried
680 * @param version the version to search for. If null then all versions will be searched for.
681 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
682 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
685 @Path("ContextSchema/Delete")
686 public ApexApiResult deleteContextSchema(@QueryParam("name") final String name,
687 @QueryParam("version") final String version) {
688 ApexApiResult ret = null;
690 String version1 = version;
691 LOGGER.entry(name1, version1);
693 ret = initialiseSessionForChanges();
698 if (name1 == null || name1.equals("")) {
701 if (version1 == null || version1.equals("")) {
705 ret = sessionApexModel.deleteContextSchema(name1, version1);
710 } catch (final Exception e) {
714 LOGGER.exit((ret == null ? false : ret.isOk()));
715 LOGGER.info("ContextSchema/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
720 * Validate context schemas with the given key names/versions. The result(s) will be available
721 * in the result messages.
723 * @param name the name to search for. If null or empty, then all names will be queried
724 * @param version the version to search for. If null then all versions will be searched for.
725 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
726 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
729 @Path("Validate/ContextSchema")
730 public ApexApiResult validateContextSchemas(@QueryParam("name") final String name,
731 @QueryParam("version") final String version) {
732 ApexApiResult ret = null;
734 String version1 = version;
735 LOGGER.entry(name1, version1);
737 if (name1 == null || name1.equals("")) {
740 if (version1 == null || version1.equals("")) {
744 ret = initialiseSessionForReadOnly();
749 ret = sessionApexModel.validateContextSchemas(name1, version1);
754 ret = addKeyInfo2Messages(ret);
756 } catch (final Exception e) {
760 LOGGER.exit((ret == null ? false : ret.isOk()));
761 LOGGER.info("Validate/ContextSchema" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
766 * Creates a context album with the information in the JSON string passed.
768 * @param jsonString the JSON string to be parsed. See {@linkplain BeanContextAlbum}
769 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
770 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
773 @Path("ContextAlbum/Create")
774 public ApexApiResult createContextAlbum(final String jsonString) {
775 ApexApiResult ret = null;
776 LOGGER.entry(jsonString);
778 ret = initialiseSessionForChanges();
783 final BeanContextAlbum jsonbean = RestUtils.getJSONParameters(jsonString, BeanContextAlbum.class);
785 ret = sessionApexModel.createContextAlbum(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getScope(),
786 Boolean.toString(jsonbean.getWriteable()), jsonbean.getItemSchema().getName(),
787 jsonbean.getItemSchema().getVersion(), jsonbean.getUuid(), jsonbean.getDescription());
792 } catch (final Exception e) {
796 LOGGER.exit((ret == null ? false : ret.isOk()));
797 LOGGER.info("ContextAlbum/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
802 * Update a context album with the information in the JSON string passed.
804 * @param jsonString the JSON string to be parsed. See {@linkplain BeanContextAlbum}
805 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
806 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
809 @Path("ContextAlbum/Update")
810 public ApexApiResult updateContextAlbum(final String jsonString) {
811 ApexApiResult ret = null;
812 LOGGER.entry(jsonString);
814 ret = initialiseSessionForChanges();
819 final BeanContextAlbum jsonbean = RestUtils.getJSONParameters(jsonString, BeanContextAlbum.class);
821 ret = sessionApexModel.updateContextAlbum(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getScope(),
822 Boolean.toString(jsonbean.getWriteable()), jsonbean.getItemSchema().getName(),
823 jsonbean.getItemSchema().getVersion(), jsonbean.getUuid(), jsonbean.getDescription());
828 } catch (final Exception e) {
832 LOGGER.exit((ret == null ? false : ret.isOk()));
833 LOGGER.info("ContextAlbum/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
838 * List context albums with the given key names/versions. If successful the result(s) will be
839 * available in the result messages. The returned value(s) will be similar to
840 * {@link AxContextAlbum}, with merged {@linkplain AxKeyInfo} for the root object.
842 * @param name the name to search for. If null or empty, then all names will be queried
843 * @param version the version to search for. If null then all versions will be searched for.
844 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
845 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
848 @Path("ContextAlbum/Get")
849 public ApexApiResult listContextAlbums(@QueryParam("name") final String name,
850 @QueryParam("version") final String version) {
851 ApexApiResult ret = null;
853 String version1 = version;
854 LOGGER.entry(name1, version1);
856 ret = initialiseSessionForReadOnly();
861 if (name1 == null || name1.equals("")) {
864 if (version1 == null || version1.equals("")) {
868 ret = sessionApexModel.listContextAlbum(name1, version1);
873 ret = addKeyInfo2Messages(ret);
875 } catch (final Exception e) {
879 LOGGER.exit((ret == null ? false : ret.isOk()));
880 LOGGER.info("ContextAlbum/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
885 * Delete context albums with the given key names/versions.
887 * @param name the name to search for. If null or empty, then all names will be queried
888 * @param version the version to search for. If null then all versions will be searched for.
889 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
890 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
893 @Path("ContextAlbum/Delete")
894 public ApexApiResult deleteContextAlbum(@QueryParam("name") final String name,
895 @QueryParam("version") final String version) {
896 ApexApiResult ret = null;
898 String version1 = version;
899 LOGGER.entry(name1, version1);
901 ret = initialiseSessionForChanges();
906 if (name1 == null || name1.equals("")) {
909 if (version1 == null || version1.equals("")) {
913 ret = sessionApexModel.deleteContextAlbum(name1, version1);
918 } catch (final Exception e) {
922 LOGGER.exit((ret == null ? false : ret.isOk()));
923 LOGGER.info("ContextAlbum/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
928 * Validate context albums with the given key names/versions. The result(s) will be available in
929 * the result messages.
931 * @param name the name to search for. If null or empty, then all names will be queried
932 * @param version the version to search for. If null then all versions will be searched for.
933 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
934 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
937 @Path("Validate/ContextAlbum")
938 public ApexApiResult validateContextAlbums(@QueryParam("name") final String name,
939 @QueryParam("version") final String version) {
940 ApexApiResult ret = null;
942 String version1 = version;
943 LOGGER.entry(name1, version1);
945 if (name1 == null || name1.equals("")) {
948 if (version1 == null || version1.equals("")) {
952 ret = initialiseSessionForReadOnly();
957 ret = sessionApexModel.listContextAlbum(name1, version1);
962 ret = addKeyInfo2Messages(ret);
964 } catch (final Exception e) {
968 LOGGER.exit((ret == null ? false : ret.isOk()));
969 LOGGER.info("Validate/ContextAlbum" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
974 * Creates an event with the information in the JSON string passed.
976 * @param jsonString the JSON string to be parsed. See {@linkplain BeanEvent}
977 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
978 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
981 @Path("Event/Create")
982 public ApexApiResult createEvent(final String jsonString) {
983 ApexApiResult ret = null;
984 LOGGER.entry(jsonString);
986 ret = initialiseSessionForChanges();
991 final BeanEvent jsonbean = RestUtils.getJSONParameters(jsonString, BeanEvent.class);
993 ret = sessionApexModel.createEvent(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getNameSpace(),
994 jsonbean.getSource(), jsonbean.getTarget(), jsonbean.getUuid(), jsonbean.getDescription());
998 if (jsonbean.getParameters() != null) {
999 for (final Entry<String, BeanField> p : jsonbean.getParameters().entrySet()) {
1000 if (p.getValue() == null) {
1001 ret = new ApexApiResult(Result.FAILED, "Null event parameter information for parameter \""
1002 + p.getKey() + "\" in event " + jsonbean.getName() + ":" + jsonbean.getVersion()
1003 + ". The event was created, but there was an error adding the event parameters."
1004 + " The event has only been partially defined.");
1007 final ApexApiResult rettmp =
1008 sessionApexModel.createEventPar(jsonbean.getName(), jsonbean.getVersion(), p.getKey(),
1009 p.getValue().getName(), p.getValue().getVersion(), p.getValue().getOptional());
1010 if (rettmp.isNok()) {
1011 rettmp.addMessage("Failed to add event parameter information for parameter \"" + p.getKey()
1012 + "\" in event " + jsonbean.getName() + ":" + jsonbean.getVersion()
1013 + ". The event was created, but there was an error adding the event parameters."
1014 + " The event has only been partially defined.");
1024 } catch (final Exception e) {
1028 LOGGER.exit((ret == null ? false : ret.isOk()));
1029 LOGGER.info("Event/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1034 * Update an event with the information in the JSON string passed.
1036 * @param jsonString the JSON string to be parsed. See {@linkplain BeanEvent}
1037 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1038 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1041 @Path("Event/Update")
1042 public ApexApiResult updateEvent(final String jsonString) {
1043 ApexApiResult ret = null;
1044 LOGGER.entry(jsonString);
1046 ret = initialiseSessionForChanges();
1051 final BeanEvent jsonbean = RestUtils.getJSONParameters(jsonString, BeanEvent.class);
1053 if (jsonbean.getName() == null || jsonbean.getName().equals("") || jsonbean.getVersion() == null
1054 || jsonbean.getVersion().equals("")) {
1055 ret = new ApexApiResult(Result.FAILED, "Null/Empty event name/version (\"" + jsonbean.getName() + ":"
1056 + jsonbean.getVersion() + "\" passed to UpdateEvent");
1060 ret = sessionApexModel.deleteEvent(jsonbean.getName(), jsonbean.getVersion());
1065 ret = createEvent(jsonString);
1070 } catch (final Exception e) {
1074 LOGGER.exit((ret == null ? false : ret.isOk()));
1075 LOGGER.info("Event/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1080 * List events with the given key names/versions. If successful the result(s) will be available
1081 * in the result messages. The returned value(s) will be similar to {@link AxEvent}, with merged
1082 * {@linkplain AxKeyInfo} for the root object.
1084 * @param name the name to search for. If null or empty, then all names will be queried
1085 * @param version the version to search for. If null then all versions will be searched for.
1086 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1087 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1091 public ApexApiResult listEvent(@QueryParam("name") final String name, @QueryParam("version") final String version) {
1092 ApexApiResult ret = null;
1093 String name1 = name;
1094 String version1 = version;
1095 LOGGER.entry(name1, version1);
1097 ret = initialiseSessionForReadOnly();
1102 if (name1 == null || name1.equals("")) {
1105 if (version1 == null || version1.equals("")) {
1109 ret = sessionApexModel.listEvent(name1, version1);
1114 ret = addKeyInfo2Messages(ret);
1116 } catch (final Exception e) {
1120 LOGGER.exit((ret == null ? false : ret.isOk()));
1121 LOGGER.info("Event/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1126 * Delete events with the given key names/versions.
1128 * @param name the name to search for. If null or empty, then all names will be queried
1129 * @param version the version to search for. If null then all versions will be searched for.
1130 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1131 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1134 @Path("Event/Delete")
1135 public ApexApiResult deleteEvent(@QueryParam("name") final String name,
1136 @QueryParam("version") final String version) {
1137 ApexApiResult ret = null;
1138 String name1 = name;
1139 String version1 = version;
1140 LOGGER.entry(name1, version1);
1142 if (name1 == null || name1.equals("")) {
1145 if (version1 == null || version1.equals("")) {
1149 ret = initialiseSessionForChanges();
1154 ret = sessionApexModel.deleteEvent(name1, version1);
1159 } catch (final Exception e) {
1163 LOGGER.exit((ret == null ? false : ret.isOk()));
1164 LOGGER.info("Event/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1169 * Validate events with the given key names/versions. The result(s) will be available in the
1172 * @param name the name to search for. If null or empty, then all names will be queried
1173 * @param version the version to search for. If null then all versions will be searched for.
1174 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1175 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1178 @Path("Validate/Event")
1179 public ApexApiResult validateEvent(@QueryParam("name") final String name,
1180 @QueryParam("version") final String version) {
1181 ApexApiResult ret = null;
1182 String name1 = name;
1183 String version1 = version;
1184 LOGGER.entry(name1, version1);
1186 ret = initialiseSessionForReadOnly();
1191 if (name1 == null || name1.equals("")) {
1194 if (version1 == null || version1.equals("")) {
1198 ret = sessionApexModel.listEvent(name1, version1);
1203 ret = addKeyInfo2Messages(ret);
1205 } catch (final Exception e) {
1209 LOGGER.exit((ret == null ? false : ret.isOk()));
1210 LOGGER.info("Validate/Event" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1215 * Creates a task with the information in the JSON string passed.
1217 * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask}
1218 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1219 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1222 @Path("Task/Create")
1223 public ApexApiResult createTask(final String jsonString) {
1224 ApexApiResult ret = null;
1225 ApexApiResult tempres = null;
1226 LOGGER.entry(jsonString);
1228 ret = initialiseSessionForChanges();
1233 final BeanTask jsonbean = RestUtils.getJSONParameters(jsonString, BeanTask.class);
1235 ret = sessionApexModel.createTask(jsonbean.getName(), jsonbean.getVersion(), jsonbean.getUuid(),
1236 jsonbean.getDescription());
1240 if (jsonbean.getInputFields() != null) {
1241 for (final Entry<String, BeanField> fin : jsonbean.getInputFields().entrySet()) {
1242 if (fin.getValue() == null) {
1243 ret = new ApexApiResult(Result.FAILED, "Null task input field information for field \""
1244 + fin.getKey() + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion()
1245 + ". The task was created, but there was an error adding the input fields."
1246 + " The task has only been partially defined.");
1249 if (fin.getKey() == null || !fin.getKey().equals(fin.getValue().getLocalName())) {
1250 ret = new ApexApiResult(Result.FAILED, "Invalid task input field information for field \""
1251 + fin.getKey() + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion()
1252 + ". The localName of the field (\"" + fin.getValue().getLocalName()
1253 + "\") is not the same as the field name. "
1254 + "The task was created, but there was an error adding the input fields."
1255 + " The task has only been partially defined.");
1258 tempres = sessionApexModel.createTaskInputField(jsonbean.getName(), jsonbean.getVersion(),
1259 fin.getKey(), fin.getValue().getName(), fin.getValue().getVersion(),
1260 fin.getValue().getOptional());
1261 if (tempres.isNok()) {
1262 tempres.addMessage("Failed to add task input field information for field \"" + fin.getKey()
1263 + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion()
1264 + ". The task was created, but there was an error adding the input fields."
1265 + " The task has only been partially defined.");
1271 if (jsonbean.getOutputFields() != null) {
1272 for (final Entry<String, BeanField> fout : jsonbean.getOutputFields().entrySet()) {
1273 if (fout.getValue() == null) {
1274 ret = new ApexApiResult(Result.FAILED, "Null task output field information for field \""
1275 + fout.getKey() + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion()
1276 + ". The task was created, but there was an error adding the output fields."
1277 + " The task has only been partially defined.");
1280 if (fout.getKey() == null || !fout.getKey().equals(fout.getValue().getLocalName())) {
1281 ret = new ApexApiResult(Result.FAILED, "Invalid task output field information for field \""
1282 + fout.getKey() + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion()
1283 + ". The localName of the field (\"" + fout.getValue().getLocalName()
1284 + "\") is not the same as the field name. "
1285 + "The task was created, but there was an error adding the output fields."
1286 + " The task has only been partially defined.");
1289 tempres = sessionApexModel.createTaskOutputField(jsonbean.getName(), jsonbean.getVersion(),
1290 fout.getKey(), fout.getValue().getName(), fout.getValue().getVersion(),
1291 fout.getValue().getOptional());
1292 if (tempres.isNok()) {
1293 tempres.addMessage("Failed to add task output field information for field \"" + fout.getKey()
1294 + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion()
1295 + ". The task was created, but there was an error adding the output fields."
1296 + " The task has only been partially defined.");
1302 if (jsonbean.getTaskLogic() != null) {
1303 final BeanLogic logic = jsonbean.getTaskLogic();
1304 tempres = sessionApexModel.createTaskLogic(jsonbean.getName(), jsonbean.getVersion(),
1305 logic.getLogicFlavour(), logic.getLogic());
1306 if (tempres.isNok()) {
1307 tempres.addMessage("Failed to add task logic in task " + jsonbean.getName() + ":"
1308 + jsonbean.getVersion()
1309 + ". The task was created, but there was an error adding the logic."
1310 + " The task has only been partially defined.");
1315 if (jsonbean.getParameters() != null) {
1316 for (final Entry<String, BeanTaskParameter> param : jsonbean.getParameters().entrySet()) {
1317 if (param.getKey() == null || param.getValue() == null
1318 || !param.getKey().equals(param.getValue().getParameterName())) {
1319 ret = new ApexApiResult(Result.FAILED,
1320 "Null or invalid task parameter information for parameter \"" + param.getKey()
1321 + "\" in task " + jsonbean.getName() + ":" + jsonbean.getVersion()
1322 + ". The task was created, but there was an error adding the parameters."
1323 + " The task has only been partially defined.");
1326 tempres = sessionApexModel.createTaskParameter(jsonbean.getName(), jsonbean.getVersion(),
1327 param.getValue().getParameterName(), param.getValue().getDefaultValue());
1328 if (tempres.isNok()) {
1329 tempres.addMessage("Failed to add task parameter \"" + param.getKey() + "\" in task "
1330 + jsonbean.getName() + ":" + jsonbean.getVersion()
1331 + ". The task was created, but there was an error adding the parameters."
1332 + " The task has only been partially defined.");
1338 if (jsonbean.getContexts() != null) {
1339 for (final BeanKeyRef contextalbum : jsonbean.getContexts()) {
1340 if (contextalbum.getName() == null || contextalbum.getVersion() == null) {
1341 ret = new ApexApiResult(Result.FAILED,
1342 "Null or invalid context album reference information in task " + jsonbean.getName()
1343 + ":" + jsonbean.getVersion()
1344 + ". The task was created, but there was an error adding the"
1345 + " context album reference. The task has only been partially defined.");
1348 tempres = sessionApexModel.createTaskContextRef(jsonbean.getName(), jsonbean.getVersion(),
1349 contextalbum.getName(), contextalbum.getVersion());
1350 if (tempres.isNok()) {
1351 ret = new ApexApiResult(Result.FAILED,
1352 "Failed to add context album reference information in task " + jsonbean.getName() + ":"
1353 + jsonbean.getVersion()
1354 + ". The task was created, but there was an error adding the"
1355 + " context album reference. The task has only been partially defined.");
1364 } catch (final Exception e) {
1368 LOGGER.exit((ret == null ? false : ret.isOk()));
1369 LOGGER.info("Task/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1374 * Update a task with the information in the JSON string passed.
1376 * @param jsonString the JSON string to be parsed. See {@linkplain BeanTask}
1377 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1378 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1381 @Path("Task/Update")
1382 public ApexApiResult updateTask(final String jsonString) {
1383 ApexApiResult ret = null;
1384 LOGGER.entry(jsonString);
1386 ret = initialiseSessionForChanges();
1391 final BeanTask jsonbean = RestUtils.getJSONParameters(jsonString, BeanTask.class);
1393 if (jsonbean.getName() == null || jsonbean.getName().equals("") || jsonbean.getVersion() == null
1394 || jsonbean.getVersion().equals("")) {
1395 ret = new ApexApiResult(Result.FAILED, "Null/Empty task name/version (\"" + jsonbean.getName() + ":"
1396 + jsonbean.getVersion() + "\" passed to UpdateTask");
1400 ret = sessionApexModel.deleteTask(jsonbean.getName(), jsonbean.getVersion());
1405 ret = createTask(jsonString);
1410 } catch (final Exception e) {
1414 LOGGER.exit((ret == null ? false : ret.isOk()));
1415 LOGGER.info("Task/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1420 * List tasks with the given key names/versions. If successful the result(s) will be available
1421 * in the result messages. The returned value(s) will be similar to {@link AxTask}, with merged
1422 * {@linkplain AxKeyInfo} for the root object.
1424 * @param name the name to search for. If null or empty, then all names will be queried
1425 * @param version the version to search for. If null then all versions will be searched for.
1426 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1427 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1431 public ApexApiResult listTask(@QueryParam("name") final String name, @QueryParam("version") final String version) {
1432 ApexApiResult ret = null;
1433 String name1 = name;
1434 String version1 = version;
1435 LOGGER.entry(name1, version1);
1437 ret = initialiseSessionForReadOnly();
1442 if (name1 == null || name1.equals("")) {
1445 if (version1 == null || version1.equals("")) {
1449 ret = sessionApexModel.listTask(name1, version1);
1454 ret = addKeyInfo2Messages(ret);
1456 } catch (final Exception e) {
1460 LOGGER.exit((ret == null ? false : ret.isOk()));
1461 LOGGER.info("Task/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1466 * Delete tasks with the given key names/versions.
1468 * @param name the name to search for. If null or empty, then all names will be queried
1469 * @param version the version to search for. If null then all versions will be searched for.
1470 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1471 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1474 @Path("Task/Delete")
1475 public ApexApiResult deleteTask(@QueryParam("name") final String name,
1476 @QueryParam("version") final String version) {
1477 ApexApiResult ret = null;
1478 String name1 = name;
1479 String version1 = version;
1480 LOGGER.entry(name1, version1);
1482 ret = initialiseSessionForChanges();
1487 if (name1 == null || name1.equals("")) {
1490 if (version1 == null || version1.equals("")) {
1494 // all input/output fields, parameters, logic, context references is "owned"/contained
1496 // deleting the task removes all of these
1497 ret = sessionApexModel.deleteTask(name1, version1);
1502 } catch (final Exception e) {
1506 LOGGER.exit((ret == null ? false : ret.isOk()));
1507 LOGGER.info("Task/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1512 * Validate tasks with the given key names/versions. The result(s) will be available in the
1515 * @param name the name to search for. If null or empty, then all names will be queried
1516 * @param version the version to search for. If null then all versions will be searched for.
1517 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1518 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1521 @Path("Validate/Task")
1522 public ApexApiResult validateTask(@QueryParam("name") final String name,
1523 @QueryParam("version") final String version) {
1524 ApexApiResult ret = null;
1525 String name1 = name;
1526 String version1 = version;
1527 LOGGER.entry(name1, version1);
1529 ret = initialiseSessionForReadOnly();
1534 if (name1 == null || name1.equals("")) {
1537 if (version1 == null || version1.equals("")) {
1541 ret = sessionApexModel.listTask(name1, version1);
1546 ret = addKeyInfo2Messages(ret);
1548 } catch (final Exception e) {
1552 LOGGER.exit((ret == null ? false : ret.isOk()));
1553 LOGGER.info("Validate/Task" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1557 // CHECKSTYLE:OFF: MethodLength
1559 * Creates a policy with the information in the JSON string passed.
1561 * @param jsonString the JSON string to be parsed See {@linkplain BeanPolicy}
1562 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1563 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1566 @Path("Policy/Create")
1567 public ApexApiResult createPolicy(final String jsonString) {
1569 ApexApiResult ret = null;
1570 ApexApiResult tempres = null;
1571 LOGGER.entry(jsonString);
1573 ret = initialiseSessionForChanges();
1578 final BeanPolicy jsonbean = RestUtils.getJSONParameters(jsonString, BeanPolicy.class);
1579 final String policyname = jsonbean.getName();
1580 final String policyversion = jsonbean.getVersion();
1582 ret = sessionApexModel.createPolicy(policyname, policyversion, jsonbean.getTemplate(),
1583 jsonbean.getFirstState(), jsonbean.getUuid(), jsonbean.getDescription());
1588 if (jsonbean.getStates() == null || jsonbean.getStates().isEmpty()) {
1589 ret = new ApexApiResult(Result.FAILED, "Null or empty state map; no states defined for policy \""
1590 + policyname + ":" + policyversion
1591 + "\". The policy was created, but there was an error adding states."
1592 + " The policy has only been partially defined.");
1596 final Map<String, BeanState> statemap = jsonbean.getStates();
1597 // need to create all the states first, before populating them
1598 for (final Map.Entry<String, BeanState> e : statemap.entrySet()) {
1599 final String statename = e.getKey();
1600 final BeanState state = e.getValue();
1601 if (state == null) {
1602 ret = new ApexApiResult(Result.FAILED, "Null or invalid state information for state \"" + statename
1603 + "\" for policy \"" + policyname + ":" + policyversion
1604 + "\". The policy was created, but there was an error adding the state."
1605 + " The policy has only been partially defined.");
1608 if (state.getTrigger() == null) {
1609 ret = new ApexApiResult(Result.FAILED, "Null or invalid state trigger for state \"" + statename
1610 + "\" for policy \"" + policyname + ":" + policyversion
1611 + "\". The policy was created, but there was an error adding the state."
1612 + " The policy has only been partially defined.");
1615 if (state.getDefaultTask() == null) {
1616 ret = new ApexApiResult(Result.FAILED, "Null or invalid default task for state \"" + statename
1617 + "\" for policy \"" + policyname + ":" + policyversion
1618 + "\". The policy was created, but there was an error adding the state."
1619 + " The policy has only been partially defined.");
1622 tempres = sessionApexModel.createPolicyState(policyname, policyversion, statename,
1623 state.getTrigger().getName(), state.getTrigger().getVersion(), state.getDefaultTask().getName(),
1624 state.getDefaultTask().getVersion());
1625 if (tempres.isNok()) {
1631 for (final Map.Entry<String, BeanState> e : statemap.entrySet()) {
1632 final String statename = e.getKey();
1633 final BeanState state = e.getValue();
1635 final BeanLogic tsl = state.getTaskSelectionLogic();
1637 tempres = sessionApexModel.createPolicyStateTaskSelectionLogic(policyname, policyversion, statename,
1638 tsl.getLogicFlavour(), tsl.getLogic());
1639 if (tempres.isNok()) {
1640 tempres.addMessage("Failed to add task selection logic for state \"" + statename + "\" for"
1641 + " policy \"" + policyname + ":" + policyversion
1642 + "\". The policy was created, but there was an error adding the task selection logic "
1643 + "for the state. The policy has only been partially defined.");
1649 final BeanKeyRef[] contexts = state.getContexts();
1650 if (contexts != null) {
1651 for (final BeanKeyRef c : contexts) {
1653 ret = new ApexApiResult(Result.FAILED,
1654 "Null or invalid context reference \"" + c + "\" for" + " state \"" + statename
1655 + "\" for policy \"" + policyname + ":" + policyversion
1656 + "\". The policy was created, but there was an error adding the context "
1657 + "reference for the state. The policy has only been partially defined.");
1660 tempres = sessionApexModel.createPolicyStateContextRef(policyname, policyversion, statename,
1661 c.getName(), c.getVersion());
1662 if (tempres.isNok()) {
1663 tempres.addMessage("Failed to add context reference \"" + c + "\" for state \"" + statename
1664 + "\" for policy \"" + policyname + ":" + policyversion
1665 + "\". The policy was created, but there was an error adding the context reference "
1666 + "for the state. The policy has only been partially defined.");
1673 final Map<String, BeanLogic> finalizers = state.getFinalizers();
1674 if (finalizers != null) {
1675 for (final Map.Entry<String, BeanLogic> f : finalizers.entrySet()) {
1676 final String finalizername = f.getKey();
1677 final BeanLogic finalizer = f.getValue();
1678 if (finalizername == null || finalizer == null) {
1679 ret = new ApexApiResult(Result.FAILED,
1680 "Null or invalid finalizer information for finalizer " + "named \"" + finalizername
1681 + "\" in state \"" + statename + "\" for policy \"" + policyname + ":"
1683 + "\". The policy and state were created, but there was an error adding the"
1684 + " finalizer. The policy has only been partially defined.");
1687 tempres = sessionApexModel.createPolicyStateFinalizerLogic(policyname, policyversion, statename,
1688 finalizername, finalizer.getLogicFlavour(), finalizer.getLogic());
1689 if (tempres.isNok()) {
1690 tempres.addMessage("Failed to add finalizer information for finalizer named \""
1691 + finalizername + "\" in" + " state \"" + statename + "\" for policy \""
1692 + policyname + ":" + policyversion
1693 + "\". The policy and state were created, but there was an error adding the"
1694 + " finalizer. The policy has only been partially defined.");
1700 final Map<String, BeanStateOutput> outputs = state.getStateOutputs();
1701 if (outputs == null || outputs.isEmpty()) {
1702 ret = new ApexApiResult(Result.FAILED,
1703 "No state outputs have been defined in state \"" + statename + "\" for policy \""
1704 + policyname + ":" + policyversion
1705 + "\". The policy and state were created, but there was an error adding state"
1706 + " outputs. The policy has only been partially defined.");
1709 for (final Map.Entry<String, BeanStateOutput> o : outputs.entrySet()) {
1710 final String outputname = o.getKey();
1711 final BeanStateOutput output = o.getValue();
1712 if (outputname == null || output == null || output.getEvent() == null) {
1713 ret = new ApexApiResult(Result.FAILED,
1714 "Null or invalid output information for output named \"" + outputname + "\" in state \""
1715 + statename + "\" for policy \"" + policyname + ":" + policyversion
1716 + "\". The policy and state were created, but there was an error adding the"
1717 + " output. The policy has only been partially defined.");
1720 tempres = sessionApexModel.createPolicyStateOutput(policyname, policyversion, statename, outputname,
1721 output.getEvent().getName(), output.getEvent().getVersion(), output.getNextState());
1722 if (tempres.isNok()) {
1723 tempres.addMessage("Failed to add output information for output named \"" + outputname
1724 + "\" in state \"" + statename + "\" for policy \"" + policyname + ":" + policyversion
1725 + "\". The policy and state were created, but there was an error adding the output."
1726 + " The policy has only been partially defined.");
1732 final Map<String, BeanStateTaskRef> taskmap = state.getTasks();
1733 if (taskmap == null || taskmap.isEmpty()) {
1734 ret = new ApexApiResult(Result.FAILED,
1735 "No tasks have been defined in state \"" + statename + "\" for policy \"" + policyname + ":"
1737 + "\". The policy and state were created, but there was an error adding tasks."
1738 + " The policy has only been partially defined.");
1741 for (final Map.Entry<String, BeanStateTaskRef> t : taskmap.entrySet()) {
1742 final String tasklocalname = t.getKey();
1743 final BeanStateTaskRef taskref = t.getValue();
1744 if (tasklocalname == null || taskref == null || taskref.getTask() == null) {
1745 ret = new ApexApiResult(Result.FAILED,
1746 "Null or invalid task information for task named \"" + tasklocalname + "\" in state \""
1747 + statename + "\" for for policy \"" + policyname + ":" + policyversion
1748 + "\". The policy and state were created, but there was an error adding the "
1749 + "task. The policy has only been partially defined.");
1752 tempres = sessionApexModel.createPolicyStateTaskRef(policyname, policyversion, statename,
1753 tasklocalname, taskref.getTask().getName(), taskref.getTask().getVersion(),
1754 taskref.getOutputType(), taskref.getOutputName());
1755 if (tempres.isNok()) {
1756 tempres.addMessage("Failed to add task reference \"" + t + "\" for state \"" + statename
1757 + "\" for policy \"" + policyname + ":" + policyversion
1758 + "\". The policy was created, but there was an error adding the task reference for"
1759 + " the state. The policy has only been partially defined.");
1770 } catch (final Exception e) {
1774 LOGGER.exit((ret == null ? false : ret.isOk()));
1775 LOGGER.info("Policy/Create" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1778 // CHECKSTYLE:ON: MethodLength
1781 * Update a policy with the information in the JSON string passed.
1783 * @param firstStatePeriodic indicates if periodic event should be created and added to model
1784 * @param jsonString the JSON string to be parsed. See {@linkplain BeanPolicy}
1785 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1786 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1789 @Path("Policy/Update")
1790 public ApexApiResult updatePolicy(@QueryParam("firstStatePeriodic") final boolean firstStatePeriodic,
1791 final String jsonString) {
1792 ApexApiResult ret = null;
1793 LOGGER.entry(jsonString);
1795 ret = initialiseSessionForChanges();
1800 final BeanPolicy jsonbean = RestUtils.getJSONParameters(jsonString, BeanPolicy.class);
1802 if (jsonbean.getName() == null || jsonbean.getName().equals("") || jsonbean.getVersion() == null
1803 || jsonbean.getVersion().equals("")) {
1804 ret = new ApexApiResult(Result.FAILED, "Null/Empty Policy name/version (\"" + jsonbean.getName() + ":"
1805 + jsonbean.getVersion() + "\" passed to UpdatePolicy");
1809 ret = sessionApexModel.deletePolicy(jsonbean.getName(), jsonbean.getVersion());
1813 if (firstStatePeriodic) {
1814 final ApexApiResult existingPeriodicEvent = sessionApexModel.listEvent("PeriodicEvent", null);
1815 if (existingPeriodicEvent.isNok()) {
1816 final String periodicEventString =
1817 "{\"name\":\"PeriodicEvent\",\"version\":\"0.0.1\","
1818 + "\"uuid\":\"44236da1-3d47-4988-8033-b6fee9d6a0f4\","
1819 + "\"description\":\"Generated description for concept referred to by key "
1820 + "'PeriodicEvent:0.0.1'\",\"source\":\"System\",\"target\":\"Apex\","
1821 + "\"nameSpace\":\"org.onap.policy.apex.domains.aadm.events\",\"parameters\":{}}";
1822 ret = createEvent(periodicEventString);
1828 ret = createPolicy(jsonString);
1833 } catch (final Exception e) {
1837 LOGGER.exit((ret == null ? false : ret.isOk()));
1838 LOGGER.info("Policy/Update" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1843 * List policies with the given key names/versions. If successful the result(s) will be
1844 * available in the result messages. The returned value(s) will be similar to {@link AxPolicy},
1845 * with merged {@linkplain AxKey Info} for the root object.
1847 * @param name the name to search for. If null or empty, then all names will be queried
1848 * @param version the version to search for. If null then all versions will be searched for.
1849 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1850 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1854 public ApexApiResult listPolicy(@QueryParam("name") final String name,
1855 @QueryParam("version") final String version) {
1856 ApexApiResult ret = null;
1857 String name1 = name;
1858 String version1 = version;
1859 LOGGER.entry(name1, version1);
1861 ret = initialiseSessionForReadOnly();
1866 if (name1 == null || name1.equals("")) {
1869 if (version1 == null || version1.equals("")) {
1873 ret = sessionApexModel.listPolicy(name1, version1);
1879 ret = addKeyInfo2Messages(ret);
1881 } catch (final Exception e) {
1885 LOGGER.exit((ret == null ? false : ret.isOk()));
1886 LOGGER.info("Policy/Get" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1891 * Delete policies with the given key names/versions.
1893 * @param name the name to search for. If null or empty, then all names will be queried
1894 * @param version the version to search for. If null then all versions will be searched for.
1895 * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return
1896 * true. Any messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
1899 @Path("Policy/Delete")
1900 public ApexApiResult deletePolicy(@QueryParam("name") final String name,
1901 @QueryParam("version") final String version) {
1902 ApexApiResult ret = null;
1903 String name1 = name;
1904 String version1 = version;
1905 LOGGER.entry(name1, version1);
1907 ret = initialiseSessionForChanges();
1912 if (name1 == null || name1.equals("")) {
1915 if (version1 == null || version1.equals("")) {
1919 // all input/output fields, parameters, logic, context references is "owned"/contained
1921 // deleting the task removes all of these
1922 ret = sessionApexModel.deletePolicy(name1, version1);
1927 } catch (final Exception e) {
1931 LOGGER.exit((ret == null ? false : ret.isOk()));
1932 LOGGER.info("Policy/Delete" + (ret != null && ret.isOk() ? ": OK" : ": Not OK"));
1937 * The json strings representing the objects listed, stored in result.messages[], does not
1938 * contain the AxKeyInformation for that object. This utility method retrieves the AxKeyInfo for
1939 * each object and adds it to the json for the object.
1941 * @param result The list result, containing json representations of objects stored in its
1943 * @return The list result, containing json augmented representations of objects stored in its
1946 private ApexApiResult addKeyInfo2Messages(final ApexApiResult result) {
1947 if (result.isNok()) {
1951 final ApexApiResult ret = new ApexApiResult(result.getResult());
1952 ret.setMessages(result.getMessages());
1954 final List<String> messages = result.getMessages();
1955 final List<String> augmessages = new ArrayList<>(messages.size());
1956 final GsonBuilder gb = new GsonBuilder();
1957 gb.serializeNulls().enableComplexMapKeySerialization();
1958 final Gson gson = gb.create();
1959 for (final String message : messages) {
1961 final JsonObject jsonObject = gson.fromJson(message, JsonObject.class);
1962 JsonObject objecttochange = jsonObject;
1964 if (jsonObject != null && jsonObject.get("key") != null && jsonObject.get("key").isJsonObject()
1965 && jsonObject.getAsJsonObject("key").get("name") != null) {
1966 name = jsonObject.getAsJsonObject("key").get("name").getAsString();
1967 } else if (jsonObject != null && jsonObject.get("policyKey") != null
1968 && jsonObject.get("policyKey").isJsonObject()
1969 && jsonObject.getAsJsonObject("policyKey").get("name") != null) {
1970 name = jsonObject.getAsJsonObject("policyKey").get("name").getAsString();
1972 String version = null;
1973 if (jsonObject != null && jsonObject.get("key") != null && jsonObject.get("key").isJsonObject()
1974 && jsonObject.getAsJsonObject("key").get("version") != null) {
1975 version = jsonObject.getAsJsonObject("key").get("version").getAsString();
1976 } else if (jsonObject != null && jsonObject.get("policyKey") != null
1977 && jsonObject.get("policyKey").isJsonObject()
1978 && jsonObject.getAsJsonObject("policyKey").get("version") != null) {
1979 version = jsonObject.getAsJsonObject("policyKey").get("version").getAsString();
1982 if (name == null && version == null && jsonObject.entrySet() != null
1983 && jsonObject.entrySet().size() > 0) {
1984 objecttochange = (JsonObject) jsonObject.entrySet().iterator().next().getValue();
1985 if (objecttochange != null && objecttochange.get("key") != null
1986 && objecttochange.get("key").isJsonObject()
1987 && objecttochange.getAsJsonObject("key").get("name") != null) {
1988 name = objecttochange.getAsJsonObject("key").get("name").getAsString();
1989 } else if (objecttochange != null && objecttochange.get("policyKey") != null
1990 && objecttochange.get("policyKey").isJsonObject()
1991 && objecttochange.getAsJsonObject("policyKey").get("name") != null) {
1992 name = objecttochange.getAsJsonObject("policyKey").get("name").getAsString();
1994 if (objecttochange != null && objecttochange.get("key") != null
1995 && objecttochange.get("key").isJsonObject()
1996 && objecttochange.getAsJsonObject("key").get("version") != null) {
1997 version = objecttochange.getAsJsonObject("key").get("version").getAsString();
1998 } else if (objecttochange != null && objecttochange.get("policyKey") != null
1999 && objecttochange.get("policyKey").isJsonObject()
2000 && objecttochange.getAsJsonObject("policyKey").get("version") != null) {
2001 version = objecttochange.getAsJsonObject("policyKey").get("version").getAsString();
2008 if (name != null && version != null) {
2009 final ApexApiResult keyInfoResult = sessionApexModel.listKeyInformation(name, version);
2010 final List<String> keyInfoMessages = keyInfoResult.getMessages();
2011 if (keyInfoResult.isOk() && keyInfoMessages != null && keyInfoMessages.size() > 0) {
2012 final String keyInfoJson = keyInfoMessages.get(0);
2013 final JsonObject keyInfoJsonObject = gson.fromJson(keyInfoJson, JsonObject.class);
2014 if (keyInfoJsonObject != null && keyInfoJsonObject.get("apexKeyInfo") != null
2015 && keyInfoJsonObject.get("apexKeyInfo").getAsJsonObject().get("UUID") != null) {
2016 uuid = keyInfoJsonObject.get("apexKeyInfo").getAsJsonObject().get("UUID").getAsString();
2018 if (keyInfoJsonObject != null && keyInfoJsonObject.get("apexKeyInfo") != null
2019 && keyInfoJsonObject.get("apexKeyInfo").getAsJsonObject().get("description") != null) {
2020 desc = keyInfoJsonObject.get("apexKeyInfo").getAsJsonObject().get("description")
2025 objecttochange.addProperty("uuid", uuid);
2026 objecttochange.addProperty("description", desc);
2027 augmessages.add(gson.toJson(jsonObject));
2028 } catch (final Exception e) {
2029 augmessages.add(message);
2032 ret.setMessages(augmessages);
2034 if (messages.size() != augmessages.size()) {
2035 ret.setResult(Result.OTHER_ERROR);
2036 ret.addMessage("Failed to add KeyInfo to all results. Results are not complete");
2043 * This method is used only for testing and is used to cause an exception on calls from unit
2044 * test to test exception handling.
2046 protected static int createCorruptSession() {
2047 final ApexEditorRestResource apexEditorRestResource = new ApexEditorRestResource();
2048 final ApexApiResult result = apexEditorRestResource.createSession();
2049 final int corruptSessionId = new Integer(result.getMessages().get(0));
2051 SESSIONMODELMAP.put(corruptSessionId, null);
2053 return corruptSessionId;