diff options
Diffstat (limited to 'gui-editors/gui-editor-apex/src/main')
53 files changed, 806 insertions, 1589 deletions
diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/ApexEditor.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/ApexEditor.java new file mode 100644 index 0000000..506134e --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/ApexEditor.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.gui.editors.apex; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApexEditor { + + public static void main(String[] args) { + SpringApplication.run(ApexEditor.class, args); + } +} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditor.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditor.java deleted file mode 100644 index d21e305..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditor.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.gui.editors.apex.rest; - -import org.glassfish.grizzly.http.server.HttpServer; -import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; -import org.glassfish.jersey.media.multipart.MultiPartFeature; -import org.glassfish.jersey.server.ResourceConfig; -import org.onap.policy.common.utils.validation.Assertions; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class is used to launch the editor. It creates a Grizzly embedded web - * server and runs the editor. - */ -public class ApexEditor { - // Logger for this class - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEditor.class); - - // The HTTP server exposing JAX-RS resources defined in this application. - private final HttpServer server; - - /** - * Starts the HTTP server for the Apex editor on the default base URI and with - * the default REST packages. - */ - public ApexEditor() { - this(new ApexEditorParameters()); - } - - /** - * Starts the HTTP server for the Apex editor. - * - * @param parameters the parameters - */ - public ApexEditor(final ApexEditorParameters parameters) { - Assertions.argumentNotNull(parameters, "parameters may not be null"); - - LOGGER.debug("Apex RESTful editor starting . . ."); - - // Create a resource configuration that scans for JAX-RS resources and providers - final ResourceConfig rc = new ResourceConfig().packages(parameters.getRestPackages()); - rc.register(MultiPartFeature.class); - - // create and start a new instance of grizzly http server - // exposing the Jersey application at BASE_URI - server = GrizzlyHttpServerFactory.createHttpServer(parameters.getBaseUri(), rc); - - // Add static content - server.getServerConfiguration().addHttpHandler(new org.glassfish.grizzly.http.server.CLStaticHttpHandler( - ApexEditorMain.class.getClassLoader(), "/webapp/"), parameters.getStaticPath()); - - LOGGER.debug("Apex RESTful editor started"); - } - - /** - * Shut down the web server. - */ - public void shutdown() { - LOGGER.debug("Apex RESTful editor shutting down . . ."); - server.shutdown(); - LOGGER.debug("Apex RESTful editor shut down"); - } -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorException.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorException.java deleted file mode 100644 index a1bd28d..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorException.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.gui.editors.apex.rest; - -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; - -/** - * Exceptions from the Apex editor. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexEditorException extends ApexException { - private static final long serialVersionUID = 4867385591967018254L; - - /** - * Instantiates a new apex editor exception. - * - * @param message the message on the exception - */ - public ApexEditorException(final String message) { - super(message); - } - - /** - * Instantiates a new apex editor exception. - * - * @param message the message on the exception - * @param object the object that the exception was thrown on - */ - public ApexEditorException(final String message, final Object object) { - super(message, object); - } - - /** - * Instantiates a new apex editor exception. - * - * @param message the message on the exception - * @param ex the exception that caused this Apex exception - */ - public ApexEditorException(final String message, final Exception ex) { - super(message, ex); - } - - /** - * Instantiates a new apex editor exception. - * - * @param message the message on the exception - * @param ex the exception that caused this Apex exception - * @param object the object that the exception was thrown on - */ - public ApexEditorException(final String message, final Exception ex, final Object object) { - super(message, ex, object); - } - -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorMain.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorMain.java deleted file mode 100644 index 3a10759..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorMain.java +++ /dev/null @@ -1,225 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019-2021 Nordix Foundation. - * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.gui.editors.apex.rest; - -import java.io.PrintStream; -import java.util.concurrent.atomic.AtomicReference; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class is the main class that is used to launch the Apex editor from the command line. - */ -public class ApexEditorMain { - // Logger for this class - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEditorMain.class); - - // Recurring string constants - private static final String REST_ENDPOINT_PREFIX = "Apex Editor REST endpoint ("; - - /** - * The Enum EditorState holds the current state of the editor. - */ - // Editor state - public enum EditorState { - /** - * The editor is stopped. - */ - STOPPED, - /** - * The editor is ready to run. - */ - READY, - /** - * The editor is getting ready to run. - */ - INITIALIZING, - /** - * The editor is running. - */ - RUNNING - } - - private static final int EDITOR_RNNING_CHECK_TIMEOUT = 1000; - - private EditorState state; - - // The Apex editor this class is running - private ApexEditor apexEditor = null; - - // The parameters for the editor - private static final AtomicReference<ApexEditorParameters> parameters = new AtomicReference<>(); - - // Output and error streams for messages - private final PrintStream outStream; - - /** - * Constructor, kicks off the editor. - * - * @param args The command line arguments for the editor - * @param outStream The stream for output messages - */ - public ApexEditorMain(final String[] args, final PrintStream outStream) { - // Save the streams for output and error - this.outStream = outStream; - - // Editor parameter parsing - final var parser = new ApexEditorParameterParser(); - - try { - // Get and check the parameters - parameters.set(parser.parse(args)); - } catch (final ApexEditorParameterException e) { - throw new ApexEditorParameterException(REST_ENDPOINT_PREFIX + this + ") parameter error, " - + e.getMessage() + '\n' + parser.getHelp(ApexEditorMain.class.getName()), e); - } - if (parameters.get().isHelp()) { - throw new ApexEditorParameterException(parser.getHelp(ApexEditorMain.class.getName())); - } - - // Validate the parameters - final String validationMessage = parameters.get().validate(); - if (validationMessage.length() > 0) { - throw new ApexEditorParameterException(REST_ENDPOINT_PREFIX + this + ") parameters invalid, " - + validationMessage + '\n' + parser.getHelp(ApexEditorMain.class.getName())); - } - - state = EditorState.READY; - } - - /** - * Initialize the Apex editor. - */ - public void init() { - outStream.println(REST_ENDPOINT_PREFIX + this + ") starting at " - + parameters.get().getBaseUri().toString() + " . . ."); - - try { - state = EditorState.INITIALIZING; - - // Start the editor - apexEditor = new ApexEditor(parameters.get()); - - // Add a shutdown hook to shut down the editor when the process is exiting - Runtime.getRuntime().addShutdownHook(new Thread(new ApexEditorShutdownHook())); - - state = EditorState.RUNNING; - - if (parameters.get().getTimeToLive() == ApexEditorParameters.INFINITY_TIME_TO_LIVE) { - outStream.println(REST_ENDPOINT_PREFIX + this + ") started at " - + parameters.get().getBaseUri().toString()); - } else { - outStream.println(REST_ENDPOINT_PREFIX + this + ") started"); - } - - // Find out how long is left to wait - long timeRemaining = parameters.get().getTimeToLive(); - while (timeRemaining == ApexEditorParameters.INFINITY_TIME_TO_LIVE || timeRemaining > 0) { - // decrement the time to live in the non-infinity case - if (timeRemaining > 0) { - timeRemaining--; - } - - // Wait for a second - Thread.sleep(EDITOR_RNNING_CHECK_TIMEOUT); - } - } catch (final Exception e) { - String message = REST_ENDPOINT_PREFIX + this + ") failed at with error: " + e.getMessage(); - outStream.println(message); - LOGGER.warn(message, e); - } finally { - if (apexEditor != null) { - apexEditor.shutdown(); - apexEditor = null; - } - state = EditorState.STOPPED; - } - } - - /** - * Get the editor state. - * - * @return the state - */ - public EditorState getState() { - return state; - } - - /** - * {@inheritDoc}. - */ - @Override - public String toString() { - return this.getClass().getSimpleName() + ": Config=[" + parameters + "], State=" + this.getState(); - } - - /** - * Explicitly shut down the editor. - */ - public void shutdown() { - if (apexEditor != null) { - outStream.println(REST_ENDPOINT_PREFIX + this + ") shutting down"); - apexEditor.shutdown(); - } - state = EditorState.STOPPED; - outStream.println(REST_ENDPOINT_PREFIX + this + ") shut down"); - } - - /** - * Get the editor parameters. - * - * @return the parameters - */ - public static ApexEditorParameters getParameters() { - return parameters.get(); - } - - /** - * This class is a shutdown hook for the Apex editor command. - */ - private class ApexEditorShutdownHook implements Runnable { - /** - * {@inheritDoc}. - */ - @Override - public void run() { - if (apexEditor != null) { - apexEditor.shutdown(); - } - } - } - - /** - * Main method, main entry point for command. - * - * @param args The command line arguments for the editor - */ - public static void main(final String[] args) { - try { - final var editorMain = new ApexEditorMain(args, System.out); - editorMain.init(); - } catch (final Exception e) { - LOGGER.error("start failed", e); - } - } -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameterException.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameterException.java deleted file mode 100644 index f59a5eb..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameterException.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.gui.editors.apex.rest; - -/** - * A run time exception used to report parsing and parameter input errors. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexEditorParameterException extends IllegalArgumentException { - private static final long serialVersionUID = 6520231162404452427L; - - /** - * Create an ApexEditorParameterException with a message. - * - * @param message the message - */ - public ApexEditorParameterException(final String message) { - super(message); - } - - /** - * Create an ApexEditorParameterException with a message and an exception. - * - * @param message the message - * @param th the Throwable instance - */ - public ApexEditorParameterException(final String message, final Throwable th) { - super(message, th); - } -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameterParser.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameterParser.java deleted file mode 100644 index 0c8c648..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameterParser.java +++ /dev/null @@ -1,193 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. - * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.gui.editors.apex.rest; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Arrays; -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; - -/** - * This class reads and handles command line parameters to the Apex CLI editor. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexEditorParameterParser { - // Apache Commons CLI options - private Options options; - - private static final int COMMAND_HELP_MAX_LINE_WIDTH = 120; - - /** - * Construct the options for the CLI editor. - */ - public ApexEditorParameterParser() { - // @formatter:off - options = new Options(); - options.addOption("h", "help", false, "outputs the usage of this command"); - options.addOption( - Option - .builder("p") - .longOpt("port") - .desc("port to use for the Apex RESTful editor REST calls.") - .hasArg() - .argName("PORT") - .required(false) - .type(Number.class) - .build() - ); - options.addOption( - Option - .builder("t") - .longOpt("time-to-live") - .desc("the amount of time in seconds that the server will run for before terminating. " - + "Default value is " + ApexEditorParameters.INFINITY_TIME_TO_LIVE + " to run indefinitely.") - .hasArg() - .argName("TIME_TO_LIVE") - .required(false) - .type(Number.class) - .build() - ); - options.addOption( - Option - .builder("l") - .longOpt("listen") - .desc("the IP address to listen on. Default value is " + ApexEditorParameters.DEFAULT_SERVER_URI_ROOT - + " to restrict access to the local machine only.") - .hasArg() - .argName("ADDRESS") - .required(false) - .type(String.class) - .build() - ); - options.addOption( - Option - .builder("uuid") - .longOpt("upload-userid") - .desc("the userid to use for uploads. Default value is null. Must be specified if the upload-url " - + "parameter is specified") - .hasArg().argName("USERID") - .required(false) - .type(String.class) - .build() - ); - options.addOption( - Option - .builder("uurl") - .longOpt("upload-url") - .desc("the URL to use for uploads. Default value is null") - .hasArg() - .argName("UPLOAD_URL") - .required(false) - .type(String.class) - .build() - ); - // @formatter:on - } - - /** - * Parse the command line options. - * - * @param args The arguments - * @return the apex editor parameters - */ - public ApexEditorParameters parse(final String[] args) { - CommandLine commandLine = null; - try { - commandLine = new DefaultParser().parse(options, args); - } catch (final ParseException e) { - throw new ApexEditorParameterException("invalid command line arguments specified : " + e.getMessage()); - } - - final var parameters = new ApexEditorParameters(); - final String[] remainingArgs = commandLine.getArgs(); - - if (commandLine.getArgs().length > 0) { - throw new ApexEditorParameterException( - "too many command line arguments specified : " + Arrays.toString(remainingArgs)); - } - - if (commandLine.hasOption('h')) { - parameters.setHelp(true); - } - try { - if (commandLine.hasOption('p')) { - parameters.setRestPort(((Number) commandLine.getParsedOptionValue("port")).intValue()); - } - } catch (final ParseException e) { - throw new ApexEditorParameterException("error parsing argument \"port\" :" + e.getMessage(), e); - } - try { - if (commandLine.hasOption('t')) { - parameters.setTimeToLive(((Number) commandLine.getParsedOptionValue("time-to-live")).longValue()); - } - } catch (final ParseException e) { - throw new ApexEditorParameterException("error parsing argument \"time-to-live\" :" + e.getMessage(), e); - } - try { - if (commandLine.hasOption('l')) { - parameters.setListenAddress(commandLine.getParsedOptionValue("listen").toString()); - } - } catch (final ParseException e) { - throw new ApexEditorParameterException("error parsing argument \"listen-address\" :" + e.getMessage(), e); - } - try { - if (commandLine.hasOption("uuid")) { - parameters.setUploadUserid(commandLine.getParsedOptionValue("uuid").toString()); - } - } catch (final ParseException e) { - throw new ApexEditorParameterException("error parsing argument \"upload-uuid\" :" + e.getMessage(), e); - } - try { - if (commandLine.hasOption("uurl")) { - parameters.setUploadUrl(commandLine.getParsedOptionValue("uurl").toString()); - } - } catch (final ParseException e) { - throw new ApexEditorParameterException("error parsing argument \"upload-url\" :" + e.getMessage(), e); - } - - return parameters; - } - - /** - * Get help information. - * - * @param mainClassName the main class name - * @return the help - */ - public String getHelp(final String mainClassName) { - final var stringWriter = new StringWriter(); - final var stringPrintWriter = new PrintWriter(stringWriter); - - final var helpFormatter = new HelpFormatter(); - helpFormatter.printHelp(stringPrintWriter, COMMAND_HELP_MAX_LINE_WIDTH, mainClassName + " [options...] ", null, - options, 0, 1, ""); - - return stringWriter.toString(); - } -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameters.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameters.java deleted file mode 100644 index 58a4b33..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameters.java +++ /dev/null @@ -1,170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2022 Nordix Foundation. - * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.gui.editors.apex.rest; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import lombok.Data; -import lombok.Generated; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class reads and handles command line parameters to the Apex CLI editor. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -@Data -@Generated -public class ApexEditorParameters { - // Logger for this class - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEditorParameters.class); - - /** The default port for connecting to the Web editor on. */ - public static final int DEFAULT_REST_PORT = 18989; - - /** The connection is held up until killed on demand. */ - public static final int INFINITY_TIME_TO_LIVE = -1; - - // Base URI the HTTP server will listen on - private static final String DEFAULT_SERVER_URI_PREFIX = "http://"; - /** The server listens on localhost by default. */ - public static final String DEFAULT_SERVER_URI_ROOT = "localhost"; - private static final String DEFAULT_REST_PATH = "apexservices/"; - private static final String DEFAULT_STATIC_PATH = "/"; - - // Constants for port checks - private static final int MIN_USER_PORT = 1024; - private static final int MAX_USER_PORT = 65535; - - // Package that will field REST requests - private static final String[] DEFAULT_PACKAGES = new String[] { "org.onap.policy.gui.editors.apex.rest" }; - - // The editor parameters - private boolean help = false; - private int restPort = DEFAULT_REST_PORT; - private long timeToLive = INFINITY_TIME_TO_LIVE; - private String listenAddress = DEFAULT_SERVER_URI_ROOT; - private String uploadUrl = null; - private String uploadUserid = null; - - /** - * Validate. - * - * @return the string - */ - public String validate() { - return validatePort() + validateTimeToLive() + validateUrl() + validateUploadUrl() + validateUploadUserid(); - } - - /** - * Gets the base URI. - * - * @return the base URI - */ - public URI getBaseUri() { - return URI.create(DEFAULT_SERVER_URI_PREFIX + listenAddress + ':' + restPort + "/" + DEFAULT_REST_PATH); - } - - /** - * Gets the REST packages. - * - * @return the REST packages - */ - public String[] getRestPackages() { - return DEFAULT_PACKAGES; - } - - /** - * Gets the static path. - * - * @return the static path - */ - public String getStaticPath() { - return DEFAULT_STATIC_PATH; - } - - /** - * Validate port. - * - * @return a warning string, or an empty string - */ - private String validatePort() { - if (restPort < MIN_USER_PORT || restPort > MAX_USER_PORT) { - return "port must be between " + MIN_USER_PORT + " and " + MAX_USER_PORT + "\n"; - } else { - return ""; - } - } - - /** - * Validate URL. - * - * @return a warning string, or an empty string - */ - private String validateUrl() { - try { - new URI(getBaseUri().toString()).parseServerAuthority(); - return ""; - } catch (final URISyntaxException e) { - String message = "listen address is not valid. " + e.getMessage() + "\n"; - LOGGER.warn(message, e); - return message; - } - } - - /** - * Validate time to live. - * - * @return the string - */ - private String validateTimeToLive() { - if (timeToLive < -1) { - return "time to live must be greater than -1 (set to -1 to wait forever)\n"; - } else { - return ""; - } - } - - private String validateUploadUrl() { - if (!StringUtils.isBlank(uploadUrl)) { - try { - new URL(uploadUrl); - } catch (MalformedURLException murle) { - return "Specified upload-url parameter is an invalid URL" + murle.getMessage() + "\n"; - } - } - return ""; - } - - private String validateUploadUserid() { - if (!StringUtils.isEmpty(uploadUrl) && StringUtils.isEmpty(uploadUserid)) { - return "upload-userid parameter must be specified if the upload-url parameter is specified\n"; - } else { - return ""; - } - } -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResource.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResource.java index 009a570..764a20f 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResource.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResource.java @@ -24,178 +24,185 @@ package org.onap.policy.gui.editors.apex.rest.handling; import java.io.IOException; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.apex.model.modelapi.ApexApiResult.Result; import org.onap.policy.common.utils.resources.TextFileUtils; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** - * The class represents the root resource exposed at the base URL<br> The url to access this resource would be in the - * form {@code <baseURL>/rest/<session>/....} <br> For example: a PUT request to the following URL - * {@code http://localhost:8080/apex/rest/109/ContextSchema/Update}, with a JSON string payload containing the new - * {@code Schema} in the body, can be explained as: <ul> <li>The server or servlet is running at the base URL - * {@code http://localhost:8080/apex} <li>This resource {@code ApexRestEditorResource} is used because the path - * {@code rest/109} matches the {@code Path} filter specification for this Resource ({@code @Path("rest/{session}")}), - * where the {@code int} path parameter {@code session} is assigned the {@code int} value {@code 109} <li>The path - * {@code ContextSchema/Update} redirects this call to the method {@link #updateContextSchema(String)}, which should be - * a {@link javax.ws.rs.PUT}, with a single String in the body/payload which gets mapped to the single String parameter - * for the method. <li>So, in summary, the REST request updates a {@code ContextSchema} as specified in the payload for - * {@code session} number {@code 109} </ul> + * The class represents the root resource exposed at the base URL<br> + * The url to access this resource would be in the form {@code <baseURL>/policy/gui/v1/apex/editor/<session>/....}, + * for example: {@code http://localhost:8080/policy/gui/v1/apex/editor/109/ContextSchema/Update}<br> * * <b>Note:</b> An allocated {@code Session} identifier must be included in (almost) all requests. Models for different * {@code Session} identifiers are completely isolated from one another. * - * <b>Note:</b> To create a new {@code Session}, and have a new session ID allocated use {@link javax.ws.rs.GET} request - * to {@code <baseURL>/rest/-1/Session/Create} (for example: {@code http://localhost:8080/apex/rest/-1/Session/Create} ) - * + * <b>Note:</b> To create a new {@code Session}, and have a new session ID allocated use a GET request to + * {@code <baseURL>/policy/gui/v1/apex/editor/-1/Session/Create} */ -@Path("editor/{session}") -@Produces({ MediaType.APPLICATION_JSON }) -@Consumes({ MediaType.APPLICATION_JSON }) +@RestController +@RequestMapping("/policy/gui/v1/apex/editor") public class ApexEditorRestResource implements RestCommandHandler { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEditorRestResource.class); - // Location of the periodi event template + // Location of the periodic event template private static final String PERIODIC_EVENT_TEMPLATE = "src/main/resources/templates/PeriodicEventTemplate.json"; - // Recurring string constants - private static final String NAME = "name"; - private static final String VERSION = "version"; + // Recurring string constants private static final String REST_COMMAND_NOT_RECOGNISED = "REST command not recognised"; private static final String OK = ": OK"; private static final String NOT_OK = ": Not OK"; private static final String SESSION_CREATE = "Session/Create"; private static final String SESSION_CREATE_NOT_OK = "Session/Create: Not OK"; + // The session handler for sessions on the Apex editor + private final RestSessionHandler sessionHandler; - private static final RestSessionHandler SESSION_HANDLER = new RestSessionHandler(); // Handlers for the various parts of an Apex model - //@formatter:off - - private static final ModelHandler MODEL_HANDLER = new ModelHandler(); - private static final KeyInfoHandler KEY_INFO_HANDLER = new KeyInfoHandler(); - private static final ContextSchemaHandler CONTEXT_SCHEMA_HANDLER = new ContextSchemaHandler(); - private static final ContextAlbumHandler CONTEXT_ALBUM_HANDLER = new ContextAlbumHandler(); - private static final EventHandler EVENT_HANDLER = new EventHandler(); - private static final TaskHandler TASK_HANDLER = new TaskHandler(); - private static final PolicyHandler POLICY_HANDLER = new PolicyHandler(); - - //@formatter:on - // The ID of this session. This gets injected from the URL. - - @PathParam("session") - private int sessionId = -1; + private final ModelHandler modelHandler; + private final KeyInfoHandler keyInfoHandler; + private final ContextSchemaHandler contextSchemaHandler; + private final ContextAlbumHandler contextAlbumHandler; + private final EventHandler eventHandler; + private final TaskHandler taskHandler; + private final PolicyHandler policyHandler; + + /** + * Autowired constructor. + */ + @Autowired + public ApexEditorRestResource(RestSessionHandler sessionHandler, + ModelHandler modelHandler, + KeyInfoHandler keyInfoHandler, + ContextSchemaHandler contextSchemaHandler, + ContextAlbumHandler contextAlbumHandler, + EventHandler eventHandler, + TaskHandler taskHandler, + PolicyHandler policyHandler) { + this.sessionHandler = sessionHandler; + this.modelHandler = modelHandler; + this.keyInfoHandler = keyInfoHandler; + this.contextSchemaHandler = contextSchemaHandler; + this.contextAlbumHandler = contextAlbumHandler; + this.eventHandler = eventHandler; + this.taskHandler = taskHandler; + this.policyHandler = policyHandler; + } /** * Creates a new session. Always call this method with sessionID -1, whereby a new sessionID will be allocated. If * successful the new sessionID will be available in the first message in the result. * + * @param sessionId the ID of this session. This gets injected from the URL. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()}. This includes the session id * for this session. */ - @GET - @Path("Session/Create") - public ApexApiResult createSession() { + @GetMapping("/{sessionId}/Session/Create") + public ApexApiResult createSession(@PathVariable final int sessionId) { if (sessionId != -1) { return new ApexApiResult(Result.FAILED, "Session ID must be set to -1 to create sessions: " + sessionId); } var result = new ApexApiResult(); - SESSION_HANDLER.createSession(result); + sessionHandler.createSession(result); return result; } /** * Load the model from a JSON string for this session. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed. The returned value(s) will be similar to {@code AxPolicyModel}, * with merged {@code AxKeyInfo} for the root object. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @PUT - @Path("/Model/Load") - public ApexApiResult loadFromString(final String jsonString) { - return processRestCommand(RestCommandType.MODEL, RestCommand.LOAD, jsonString); + @PutMapping("/{sessionId}/Model/Load") + public ApexApiResult loadFromString(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.LOAD, jsonString); } /** * Analyse the model and return analysis results. If successful the analysis results will be available in the * messages in the result. * + * @param sessionId the ID of this session. This gets injected from the URL. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Model/Analyse") - public ApexApiResult analyse() { - return processRestCommand(RestCommandType.MODEL, RestCommand.ANALYSE); + @GetMapping("/{sessionId}/Model/Analyse") + public ApexApiResult analyse(@PathVariable final int sessionId) { + return processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.ANALYSE); } /** * Validate the model and return validation results. If successful the validation results will be available in the * messages in the result. * + * @param sessionId the ID of this session. This gets injected from the URL. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Model/Validate") - public ApexApiResult validate() { - return processRestCommand(RestCommandType.MODEL, RestCommand.VALIDATE); + @GetMapping("/{sessionId}/Model/Validate") + public ApexApiResult validate(@PathVariable final int sessionId) { + return processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.VALIDATE); } /** * Creates the new model model for this session. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed containing the new model. See {@code BeanModel} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @POST - @Path("Model/Create") - public ApexApiResult createModel(final String jsonString) { - return processRestCommand(RestCommandType.MODEL, RestCommand.CREATE, jsonString); + @PostMapping("/{sessionId}/Model/Create") + public ApexApiResult createModel(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.CREATE, jsonString); } /** * Update the model for this session. - * + *processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.CREATE, jsonString); + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed containing the updated model. See {@code BeanModel} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @PUT - @Path("Model/Update") - public ApexApiResult updateModel(final String jsonString) { - return processRestCommand(RestCommandType.MODEL, RestCommand.UPDATE, jsonString); + @PutMapping("/{sessionId}/Model/Update") + public ApexApiResult updateModel(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.UPDATE, jsonString); } /** * Gets the key for the model for this session. If successful the model key will be available in the first message * in the result. See {@code AxKey} * + * @param sessionId the ID of this session. This gets injected from the URL. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Model/GetKey") - public ApexApiResult getModelKey() { - return processRestCommand(RestCommandType.MODEL, RestCommand.GET_KEY); + @GetMapping("/{sessionId}/Model/GetKey") + public ApexApiResult getModelKey(@PathVariable final int sessionId) { + return processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.GET_KEY); } /** @@ -203,25 +210,24 @@ public class ApexEditorRestResource implements RestCommandHandler { * result. The returned value will be similar to a {@code AxPolicyModel}, with merged {@code AxKeyInfo} for the root * object. * + * @param sessionId the ID of this session. This gets injected from the URL. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Model/Get") - public ApexApiResult listModel() { - return processRestCommand(RestCommandType.MODEL, RestCommand.LIST); + @GetMapping("/{sessionId}/Model/Get") + public ApexApiResult listModel(@PathVariable final int sessionId) { + return processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.LIST); } /** * Download the model for this session as a String. * + * @param sessionId the ID of this session. This gets injected from the URL. * @return the model represented as a YAML string. See {@code AxPolicyModel} */ - @GET - @Produces(MediaType.TEXT_PLAIN) - @Path("Model/Download") - public String downloadModel() { - ApexApiResult result = processRestCommand(RestCommandType.MODEL, RestCommand.DOWNLOAD); + @GetMapping(value = "/{sessionId}/Model/Download", produces = MediaType.TEXT_PLAIN_VALUE) + public String downloadModel(@PathVariable final int sessionId) { + ApexApiResult result = processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.DOWNLOAD); if (result != null && result.isOk()) { return result.getMessage(); } else { @@ -232,68 +238,72 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * Uploads a TOSCA Policy Model to a configured endpoint. * - * @param userId the userId to use for upload. If blank, the commandline - * parameter "upload-userid" is used. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param userId the userId to use for upload. If blank, the Spring + * config parameter "apex-editor.upload-userid" is used. * @return an ApexAPIResult that contains the operation status and success/error messages */ - @GET - @Path("Model/Upload") - public ApexApiResult uploadModel(@QueryParam("userId") final String userId) { - return processRestCommand(RestCommandType.MODEL, RestCommand.UPLOAD, userId); + @GetMapping("/{sessionId}/Model/Upload") + public ApexApiResult uploadModel(@PathVariable final int sessionId, + @RequestParam(required = false) final String userId) { + return processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.UPLOAD, userId); } /** * Delete the model for this session. * + * @param sessionId the ID of this session. This gets injected from the URL. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @DELETE - @Path("Model/Delete") - public ApexApiResult deleteModel() { - return processRestCommand(RestCommandType.MODEL, RestCommand.DELETE); + @DeleteMapping("/{sessionId}/Model/Delete") + public ApexApiResult deleteModel(@PathVariable final int sessionId) { + return processRestCommand(sessionId, RestCommandType.MODEL, RestCommand.DELETE); } /** * List key information with the given key names/versions. If successful the result(s) will be available in the * result messages. See {@code AxKeyInfo} * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("KeyInformation/Get") - public ApexApiResult listKeyInformation(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.KEY_INFO, RestCommand.LIST, name, version); + @GetMapping("/{sessionId}/KeyInformation/Get") + public ApexApiResult listKeyInformation(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.KEY_INFO, RestCommand.LIST, name, version); } /** * Creates a context schema with the information in the JSON string passed. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed. See {@code BeanContextSchema} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @POST - @Path("ContextSchema/Create") - public ApexApiResult createContextSchema(final String jsonString) { - return processRestCommand(RestCommandType.CONTEXT_SCHEMA, RestCommand.CREATE, jsonString); + @PostMapping("/{sessionId}/ContextSchema/Create") + public ApexApiResult createContextSchema(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.CONTEXT_SCHEMA, RestCommand.CREATE, jsonString); } /** * Update a context schema with the information in the JSON string passed. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed. See {@code BeanContextSchema} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @PUT - @Path("ContextSchema/Update") - public ApexApiResult updateContextSchema(final String jsonString) { - return processRestCommand(RestCommandType.CONTEXT_SCHEMA, RestCommand.UPDATE, jsonString); + @PutMapping("/{sessionId}/ContextSchema/Update") + public ApexApiResult updateContextSchema(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.CONTEXT_SCHEMA, RestCommand.UPDATE, jsonString); } /** @@ -301,73 +311,78 @@ public class ApexEditorRestResource implements RestCommandHandler { * result messages. The returned value(s) will be similar to {@code AxContextSchema}, with merged {@code AxKeyInfo} * for the root object. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("ContextSchema/Get") - public ApexApiResult listContextSchemas(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.CONTEXT_SCHEMA, RestCommand.LIST, name, version); + @GetMapping("/{sessionId}/ContextSchema/Get") + public ApexApiResult listContextSchemas(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.CONTEXT_SCHEMA, RestCommand.LIST, name, version); } /** * Delete context schemas with the given key names/versions. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @DELETE - @Path("ContextSchema/Delete") - public ApexApiResult deleteContextSchema(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.CONTEXT_SCHEMA, RestCommand.DELETE, name, version); + @DeleteMapping("/{sessionId}/ContextSchema/Delete") + public ApexApiResult deleteContextSchema(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.CONTEXT_SCHEMA, RestCommand.DELETE, name, version); } /** * Validate context schemas with the given key names/versions. The result(s) will be available in the result * messages. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Validate/ContextSchema") - public ApexApiResult validateContextSchemas(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.CONTEXT_SCHEMA, RestCommand.VALIDATE, name, version); + @GetMapping("/{sessionId}/Validate/ContextSchema") + public ApexApiResult validateContextSchemas(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.CONTEXT_SCHEMA, RestCommand.VALIDATE, name, version); } /** * Creates a context album with the information in the JSON string passed. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed. See {@code BeanContextAlbum} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @POST - @Path("ContextAlbum/Create") - public ApexApiResult createContextAlbum(final String jsonString) { - return processRestCommand(RestCommandType.CONTEXT_ALBUM, RestCommand.CREATE, jsonString); + @PostMapping("/{sessionId}/ContextAlbum/Create") + public ApexApiResult createContextAlbum(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.CONTEXT_ALBUM, RestCommand.CREATE, jsonString); } /** * Update a context album with the information in the JSON string passed. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed. See {@code BeanContextAlbum} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @PUT - @Path("ContextAlbum/Update") - public ApexApiResult updateContextAlbum(final String jsonString) { - return processRestCommand(RestCommandType.CONTEXT_ALBUM, RestCommand.UPDATE, jsonString); + @PutMapping("/{sessionId}/ContextAlbum/Update") + public ApexApiResult updateContextAlbum(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.CONTEXT_ALBUM, RestCommand.UPDATE, jsonString); } /** @@ -375,73 +390,78 @@ public class ApexEditorRestResource implements RestCommandHandler { * result messages. The returned value(s) will be similar to {@code AxContextAlbum}, with merged {@code AxKeyInfo} * for the root object. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("ContextAlbum/Get") - public ApexApiResult listContextAlbums(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.CONTEXT_ALBUM, RestCommand.LIST, name, version); + @GetMapping("/{sessionId}/ContextAlbum/Get") + public ApexApiResult listContextAlbums(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.CONTEXT_ALBUM, RestCommand.LIST, name, version); } /** * Delete context albums with the given key names/versions. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @DELETE - @Path("ContextAlbum/Delete") - public ApexApiResult deleteContextAlbum(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.CONTEXT_ALBUM, RestCommand.DELETE, name, version); + @DeleteMapping("/{sessionId}/ContextAlbum/Delete") + public ApexApiResult deleteContextAlbum(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.CONTEXT_ALBUM, RestCommand.DELETE, name, version); } /** * Validate context albums with the given key names/versions. The result(s) will be available in the result * messages. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Validate/ContextAlbum") - public ApexApiResult validateContextAlbums(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.CONTEXT_ALBUM, RestCommand.VALIDATE, name, version); + @GetMapping("/{sessionId}/Validate/ContextAlbum") + public ApexApiResult validateContextAlbums(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.CONTEXT_ALBUM, RestCommand.VALIDATE, name, version); } /** * Creates an event with the information in the JSON string passed. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed. See {@code BeanEvent} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @POST - @Path("Event/Create") - public ApexApiResult createEvent(final String jsonString) { - return processRestCommand(RestCommandType.EVENT, RestCommand.CREATE, jsonString); + @PostMapping("/{sessionId}/Event/Create") + public ApexApiResult createEvent(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.EVENT, RestCommand.CREATE, jsonString); } /** * Update an event with the information in the JSON string passed. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed. See {@code BeanEvent} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @PUT - @Path("Event/Update") - public ApexApiResult updateEvent(final String jsonString) { - return processRestCommand(RestCommandType.EVENT, RestCommand.UPDATE, jsonString); + @PutMapping("/{sessionId}/Event/Update") + public ApexApiResult updateEvent(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.EVENT, RestCommand.UPDATE, jsonString); } /** @@ -449,69 +469,77 @@ public class ApexEditorRestResource implements RestCommandHandler { * messages. The returned value(s) will be similar to {@code AxEvent}, with merged {@code AxKeyInfo} for the root * object. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Event/Get") - public ApexApiResult listEvent(@QueryParam(NAME) final String name, @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.EVENT, RestCommand.LIST, name, version); + @GetMapping("/{sessionId}/Event/Get") + public ApexApiResult listEvent(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.EVENT, RestCommand.LIST, name, version); } /** * Delete events with the given key names/versions. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @DELETE - @Path("Event/Delete") - public ApexApiResult deleteEvent(@QueryParam(NAME) final String name, @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.EVENT, RestCommand.DELETE, name, version); + @DeleteMapping("/{sessionId}/Event/Delete") + public ApexApiResult deleteEvent(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.EVENT, RestCommand.DELETE, name, version); } /** * Validate events with the given key names/versions. The result(s) will be available in the result messages. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Validate/Event") - public ApexApiResult validateEvent(@QueryParam(NAME) final String name, @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.EVENT, RestCommand.VALIDATE, name, version); + @GetMapping("/{sessionId}/Validate/Event") + public ApexApiResult validateEvent(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.EVENT, RestCommand.VALIDATE, name, version); } /** * Creates a task with the information in the JSON string passed. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed. See {@code BeanTask} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @POST - @Path("Task/Create") - public ApexApiResult createTask(final String jsonString) { - return processRestCommand(RestCommandType.TASK, RestCommand.CREATE, jsonString); + @PostMapping("/{sessionId}/Task/Create") + public ApexApiResult createTask(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.TASK, RestCommand.CREATE, jsonString); } /** * Update a task with the information in the JSON string passed. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed. See {@code BeanTask} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @PUT - @Path("Task/Update") - public ApexApiResult updateTask(final String jsonString) { - return processRestCommand(RestCommandType.TASK, RestCommand.UPDATE, jsonString); + @PutMapping("/{sessionId}/Task/Update") + public ApexApiResult updateTask(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.TASK, RestCommand.UPDATE, jsonString); } /** @@ -519,74 +547,81 @@ public class ApexEditorRestResource implements RestCommandHandler { * messages. The returned value(s) will be similar to {@code AxTask}, with merged {@code AxKeyInfo} for the root * object. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Task/Get") - public ApexApiResult listTask(@QueryParam(NAME) final String name, @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.TASK, RestCommand.LIST, name, version); + @GetMapping("/{sessionId}/Task/Get") + public ApexApiResult listTask(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.TASK, RestCommand.LIST, name, version); } /** * Delete tasks with the given key names/versions. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @DELETE - @Path("Task/Delete") - public ApexApiResult deleteTask(@QueryParam(NAME) final String name, @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.TASK, RestCommand.DELETE, name, version); + @DeleteMapping("/{sessionId}/Task/Delete") + public ApexApiResult deleteTask(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.TASK, RestCommand.DELETE, name, version); } /** * Validate tasks with the given key names/versions. The result(s) will be available in the result messages. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Validate/Task") - public ApexApiResult validateTask(@QueryParam(NAME) final String name, @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.TASK, RestCommand.VALIDATE, name, version); + @GetMapping("/{sessionId}/Validate/Task") + public ApexApiResult validateTask(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.TASK, RestCommand.VALIDATE, name, version); } /** * Creates a policy with the information in the JSON string passed. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param jsonString the JSON string to be parsed See {@code BeanPolicy} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @POST - @Path("Policy/Create") - public ApexApiResult createPolicy(final String jsonString) { - return processRestCommand(RestCommandType.POLICY, RestCommand.CREATE, jsonString); + @PostMapping("/{sessionId}/Policy/Create") + public ApexApiResult createPolicy(@PathVariable final int sessionId, + @RequestBody(required = false) final String jsonString) { + return processRestCommand(sessionId, RestCommandType.POLICY, RestCommand.CREATE, jsonString); } /** * Update a policy with the information in the JSON string passed. * + * @param sessionId the ID of this session. This gets injected from the URL. * @param firstStatePeriodic indicates if periodic event should be created and added to model * @param jsonString the JSON string to be parsed. See {@code BeanPolicy} * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @PUT - @Path("Policy/Update") - public ApexApiResult updatePolicy(@QueryParam("firstStatePeriodic") final boolean firstStatePeriodic, - final String jsonString) { - - ApexApiResult result = processRestCommand(RestCommandType.POLICY, RestCommand.UPDATE, jsonString); + @PutMapping("/{sessionId}/Policy/Update") + public ApexApiResult updatePolicy(@PathVariable final int sessionId, + @RequestParam(required = false) final boolean firstStatePeriodic, + @RequestBody(required = false) final String jsonString) { + ApexApiResult result = processRestCommand(sessionId, RestCommandType.POLICY, RestCommand.UPDATE, jsonString); if (result != null && result.isOk() && firstStatePeriodic) { - result = createPeriodicEvent(); + result = createPeriodicEvent(sessionId); } return result; } @@ -596,43 +631,49 @@ public class ApexEditorRestResource implements RestCommandHandler { * messages. The returned value(s) will be similar to {@code AxPolicy}, with merged {@code AxKeyInfo} for the root * object. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @GET - @Path("Policy/Get") - public ApexApiResult listPolicy(@QueryParam(NAME) final String name, @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.POLICY, RestCommand.LIST, name, version); + @GetMapping("/{sessionId}/Policy/Get") + public ApexApiResult listPolicy(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.POLICY, RestCommand.LIST, name, version); } /** * Delete policies with the given key names/versions. * - * @param name the name to search for. If null or empty, then all names will be queried - * @param version the version to search for. If null then all versions will be searched for. + * @param sessionId the ID of this session. This gets injected from the URL. + * @param name the name to search for. If null or empty, then all names will be queried + * @param version the version to search for. If null then all versions will be searched for. * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ - @DELETE - @Path("Policy/Delete") - public ApexApiResult deletePolicy(@QueryParam(NAME) final String name, @QueryParam(VERSION) final String version) { - return processRestCommand(RestCommandType.POLICY, RestCommand.DELETE, name, version); + @DeleteMapping("/{sessionId}/Policy/Delete") + public ApexApiResult deletePolicy(@PathVariable final int sessionId, + @RequestParam(required = false) final String name, + @RequestParam(required = false) final String version) { + return processRestCommand(sessionId, RestCommandType.POLICY, RestCommand.DELETE, name, version); } /** * This method routes REST commands that take no parameters to their caller. * + * @param sessionId the Apex editor session ID * @param commandType the type of REST command to process * @param command the REST command to process * @return the result of the REST command */ - private ApexApiResult processRestCommand(final RestCommandType commandType, final RestCommand command) { + private ApexApiResult processRestCommand(final int sessionId, final RestCommandType commandType, + final RestCommand command) { LOGGER.entry(commandType); try { var result = new ApexApiResult(); - RestSession session = SESSION_HANDLER.getSession(sessionId, result); + RestSession session = sessionHandler.getSession(sessionId, result); if (session == null) { return result; } @@ -649,17 +690,18 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * This method routes REST commands that take a JSON string to their caller. * + * @param sessionId the Apex editor session ID * @param commandType the type of REST command to process * @param command the REST command to process * @param jsonString the JSON string received in the REST request * @return the result of the REST command */ - private ApexApiResult processRestCommand(final RestCommandType commandType, final RestCommand command, - final String jsonString) { + private ApexApiResult processRestCommand(final int sessionId, final RestCommandType commandType, + final RestCommand command, final String jsonString) { LOGGER.entry(commandType, jsonString); try { var result = new ApexApiResult(); - RestSession session = SESSION_HANDLER.getSession(sessionId, result); + RestSession session = sessionHandler.getSession(sessionId, result); if (session == null) { return result; } @@ -676,18 +718,19 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * This method routes REST commands that take a name and version to their caller. * + * @param sessionId the Apex editor session ID * @param commandType the type of REST command to process * @param command the REST command to process * @param name the name received in the REST request * @param version the name received in the REST request * @return the result of the REST command */ - private ApexApiResult processRestCommand(final RestCommandType commandType, final RestCommand command, - final String name, final String version) { + private ApexApiResult processRestCommand(final int sessionId, final RestCommandType commandType, + final RestCommand command, final String name, final String version) { LOGGER.entry(commandType, name, version); try { var result = new ApexApiResult(); - RestSession session = SESSION_HANDLER.getSession(sessionId, result); + RestSession session = sessionHandler.getSession(sessionId, result); if (session == null) { return result; } @@ -711,22 +754,22 @@ public class ApexEditorRestResource implements RestCommandHandler { */ @Override public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType, - final RestCommand command) { + final RestCommand command) { switch (commandType) { case MODEL: - return MODEL_HANDLER.executeRestCommand(session, commandType, command); + return modelHandler.executeRestCommand(session, commandType, command); case KEY_INFO: - return KEY_INFO_HANDLER.executeRestCommand(session, commandType, command); + return keyInfoHandler.executeRestCommand(session, commandType, command); case CONTEXT_SCHEMA: - return CONTEXT_SCHEMA_HANDLER.executeRestCommand(session, commandType, command); + return contextSchemaHandler.executeRestCommand(session, commandType, command); case CONTEXT_ALBUM: - return CONTEXT_ALBUM_HANDLER.executeRestCommand(session, commandType, command); + return contextAlbumHandler.executeRestCommand(session, commandType, command); case EVENT: - return EVENT_HANDLER.executeRestCommand(session, commandType, command); + return eventHandler.executeRestCommand(session, commandType, command); case TASK: - return TASK_HANDLER.executeRestCommand(session, commandType, command); + return taskHandler.executeRestCommand(session, commandType, command); case POLICY: - return POLICY_HANDLER.executeRestCommand(session, commandType, command); + return policyHandler.executeRestCommand(session, commandType, command); default: return new ApexApiResult(Result.FAILED, REST_COMMAND_NOT_RECOGNISED); } @@ -743,22 +786,22 @@ public class ApexEditorRestResource implements RestCommandHandler { */ @Override public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType, - final RestCommand command, final String jsonString) { + final RestCommand command, final String jsonString) { switch (commandType) { case MODEL: - return MODEL_HANDLER.executeRestCommand(session, commandType, command, jsonString); + return modelHandler.executeRestCommand(session, commandType, command, jsonString); case KEY_INFO: - return KEY_INFO_HANDLER.executeRestCommand(session, commandType, command, jsonString); + return keyInfoHandler.executeRestCommand(session, commandType, command, jsonString); case CONTEXT_SCHEMA: - return CONTEXT_SCHEMA_HANDLER.executeRestCommand(session, commandType, command, jsonString); + return contextSchemaHandler.executeRestCommand(session, commandType, command, jsonString); case CONTEXT_ALBUM: - return CONTEXT_ALBUM_HANDLER.executeRestCommand(session, commandType, command, jsonString); + return contextAlbumHandler.executeRestCommand(session, commandType, command, jsonString); case EVENT: - return EVENT_HANDLER.executeRestCommand(session, commandType, command, jsonString); + return eventHandler.executeRestCommand(session, commandType, command, jsonString); case TASK: - return TASK_HANDLER.executeRestCommand(session, commandType, command, jsonString); + return taskHandler.executeRestCommand(session, commandType, command, jsonString); case POLICY: - return POLICY_HANDLER.executeRestCommand(session, commandType, command, jsonString); + return policyHandler.executeRestCommand(session, commandType, command, jsonString); default: return new ApexApiResult(Result.FAILED, REST_COMMAND_NOT_RECOGNISED); } @@ -776,22 +819,22 @@ public class ApexEditorRestResource implements RestCommandHandler { */ @Override public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType, - final RestCommand command, final String name, final String version) { + final RestCommand command, final String name, final String version) { switch (commandType) { case MODEL: - return MODEL_HANDLER.executeRestCommand(session, commandType, command, name, version); + return modelHandler.executeRestCommand(session, commandType, command, name, version); case KEY_INFO: - return KEY_INFO_HANDLER.executeRestCommand(session, commandType, command, name, version); + return keyInfoHandler.executeRestCommand(session, commandType, command, name, version); case CONTEXT_SCHEMA: - return CONTEXT_SCHEMA_HANDLER.executeRestCommand(session, commandType, command, name, version); + return contextSchemaHandler.executeRestCommand(session, commandType, command, name, version); case CONTEXT_ALBUM: - return CONTEXT_ALBUM_HANDLER.executeRestCommand(session, commandType, command, name, version); + return contextAlbumHandler.executeRestCommand(session, commandType, command, name, version); case EVENT: - return EVENT_HANDLER.executeRestCommand(session, commandType, command, name, version); + return eventHandler.executeRestCommand(session, commandType, command, name, version); case TASK: - return TASK_HANDLER.executeRestCommand(session, commandType, command, name, version); + return taskHandler.executeRestCommand(session, commandType, command, name, version); case POLICY: - return POLICY_HANDLER.executeRestCommand(session, commandType, command, name, version); + return policyHandler.executeRestCommand(session, commandType, command, name, version); default: return new ApexApiResult(Result.FAILED, REST_COMMAND_NOT_RECOGNISED); } @@ -800,32 +843,18 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * Create a periodic event from the periodic event template. */ - private ApexApiResult createPeriodicEvent() { + private ApexApiResult createPeriodicEvent(final int sessionId) { String periodicEventJsonString; try { periodicEventJsonString = TextFileUtils.getTextFileAsString(PERIODIC_EVENT_TEMPLATE); } catch (IOException ioException) { - String message = "read of periodic event tempalte from " + PERIODIC_EVENT_TEMPLATE + "failed: " + String message = "read of periodic event template from " + PERIODIC_EVENT_TEMPLATE + "failed: " + ioException.getMessage(); LOGGER.debug(message, ioException); return new ApexApiResult(Result.FAILED, message); } - return processRestCommand(RestCommandType.EVENT, RestCommand.CREATE, periodicEventJsonString); - } - - /* - * This method is used only for testing and is used to cause an exception on calls from unit test to test exception - * handling. - */ - protected static int createCorruptSession() { - final var apexEditorRestResource = new ApexEditorRestResource(); - final ApexApiResult result = apexEditorRestResource.createSession(); - final var corruptSessionId = Integer.parseInt(result.getMessages().get(0)); - - SESSION_HANDLER.setCorruptSession(corruptSessionId); - - return corruptSessionId; + return processRestCommand(sessionId, RestCommandType.EVENT, RestCommand.CREATE, periodicEventJsonString); } } diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ContextAlbumHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ContextAlbumHandler.java index 50a61e5..13d46bc 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ContextAlbumHandler.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ContextAlbumHandler.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -28,10 +28,12 @@ import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanContextAlbum; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +import org.springframework.stereotype.Service; /** * This class handles commands on context albums in Apex models. */ +@Service public class ContextAlbumHandler implements RestCommandHandler { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(ContextAlbumHandler.class); diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ContextSchemaHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ContextSchemaHandler.java index 030bdeb..211acfa 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ContextSchemaHandler.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ContextSchemaHandler.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,10 +26,12 @@ import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanContextSchema; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +import org.springframework.stereotype.Service; /** * This class handles commands on context schemas in Apex models. */ +@Service public class ContextSchemaHandler implements RestCommandHandler { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(ContextSchemaHandler.class); diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/EventHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/EventHandler.java index a66ce63..a5113e9 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/EventHandler.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/EventHandler.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation. + * Modifications Copyright (C) 2019-2022 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -31,10 +31,12 @@ import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanEvent; import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanField; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +import org.springframework.stereotype.Service; /** * This class handles commands on events in Apex models. */ +@Service public class EventHandler implements RestCommandHandler { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventHandler.class); diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/KeyInfoHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/KeyInfoHandler.java index eec8e6c..774d45f 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/KeyInfoHandler.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/KeyInfoHandler.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +22,12 @@ package org.onap.policy.gui.editors.apex.rest.handling; import org.onap.policy.apex.model.modelapi.ApexApiResult; +import org.springframework.stereotype.Service; /** * This class handles commands on key information in Apex models. */ +@Service public class KeyInfoHandler implements RestCommandHandler { /** * {@inheritDoc}. diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ModelHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ModelHandler.java index 18dc227..07051f2 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ModelHandler.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ModelHandler.java @@ -27,23 +27,31 @@ import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.basicmodel.concepts.AxKey; import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.apex.model.modelapi.ApexApiResult.Result; +import org.onap.policy.apex.model.modelapi.ApexModel; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanModel; +import org.onap.policy.gui.editors.apex.rest.handling.plugin.upload.PolicyUploadHandler; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; /** * This class handles commands on Apex models. */ +@Service public class ModelHandler implements RestCommandHandler { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(ModelHandler.class); + private final PolicyUploadHandler policyUploadHandler; + // Recurring string constants private static final String OK = ": OK"; private static final String NOT_OK = ": Not OK"; @@ -55,6 +63,11 @@ public class ModelHandler implements RestCommandHandler { private static final String POLICY_KEY = "policyKey"; private static final String APEX_KEY_INFO = "apexKeyInfo"; + @Autowired + public ModelHandler(PolicyUploadHandler policyUploadHandler) { + this.policyUploadHandler = policyUploadHandler; + } + /** * {@inheritDoc}. */ @@ -268,24 +281,41 @@ public class ModelHandler implements RestCommandHandler { ApexApiResult result = session.downloadModel(); - LOGGER.exit("Model/Download" + (result != null && result.isOk() ? OK : NOT_OK)); + LOGGER.exit("Model/Download" + (result.isOk() ? OK : NOT_OK)); return result; } /** - * Upload the model for this session to the configured URL. + * Upload the model for this session as a TOSCA service template YAML string to the configured URL. * * @param session the Apex model editing session - * @param userId the userId to use for upload. If blank, the commandline - * parameter "upload-userid" is used. + * @param userId the userId to use for upload. If blank, the Spring + * config parameter "apex-editor.upload-userid" is used. * @return a result indicating if the upload was successful or not */ private ApexApiResult uploadModel(final RestSession session, String userId) { LOGGER.entry(); - ApexApiResult result = session.uploadModel(userId); + // Get the model in TOSCA format + ApexApiResult downloadResult = downloadModel(session); + if (downloadResult.isNok()) { + LOGGER.exit("Model/Upload" + NOT_OK); + return downloadResult; + } + String toscaServiceTemplate = downloadResult.getMessage(); + + ApexModel apexModel = session.getApexModel(); + ApexModel apexModelEdited = session.getApexModelEdited(); + ApexModel apexModelBeingUploaded = (apexModelEdited == null ? apexModel : apexModelEdited); + + AxArtifactKey policyModelKey = apexModelBeingUploaded.getPolicyModel().getKey(); + + String policyModelUUid = apexModelBeingUploaded.getPolicyModel().getKeyInformation().get(policyModelKey) + .getUuid().toString(); + + var result = policyUploadHandler.doUpload(toscaServiceTemplate, policyModelKey, policyModelUUid, userId); - LOGGER.exit("Model/Download" + (result != null && result.isOk() ? OK : NOT_OK)); + LOGGER.exit("Model/Upload" + (result != null && result.isOk() ? OK : NOT_OK)); return result; } diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/PolicyHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/PolicyHandler.java index f296083..becbd4f 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/PolicyHandler.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/PolicyHandler.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -35,10 +35,12 @@ import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanStateOutput; import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanStateTaskRef; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +import org.springframework.stereotype.Service; /** * This class handles commands on policies in Apex models. */ +@Service public class PolicyHandler implements RestCommandHandler { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(PolicyHandler.class); diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSession.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSession.java index c41513f..48daf9f 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSession.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSession.java @@ -25,7 +25,6 @@ package org.onap.policy.gui.editors.apex.rest.handling; import java.util.Map; import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.apex.model.modelapi.ApexApiResult.Result; import org.onap.policy.apex.model.modelapi.ApexModel; @@ -34,7 +33,6 @@ import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.coder.StandardYamlCoder; import org.onap.policy.common.utils.resources.ResourceUtils; -import org.onap.policy.gui.editors.apex.rest.handling.plugin.upload.PolicyUploadHandler; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; @@ -198,29 +196,6 @@ public class RestSession { } /** - * Upload the apex model as a TOSCA service template YAML string to the configured URL. - * - * @param userId the userId to use for upload. If blank, the commandline - * parameter "upload-userid" is used. - * @return a result indicating if the upload was successful or not - */ - public ApexApiResult uploadModel(final String userId) { - // Get the model in TOSCA format - ApexApiResult result = downloadModel(); - if (result.isNok()) { - return result; - } - - ApexModel apexModelBeingUploaded = (apexModelEdited == null ? apexModel : apexModelEdited); - - AxArtifactKey policyModelKey = apexModelBeingUploaded.getPolicyModel().getKey(); - - var policyModelUUid = apexModelBeingUploaded.getPolicyModel().getKeyInformation().get(policyModelKey) - .getUuid().toString(); - return new PolicyUploadHandler().doUpload(result.getMessage(), policyModelKey, policyModelUUid, userId); - } - - /** * Finish a session by committing or discarding the changes. * * @param commitFlag if true, commit changes otherwise discard them @@ -259,4 +234,13 @@ public class RestSession { public ApexModel getApexModelEdited() { return apexModelEdited; } + + /** + * Get the edited or unedited Apex model of the session. + * + * @return the apexModel + */ + public ApexModel getApexModelToDownload() { + return apexModelEdited == null ? apexModel : apexModelEdited; + } } diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSessionHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSessionHandler.java index 2afd5bd..43c0a95 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSessionHandler.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSessionHandler.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,10 +28,12 @@ import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.apex.model.modelapi.ApexApiResult.Result; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +import org.springframework.stereotype.Service; /** * This class carries out session handling for Apex REST editor sessions. */ +@Service public class RestSessionHandler { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(RestSessionHandler.class); diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestUtils.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestUtils.java index 42ba08e..53b91f5 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestUtils.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestUtils.java @@ -173,12 +173,12 @@ public abstract class RestUtils { } /** - * Gets the JSO nfrom concept. + * Gets the JSON from concept. * * @param object the object - * @return the JSO nfrom concept + * @return the JSON from concept */ - public static String getJsonfromConcept(final Object object) { + public static String getJsonFromConcept(final Object object) { final var gb = new GsonBuilder(); gb.serializeNulls().enableComplexMapKeySerialization(); return gb.create().toJson(object); diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/TaskHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/TaskHandler.java index 848a117..581fdd7 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/TaskHandler.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/TaskHandler.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -34,10 +34,12 @@ import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanTask; import org.onap.policy.gui.editors.apex.rest.handling.bean.BeanTaskParameter; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +import org.springframework.stereotype.Service; /** * This class handles commands on tasks in Apex models. */ +@Service public class TaskHandler implements RestCommandHandler { // Get a reference to the logger private static final XLogger LOGGER = XLoggerFactory.getXLogger(TaskHandler.class); diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/config/PolicyUploadPluginConfigKey.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/config/PolicyUploadPluginConfigKey.java deleted file mode 100644 index 02e23ff..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/config/PolicyUploadPluginConfigKey.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.gui.editors.apex.rest.handling.config; - -import lombok.Getter; - -/** - * Represents properties related to the upload plugin. - */ -@Getter -public enum PolicyUploadPluginConfigKey { - URL("plugin.policy.upload.url", String.class), - ENABLE("plugin.policy.upload.enable", Boolean.class); - - private final String key; - private final Class<?> type; - - PolicyUploadPluginConfigKey(final String key, final Class<?> type) { - this.key = key; - this.type = type; - } - -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadConfig.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadConfig.java new file mode 100644 index 0000000..c637172 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadConfig.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.gui.editors.apex.rest.handling.plugin.upload; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class PolicyUploadConfig { + + @Bean + public RestTemplate policyUploadRestTemplate() { + return new RestTemplate(); + } +} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandler.java index 1766831..677b3dd 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandler.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandler.java @@ -23,41 +23,59 @@ package org.onap.policy.gui.editors.apex.rest.handling.plugin.upload; import java.nio.charset.StandardCharsets; import java.util.Base64; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; import org.apache.commons.lang3.StringUtils; import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.apex.model.modelapi.ApexApiResult.Result; -import org.onap.policy.gui.editors.apex.rest.ApexEditorMain; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestTemplate; /** * Handles the Policy Model upload. */ +@Service public class PolicyUploadHandler { private static final XLogger LOGGER = XLoggerFactory.getXLogger(PolicyUploadHandler.class); + @Value("${apex-editor.upload-url:}") + private String uploadUrl; + + @Value("${apex-editor.upload-userid:}") + private String defaultUserId; + + private final RestTemplate policyUploadRestTemplate; + // Recurring string constants + private static final String MODEL_UPLOAD_OK = "Model/Upload: OK"; private static final String MODEL_UPLOAD_NOT_OK = "Model/Upload: NOT OK"; + @Autowired + public PolicyUploadHandler(RestTemplate policyUploadRestTemplate) { + this.policyUploadRestTemplate = policyUploadRestTemplate; + } + /** * Handles the policy model upload converting it to TOSCA with given template files. * * @param toscaServiceTemplate the TOSCA service template * @param policyModelKey the key of the policy model * @param policyModelUuid the UUID of the policy model - * @param uploadUserId the userId to use for upload. If blank, the commandline - * parameter "upload-userid" is used. + * @param uploadUserId the userId to use for upload. If blank, the Spring + * config parameter "apex-editor.upload-userid" is used. * @return the result of the upload process */ public ApexApiResult doUpload(final String toscaServiceTemplate, final AxArtifactKey policyModelKey, - final String policyModelUuid, String uploadUserId) { + final String policyModelUuid, String uploadUserId) { LOGGER.entry(); - final String uploadUrl = ApexEditorMain.getParameters().getUploadUrl(); if (StringUtils.isBlank(uploadUrl)) { final var apexApiResult = new ApexApiResult(Result.FAILED); apexApiResult.addMessage("Model upload is disabled, parameter upload-url is not set on server"); @@ -66,7 +84,7 @@ public class PolicyUploadHandler { } if (StringUtils.isBlank(uploadUserId)) { - uploadUserId = ApexEditorMain.getParameters().getUploadUserid(); + uploadUserId = defaultUserId; } final var uploadPolicyRequestDto = new UploadPolicyRequestDto(); @@ -77,29 +95,30 @@ public class PolicyUploadHandler { String.format("%s.%s.%s", policyModelUuid, policyModelKey.getName(), policyModelKey.getVersion())); try { - final var response = ClientBuilder.newClient().target(uploadUrl) - .request(MediaType.APPLICATION_JSON) - .post(Entity.entity(uploadPolicyRequestDto, MediaType.APPLICATION_JSON)); - - if (response.getStatus() == 201) { - final var apexApiResult = new ApexApiResult(Result.SUCCESS); - apexApiResult.addMessage( - String.format("uploading Policy '%s' to URL '%s' with userId '%s' was successful", - policyModelKey.getId(), uploadUrl, uploadUserId)); - LOGGER.exit("Model/Upload: OK"); - return apexApiResult; - } else { - final var apexApiResult = new ApexApiResult(Result.FAILED); - apexApiResult.addMessage( - String.format("uploading Policy '%s' to URL '%s' with userId '%s' failed with status %s", - policyModelKey.getId(), uploadUrl, uploadUserId, response.getStatus())); - LOGGER.exit(MODEL_UPLOAD_NOT_OK); - return apexApiResult; - } + var headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + var request = new HttpEntity<>(uploadPolicyRequestDto, headers); + policyUploadRestTemplate.postForObject(uploadUrl, request, String.class); + + final var apexApiResult = new ApexApiResult(Result.SUCCESS); + apexApiResult.addMessage( + String.format("uploading Policy '%s' to URL '%s' with userId '%s' was successful", + policyModelKey.getId(), uploadUrl, uploadUserId)); + LOGGER.exit(MODEL_UPLOAD_OK); + return apexApiResult; + + } catch (HttpStatusCodeException e) { + final var apexApiResult = new ApexApiResult(Result.FAILED); + apexApiResult.addMessage( + String.format("uploading Policy '%s' to URL '%s' with userId '%s' failed with status %d", + policyModelKey.getId(), uploadUrl, uploadUserId, e.getRawStatusCode())); + LOGGER.exit(MODEL_UPLOAD_NOT_OK); + return apexApiResult; + } catch (Exception e) { final var apexApiResult = new ApexApiResult(Result.FAILED); - apexApiResult - .addMessage(String.format("uploading Policy '%s' to URL '%s' with userId '%s' failed with error %s", + apexApiResult.addMessage( + String.format("uploading Policy '%s' to URL '%s' with userId '%s' failed with error %s", policyModelKey.getId(), uploadUrl, uploadUserId, e.getMessage())); LOGGER.exit(MODEL_UPLOAD_NOT_OK); return apexApiResult; diff --git a/gui-editors/gui-editor-apex/src/main/webapp/WEB-INF/web.xml b/gui-editors/gui-editor-apex/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index c60f575..0000000 --- a/gui-editors/gui-editor-apex/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,43 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - ============LICENSE_START======================================================= - Copyright (C) 2016-2018 Ericsson. All rights reserved. - Modifications Copyright (C) 2020 Nordix Foundation. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - SPDX-License-Identifier: Apache-2.0 - ============LICENSE_END========================================================= ---> - -<!-- This web.xml file is not required when using Servlet 3.0 container, - see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html --> -<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> - - <servlet> - <servlet-name>apex-services.rest</servlet-name> - <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> - <init-param> - <param-name>jersey.config.server.provider.packages</param-name> - <param-value>org.onap.policy.apex.client.editor.rest</param-value> - </init-param> - <load-on-startup>1</load-on-startup> - </servlet> - <servlet-mapping> - <servlet-name>apex-services.rest</servlet-name> - <url-pattern>/apexservices/*</url-pattern> - </servlet-mapping> - -</web-app> diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexAjax.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexAjax.js index 4a6dc7d..b583ffd 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexAjax.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexAjax.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -46,11 +46,11 @@ function ajax_getWithKeyInfo(requestURL, objectType, callback, keyNam) { ajax_get(keyInfoURL, function(dataKeyInfos) { ajax_get(requestURL, function(data) { var keyInfos = []; - for ( let value of dataKeyInfos.messages.message) { + for (let value of dataKeyInfos.messages) { var ki = JSON.parse(value).apexKeyInfo; keyInfos.push(ki); } - var object = JSON.parse(data.messages.message[0])[objectType]; + var object = JSON.parse(data.messages[0])[objectType]; var keyInfo = keyInfos.filter(function(ki) { return ki.key.name === object[keyName].name && ki.key.version === object[keyName].version; @@ -128,4 +128,4 @@ function ajax_delete(requestURL, callback) { }); } -export {ajax_get, ajax_delete, ajax_post, ajax_put, ajax_getOKOrFail, ajax_getWithKeyInfo};
\ No newline at end of file +export {ajax_get, ajax_delete, ajax_post, ajax_put, ajax_getOKOrFail, ajax_getWithKeyInfo}; diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumEditForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumEditForm.js index 23d138d..687d7b3 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumEditForm.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumEditForm.js @@ -31,7 +31,7 @@ function editContextAlbumForm_createContextAlbum(formParent) { var requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; var contextSchemas = new Array(); ajax_get(requestURL, function(data2) { - for (let value of data2.messages.message) { + for (let value of data2.messages) { var contextSchema = JSON.parse(value).apexContextSchema; contextSchemas.push({ "name" : contextSchema.key.name, @@ -63,7 +63,7 @@ function editContextAlbumForm_viewContextAlbum(parent, name, version) { requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; var contextSchemas = new Array(); ajax_get(requestURL, function(data2) { - for (let value of data2.messages.message) { + for (let value of data2.messages) { var contextSchema = JSON.parse(value).apexContextSchema; contextSchemas.push({ "name" : contextSchema.key.name, @@ -84,7 +84,7 @@ function editContextAlbumForm_editContextAlbum(formParent, name, version) { requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; var contextSchemas = new Array(); ajax_get(requestURL, function(data2) { - for (let value of data2.messages.message) { + for (let value of data2.messages) { var contextSchema = JSON.parse(value).apexContextSchema; contextSchemas.push({ "name" : contextSchema.key.name, diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumTab.js index 821e5f6..fe9bcbb 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumTab.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextAlbumTab.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -38,7 +38,7 @@ function contextAlbumTab_activate() { ajax_get(requestURL, function(data) { $("#contextAlbumTableBody").find("tr:gt(0)").remove(); - for (let value of data.messages.message) { + for (let value of data.messages) { var contextAlbum = JSON.parse(value).apexContextAlbum; var contextAlbumRow_tr = document.createElement("tr"); @@ -125,4 +125,4 @@ function contextAlbumTab_create() { } //Testing purposes -export { contextAlbumTab_reset, contextAlbumTab_create, contextAlbumTab_activate, contextAlbumTab_deactivate };
\ No newline at end of file +export { contextAlbumTab_reset, contextAlbumTab_create, contextAlbumTab_activate, contextAlbumTab_deactivate }; diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaTab.js index fa5ed6f..12f2e11 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaTab.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexContextSchemaTab.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ function contextSchemaTab_activate() { ajax_get(requestURL, function(data) { $("#contextSchemaTableBody").find("tr:gt(0)").remove(); - for (let value of data.messages.message) { + for (let value of data.messages) { var contextSchema = JSON.parse(value).apexContextSchema; var contextSchemaRow_tr = document.createElement("tr"); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventEditForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventEditForm.js index fef9278..cc14b63 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventEditForm.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventEditForm.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ function editEventForm_createEvent(formParent) { var requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; var contextSchemas = new Array(); ajax_get(requestURL, function(data2) { - for (let value of data2.messages.message) { + for (let value of data2.messages) { var contextSchema = JSON.parse(value).apexContextSchema; var dt = { "name" : contextSchema.key.name, @@ -72,7 +72,7 @@ function editEventForm_editEvent_inner(formParent, name, version, viewOrEdit) { requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; var contextSchemas = new Array(); ajax_get(requestURL, function(data2) { - for (let value of data2.messages.message) { + for (let value of data2.messages) { var contextSchema = JSON.parse(value).apexContextSchema; contextSchemas.push({ "name" : contextSchema.key.name, diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventTab.js index 44458c2..cc431b5 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventTab.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexEventTab.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -40,7 +40,7 @@ function eventTab_activate() { $("#eventTableBody").find("tr:gt(0)").remove(); - for (let value of data.messages.message) { + for (let value of data.messages) { var event = JSON.parse(value).apexEvent; var eventTableRow_tr = document.createElement("tr"); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexFiles.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexFiles.js index de9edf3..f24534f 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexFiles.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexFiles.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -38,7 +38,7 @@ function files_fileOpen() { localStorage.setItem("apex_model_loaded", true); requestURL = window.restRootURL + "/Model/GetKey"; ajax_get(requestURL, function(data) { - var modelKey = JSON.parse(data.messages.message[0]).apexArtifactKey; + var modelKey = JSON.parse(data.messages[0]).apexArtifactKey; pageControl_modelMode(modelKey.name, modelKey.version, fileName); }); }); @@ -65,7 +65,7 @@ function files_fileUpload() { } ajax_getOKOrFail(requestURL, function(data) { let uploadResultString = ""; - for (let value of data.messages.message) { + for (let value of data.messages) { uploadResultString += (value + "\n"); } resultForm_activate(document.getElementById("mainArea"), "Model Upload Result", uploadResultString); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexKeyInformationTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexKeyInformationTab.js index 6cfc28d..814725a 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexKeyInformationTab.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexKeyInformationTab.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -37,7 +37,7 @@ function keyInformationTab_activate() { ajax_get(requestURL, function(data) { $("#keyInformationTableBody").find("tr:gt(0)").remove(); - for (let value of data.messages.message) { + for (let value of data.messages) { var keyInfo = JSON.parse(value).apexKeyInfo; var keyInfoRow_tr = document.createElement("tr"); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexMain.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexMain.js index 3fc3cd5..da75fc9 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexMain.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexMain.js @@ -117,7 +117,7 @@ function main_getRestRootURL() { + (location.port ? ':' + location.port : '') + (location.pathname.endsWith("/editor/") ? location.pathname.substring(0, location.pathname .indexOf("editor/")) : location.pathname); - const restContext = "apexservices/editor/"; + const restContext = "policy/gui/v1/apex/editor/"; if (localStorage.getItem("apex_session")) { restRootURL = href + restContext + localStorage.getItem("apex_session"); window.restRootURL = restRootURL; @@ -125,7 +125,7 @@ function main_getRestRootURL() { ajax_get(requestURL, function(data) { $("#statusMessageTable").append("<tr><td> REST root URL set to: " + restRootURL + "</td></tr>"); if (localStorage.getItem("apex_model_loaded")) { - const modelKey = JSON.parse(data.messages.message[0]).apexArtifactKey; + const modelKey = JSON.parse(data.messages[0]).apexArtifactKey; pageControl_modelMode(modelKey.name, modelKey.version, modelFileName); if (localStorage.getItem("apex_tab_index")) { $("#mainTabs").tabs({ @@ -138,7 +138,7 @@ function main_getRestRootURL() { const createSessionURL = href + restContext + "-1/Session/Create"; ajax_get(createSessionURL, function(data) { - localStorage.setItem("apex_session", data.messages.message[0]); + localStorage.setItem("apex_session", data.messages[0]); restRootURL = href + restContext + localStorage.getItem("apex_session"); window.restRootURL = restRootURL; $("#statusMessageTable").append("<tr><td> REST root URL set to: " + restRootURL + "</td></tr>"); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexModelHandling.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexModelHandling.js index 9c04102..27ff5f4 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexModelHandling.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexModelHandling.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ function modelHandling_analyse() { var requestURL = window.restRootURL + "/Model/Analyse"; ajax_get(requestURL, function(data) { - resultForm_activate(document.getElementById("mainArea"), "Model Analysis Result", data.messages.message[0]); + resultForm_activate(document.getElementById("mainArea"), "Model Analysis Result", data.messages[0]); }); } @@ -35,8 +35,8 @@ function modelHandling_validate() { ajax_getOKOrFail(requestURL, function(data) { var validationResultString = ""; - for (var i = 1; i < data.messages.message.length; i++) { - validationResultString += (data.messages.message[i] + "\n"); + for (var i = 1; i < data.messages.length; i++) { + validationResultString += (data.messages[i] + "\n"); } resultForm_activate(document.getElementById("mainArea"), "Model Validation Result", validationResultString); }); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexNewModelForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexNewModelForm.js index d7e5ccd..ff48d8f 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexNewModelForm.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexNewModelForm.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -224,7 +224,7 @@ function newModelForm_submitPressed() { requestURL = window.restRootURL + "/Model/GetKey"; ajax_get(requestURL, function(data) { - var modelKey = JSON.parse(data.messages.message[0]).apexArtifactKey; + var modelKey = JSON.parse(data.messages[0]).apexArtifactKey; var modelFileName = modelKey.name + ".json"; pageControl_modelMode(modelKey.name, modelKey.version, modelFileName); }); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPageControl.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPageControl.js index 7b1b884..d2e1911 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPageControl.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPageControl.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -221,24 +221,23 @@ function pageControl_successStatus(data) { $('#statusString').html(data.result); $("#statusMessageTable").empty(); - if (data.ok) { + if (data.result === 'SUCCESS' || data.result === 'FINISHED') { $('#statusString').css("color", "green"); $('#ebInlineMessage-iconHolder-icon').attr("class", "ebIcon ebIcon_big ebIcon_tick"); } else { $('#statusString').css("color", "red"); $('#ebInlineMessage-iconHolder-icon').attr("class", "ebIcon ebIcon_big ebIcon_error"); - for (let value of data.messages.message) { + for (let value of data.messages) { $("#statusMessageTable").append("<tr><td>" + value + "</td></tr>"); } // A session with session ID "0" does not exist var sessionDoesNotExistStringStart = "A session with session ID "; var sessionDoesNotExistStringEnd = " does not exist"; - if (data.content.indexOf(sessionDoesNotExistStringStart) !== -1 - && data.content.indexOf(sessionDoesNotExistStringEnd) !== -1) { + if (data.messages[0].indexOf(sessionDoesNotExistStringStart) !== -1 + && data.messages[0].indexOf(sessionDoesNotExistStringEnd) !== -1) { clearLocalStorage(); location.reload(); } - throw "REST call returned an error\n" + data; } } @@ -246,7 +245,7 @@ function pageControl_status(data) { $('#statusString').html(data.result); $("#statusMessageTable").empty(); - if (data.ok) { + if (data.result === 'SUCCESS' || data.result === 'FINISHED') { $('#statusString').css("color", "green"); $('#ebInlineMessage-iconHolder-icon').attr("class", "ebIcon ebIcon_big ebIcon_tick"); } else { diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm.js index 4c53959..cf046c1 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyEditForm.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -66,7 +66,7 @@ function editPolicyForm_editPolicy_inner(formParent, policy, viewOrEdit) { var requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; var contextSchemas = new Array(); ajax_get(requestURL, function(data2) { - for (let value of data2.messages.message) { + for (let value of data2.messages) { var contextSchema = JSON.parse(value).apexContextSchema; contextSchemas.push({ "name" : contextSchema.key.name, @@ -79,7 +79,7 @@ function editPolicyForm_editPolicy_inner(formParent, policy, viewOrEdit) { requestURL = window.restRootURL + "/Task/Get?name=&version="; var tasks = new Array(); ajax_get(requestURL, function(data3) { - for (let value of data3.messages.message) { + for (let value of data3.messages) { var task = JSON.parse(value).apexTask; tasks.push({ "name" : task.key.name, @@ -92,7 +92,7 @@ function editPolicyForm_editPolicy_inner(formParent, policy, viewOrEdit) { requestURL = window.restRootURL + "/ContextAlbum/Get?name=&version="; var albums = new Array(); ajax_get(requestURL, function(data4) { - for (let value of data4.messages.message) { + for (let value of data4.messages) { var album = JSON.parse(value).apexContextAlbum; albums.push({ "name" : album.key.name, @@ -105,7 +105,7 @@ function editPolicyForm_editPolicy_inner(formParent, policy, viewOrEdit) { requestURL = window.restRootURL + "/Event/Get?name=&version="; var events = new Array(); ajax_get(requestURL, function(data5) { - for (let value of data5.messages.message) { + for (let value of data5.messages) { var event = JSON.parse(value).apexEvent; events.push({ "name" : event.key.name, diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyTab.js index 2aa96e4..902bb2a 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyTab.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexPolicyTab.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -38,7 +38,7 @@ function policyTab_activate() { ajax_get(requestURL, function(data) { $("#policyTableBody").find("tr:gt(0)").remove(); - for (let value of data.messages.message) { + for (let value of data.messages) { var policy = JSON.parse(value).apexPolicy; var policyRow_tr = document.createElement("tr"); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskEditForm.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskEditForm.js index 4932de6..ea33904 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskEditForm.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskEditForm.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -33,7 +33,7 @@ function editTaskForm_createTask(formParent) { var requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; var contextSchemas = new Array(); ajax_get(requestURL, function(data2) { - for (let value of data2.messages.message) { + for (let value of data2.messages) { var contextSchema = JSON.parse(value).apexContextSchema; var dt = { "name" : contextSchema.key.name, @@ -47,7 +47,7 @@ function editTaskForm_createTask(formParent) { requestURL = window.restRootURL + "/ContextAlbum/Get?name=&version="; var contextAlbums = new Array(); ajax_get(requestURL, function(data3) { - for (let value of data3.messages.message) { + for (let value of data3.messages) { var contextAlbum = JSON.parse(value).apexContextAlbum; var ca = { "name" : contextAlbum.key.name, @@ -89,7 +89,7 @@ function editTaskForm_editTask_inner(formParent, name, version, viewOrEdit) { requestURL = window.restRootURL + "/ContextSchema/Get?name=&version="; var contextSchemas = new Array(); ajax_get(requestURL, function(data2) { - for (let value of data2.messages.message) { + for (let value of data2.messages) { var contextSchema = JSON.parse(value).apexContextSchema; contextSchemas.push({ "name" : contextSchema.key.name, @@ -102,7 +102,7 @@ function editTaskForm_editTask_inner(formParent, name, version, viewOrEdit) { requestURL = window.restRootURL + "/ContextAlbum/Get?name=&version="; var contextAlbums = new Array(); ajax_get(requestURL, function(data3) { - for (let value of data3.messages.message) { + for (let value of data3.messages) { var contextAlbum = JSON.parse(value).apexContextAlbum; var ca = { "name" : contextAlbum.key.name, diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskTab.js b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskTab.js index 9c79ad4..afd0cad 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskTab.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/ApexTaskTab.js @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2022 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -38,7 +38,7 @@ function taskTab_activate() { ajax_get(requestURL, function(data) { $("#taskTableBody").find("tr:gt(0)").remove(); - for (let value of data.messages.message) { + for (let value of data.messages) { const task = JSON.parse(value).apexTask; const taskRow_tr = document.createElement("tr"); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexAjax.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexAjax.test.js index dadbaa0..362a1f9 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexAjax.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexAjax.test.js @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2020-2021 Nordix Foundation + * Copyright (C) 2020-2022 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,12 +29,9 @@ beforeEach(() => { port: 'port', username: 'username', password: 'password', - messages: { - message: '' - }, + messages: [''], content: ['01', '02'], - result: 'ok', - ok: true + result: 'SUCCESS' }; }); @@ -72,12 +69,10 @@ test('Test ajax_getWithKeyInfo success', (done) => { }); done(); }); - data.messages = { - message: [ - '{"apexKeyInfo": {"UUID": "UUID1", "description": "description1", "key":{"name": "name1", "version":' + - ' "version1"}}, "objectType": {"key": {"name": "name1", "version": "version1"}}}' - ] - }; + data.messages = [ + '{"apexKeyInfo": {"UUID": "UUID1", "description": "description1", "key":{"name": "name1", "version":' + + ' "version1"}}, "objectType": {"key": {"name": "name1", "version": "version1"}}}' + ]; const jqXHR = {status: 200, responseText: ""}; $.ajax = jest.fn().mockImplementation((args) => { @@ -98,12 +93,10 @@ test('Test ajax_getWithKeyInfo with custom key success', (done) => { }); done(); }); - data.messages = { - message: [ - '{"apexKeyInfo": {"UUID": "UUID1", "description": "description1", "key":{"name": "name1",' + - ' "version": "version1"}}, "objectType": {"customKey": {"name": "name1", "version": "version1"}}}' - ] - }; + data.messages = [ + '{"apexKeyInfo": {"UUID": "UUID1", "description": "description1", "key":{"name": "name1",' + + ' "version": "version1"}}, "objectType": {"customKey": {"name": "name1", "version": "version1"}}}' + ]; const jqXHR = {status: 200, responseText: ""}; $.ajax = jest.fn().mockImplementation((args) => { diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumEditForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumEditForm.test.js index 8d2976d..e5268fe 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumEditForm.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextAlbumEditForm.test.js @@ -24,14 +24,12 @@ const keyInformationTab_reset = require('../ApexKeyInformationTab'); const formUtils_generateDescription = require('../ApexFormUtils'); let data = { - messages: { - message: [ - '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + - '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"},"itemSchema":{}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + - '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' - ] - }, - ok: true + messages: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"},"itemSchema":{}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ], + result: 'SUCCESS' }; test('Test mock_editContextAlbumForm_activate', () => { @@ -167,4 +165,4 @@ test('Test Submit Pressed with page', () => { const mock_activate = jest.fn(mod.editContextAlbumForm_submitPressed); mock_activate(); expect(mock_activate).toBeCalled(); -});
\ No newline at end of file +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaEditForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaEditForm.test.js index 87b4f82..70f5fde 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaEditForm.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaEditForm.test.js @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2020-2021 Nordix Foundation. + * Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,8 @@ const apexAjax = require('../ApexAjax'); const formUtils_generateDescription = require('../ApexFormUtils'); let data = { - messages: { - message: [] - }, - ok: true + messages: [], + result: 'SUCCESS' }; const contextSchema = { name: 'testName', @@ -107,4 +105,4 @@ test('Test Submit Pressed', () => { const mock_activate = jest.fn(mod.editContextSchemaForm_submitPressed); mock_activate(); expect(mock_activate).toBeCalled(); -});
\ No newline at end of file +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaTab.test.js index 3883bd5..9c7ca8c 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaTab.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexContextSchemaTab.test.js @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2020-2021 Nordix Foundation. + * Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,14 +21,12 @@ const mod = require('../ApexContextSchemaTab'); let data = { - messages: { - message: [ - '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + - '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + - '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' - ] - }, - ok: true + messages: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ], + result: 'SUCCESS' }; test('Test activateContextSchema', () => { @@ -51,4 +49,4 @@ test('Test reset', () => { const mock_deactivate = jest.fn(mod.contextSchemaTab_reset); mock_deactivate(); expect(mock_deactivate).toBeCalledWith(); -});
\ No newline at end of file +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventEditForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventEditForm.test.js index 48573e8..c1ac98b 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventEditForm.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventEditForm.test.js @@ -25,14 +25,12 @@ const formUtils_generateDescription = require('../ApexFormUtils'); const keyInformationTab_reset = require('../ApexKeyInformationTab'); let data = { - messages: { - message: [ - '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + - '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + - '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' - ] - }, - ok: true + messages: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ], + result: 'SUCCESS' }; const contextSchema = { diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventTab.test.js index 16042af..50d1101 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventTab.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexEventTab.test.js @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2020-2021 Nordix Foundation. + * Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,17 +34,14 @@ test('Test activate', () => { port: 'port', username: 'username', password: 'password', - messages: { - message: [ - '{"apexEvent" : {"key": {"name": "name1", "version":"version1"}, "nameSpace":"nameSpace1",' + - ' "source":"source1", "target":"target1", "parameter": ' + - '{"entry": [{"key": "key1", "value": {"optional":"optional", "fieldSchemaKey": ' + - '{"name": "name2", "version":"version2"}}}]}}}' - ] - }, + messages: [ + '{"apexEvent" : {"key": {"name": "name1", "version":"version1"}, "nameSpace":"nameSpace1",' + + ' "source":"source1", "target":"target1", "parameter": ' + + '{"entry": [{"key": "key1", "value": {"optional":"optional", "fieldSchemaKey": ' + + '{"name": "name2", "version":"version2"}}}]}}}' + ], content: ['01', '02'], - result: 'ok', - ok: true + result: 'SUCCESS' }; $.ajax = jest.fn().mockImplementation((args) => { diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFiles.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFiles.test.js index f5be3cc..9e2307a 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFiles.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexFiles.test.js @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2020-2021 Nordix Foundation + * Copyright (C) 2020-2022 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,14 +22,12 @@ const mod = require('../ApexFiles'); const resultForm_activate = require('../ApexResultForm'); let data = { - messages: { - message: [ - '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + - '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"},"itemSchema":{}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + - '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' - ] - }, - ok: true + messages: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"},"itemSchema":{}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ], + result: 'SUCCESS' }; test('test files_open', () => { @@ -54,4 +52,4 @@ test('Test files_upload', () => { const upload = jest.fn(mod.files_fileUpload); upload(); expect(upload).toBeCalled(); -});
\ No newline at end of file +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexKeyInformationTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexKeyInformationTab.test.js index 2dcc7c2..fb49214 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexKeyInformationTab.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexKeyInformationTab.test.js @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021-2022 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,15 +28,12 @@ test("Test keyInformationTab_activate", () => { port: 'port', username: 'username', password: 'password', - messages: { - message: [ - '{"apexKeyInfo": {"UUID": "UUID1", "description": "description1", "key":{"name": "name1", "version":' + - ' "version1"}}, "objectType": {"key": {"name": "name1", "version": "version1"}}}' - ] - }, + messages: [ + '{"apexKeyInfo": {"UUID": "UUID1", "description": "description1", "key":{"name": "name1", "version":' + + ' "version1"}}, "objectType": {"key": {"name": "name1", "version": "version1"}}}' + ], content: ['01', '02'], - result: 'ok', - ok: true + result: 'SUCCESS' }; $.ajax = jest.fn().mockImplementation((args) => { args.success(data, null, null); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexMain.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexMain.test.js index 13fd658..c825370 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexMain.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexMain.test.js @@ -30,21 +30,18 @@ const keyInformationTab = require('../ApexKeyInformationTab'); require('../../dist/js/jquery-ui-1.12.1/jquery-ui.js'); const data = { - messages: { - message: [ - '{' + - ' "apexArtifactKey": {' + - ' "key": {' + - ' "name": "name1",' + - ' "version": "version1"' + - ' }' + - ' }' + - '}' - ] - }, + messages: [ + '{' + + ' "apexArtifactKey": {' + + ' "key": {' + + ' "name": "name1",' + + ' "version": "version1"' + + ' }' + + ' }' + + '}' + ], content: ['01', '02'], - result: 'ok', - ok: true + result: 'SUCCESS' }; const jqXHR = { status: 200, responseText: "" }; @@ -85,7 +82,7 @@ test('Test main_getRestRootURL false', () => { const mock_main_getRestRootURL = jest.fn(mod.main_getRestRootURL); mock_main_getRestRootURL(); expect(mock_main_getRestRootURL).toBeCalled(); - expect(document.documentElement.innerHTML).toEqual('<head></head><body><div class="ebInlineMessage-description" id="statusMessageTable"><tr><td> REST root URL set to: http://localhost/apexservices/editor/false</td></tr></div></body>'); + expect(document.documentElement.innerHTML).toEqual('<head></head><body><div class="ebInlineMessage-description" id="statusMessageTable"><tr><td> REST root URL set to: http://localhost/policy/gui/v1/apex/editor/false</td></tr></div></body>'); }); test('Test clearLocalStorage', () => { diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexModelHandling.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexModelHandling.test.js index 2144506..8b2055f 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexModelHandling.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexModelHandling.test.js @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2020-2021 Nordix Foundation. + * Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,14 +32,11 @@ test('Test modelHandling_analyse', (done) => { port: 'port', username: 'username', password: 'password', - messages: { - message: [ - '{"apexKeyInfo": null}' - ] - }, + messages: [ + '{"apexKeyInfo": null}' + ], content: ['01'], - result: 'ok', - ok: true + result: 'SUCCESS' }; const expectedMessage = '{"apexKeyInfo": null}'; document.body.innerHTML = '<div id="mainArea"></div>'; @@ -65,16 +62,13 @@ test('Test modelHandling_validate', (done) => { port: 'port', username: 'username', password: 'password', - messages: { - message: [ - '{"apexKeyInfo": null}', - '{"apexPolicy": null}', - '{"apexEvent": null}' - ] - }, + messages: [ + '{"apexKeyInfo": null}', + '{"apexPolicy": null}', + '{"apexEvent": null}' + ], content: ['01'], - result: 'ok', - ok: true + result: 'SUCCESS' }; const expectedMessage = '{"apexPolicy": null}\n{"apexEvent": null}\n'; diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPageControl.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPageControl.test.js index b414bb1..f9e2a65 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPageControl.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPageControl.test.js @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. + * Copyright (C) 2021-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,10 +40,8 @@ test('Test showPlaceholder hide', () => { test('Test pageControl_status', () => { let data = { - messages: { - message: [] - }, - ok: true + messages: [], + result: 'SUCCESS' }; const mock_activate = jest.fn(mod.pageControl_status); mock_activate(data); @@ -52,9 +50,7 @@ test('Test pageControl_status', () => { test('Test pageControl_status when data is not present', () => { let data = { - messages: { - message: [] - } + messages: [] }; const mock_activate = jest.fn(mod.pageControl_status); mock_activate(data); @@ -113,4 +109,4 @@ test('Test pageControl_readyMode', () => { const mock_activate = jest.fn(mod.pageControl_readyMode); mock_activate(); expect(mock_activate).toBeCalled(); -});
\ No newline at end of file +}); diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm.test.js index 24af346..fc92934 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyEditForm.test.js @@ -30,14 +30,12 @@ const policy = { uuid: 'testUUID' } let data = { - messages: { - message: [ - '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + - '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + - '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' - ] - }, - ok: true + messages: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ], + result: 'SUCCESS' }; test('Test Create Policy', () => { diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyTab.test.js index 4136fd6..58714c6 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyTab.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexPolicyTab.test.js @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2020-2021 Nordix Foundation + * Copyright (C) 2020-2022 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,157 +33,154 @@ test('Test policyTab_activate', () => { port: 'port', username: 'username', password: 'password', - messages: { - message: [ - '{' + - ' "apexPolicy": {' + - ' "policyKey": {' + - ' "name": "name1",' + - ' "version": "version1"' + - ' },' + - ' "template": "template1",' + - ' "firstState": "key11",' + - ' "state": {' + - ' "entry": [' + - ' {' + - ' "key": "key1",' + - ' "value": {' + - ' "trigger": {' + - ' "name": "name2",' + - ' "version": "version2"' + - ' },' + - ' "taskReferences": {' + - ' "entry": [' + - ' {' + - ' "key": {' + - ' "name": "name3",' + - ' "version": "version3"' + - ' },' + - ' "version": "version2",' + - ' "value": {' + - ' "outputType": "outputType1",' + - ' "output": {' + - ' "localName": "localName1"' + - ' }' + - ' }' + - ' }' + - ' ]' + - ' },' + - ' "defaultTask": {' + - ' "name": "name4",' + - ' "version": "version4"' + - ' },' + - ' "taskSelectionLogic": {' + - ' "logicFlavour": "logicFlavour1"' + - ' },' + - ' "stateOutputs": {' + - ' "entry": [' + - ' {' + - ' "key": "key2",' + - ' "value": {' + - ' "nextState": {' + - ' "localName": "localName2"' + - ' },' + - ' "outgoingEvent": {' + - ' "name": "name4",' + - ' "version": "version4"' + - ' }' + - ' }' + - ' }' + - ' ]' + - ' },' + - ' "stateFinalizerLogicMap": {' + - ' "entry": [' + - ' {' + - ' "key": "key3",' + - ' "value": {' + - ' "logicFlavour": "logicFlavour2"' + - ' }' + - ' }' + - ' ]' + - ' },' + - ' "contextAlbumReference": [' + - ' {' + - ' "name": "name5",' + - ' "version": "version5"' + - ' }' + - ' ]' + - ' }' + - ' },' + - ' {' + - ' "key": "key11",' + - ' "value": {' + - ' "trigger": {' + - ' "name": "name12",' + - ' "version": "version12"' + - ' },' + - ' "taskReferences": {' + - ' "entry": [' + - ' {' + - ' "key": {' + - ' "name": "name13",' + - ' "version": "version13"' + - ' },' + - ' "version": "version12",' + - ' "value": {' + - ' "outputType": "outputType11",' + - ' "output": {' + - ' "localName": "localName11"' + - ' }' + - ' }' + - ' }' + - ' ]' + - ' },' + - ' "defaultTask": {' + - ' "name": "name14",' + - ' "version": "version14"' + - ' },' + - ' "taskSelectionLogic": {' + - ' "logicFlavour": "logicFlavour11"' + - ' },' + - ' "stateOutputs": {' + - ' "entry": [' + - ' {' + - ' "key": "key12",' + - ' "value": {' + - ' "nextState": {' + - ' "localName": "localName12"' + - ' },' + - ' "outgoingEvent": {' + - ' "name": "name14",' + - ' "version": "version14"' + - ' }' + - ' }' + - ' }' + - ' ]' + - ' },' + - ' "stateFinalizerLogicMap": {' + - ' "entry": [' + - ' {' + - ' "key": "key13",' + - ' "value": {' + - ' "logicFlavour": "logicFlavour12"' + - ' }' + - ' }' + - ' ]' + - ' },' + - ' "contextAlbumReference": [' + - ' {' + - ' "name": "name15",' + - ' "version": "version15"' + - ' }' + - ' ]' + - ' }' + - ' }' + - ' ]' + - ' }' + - ' }' + - '}' - ] - }, + messages: [ + '{' + + ' "apexPolicy": {' + + ' "policyKey": {' + + ' "name": "name1",' + + ' "version": "version1"' + + ' },' + + ' "template": "template1",' + + ' "firstState": "key11",' + + ' "state": {' + + ' "entry": [' + + ' {' + + ' "key": "key1",' + + ' "value": {' + + ' "trigger": {' + + ' "name": "name2",' + + ' "version": "version2"' + + ' },' + + ' "taskReferences": {' + + ' "entry": [' + + ' {' + + ' "key": {' + + ' "name": "name3",' + + ' "version": "version3"' + + ' },' + + ' "version": "version2",' + + ' "value": {' + + ' "outputType": "outputType1",' + + ' "output": {' + + ' "localName": "localName1"' + + ' }' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "defaultTask": {' + + ' "name": "name4",' + + ' "version": "version4"' + + ' },' + + ' "taskSelectionLogic": {' + + ' "logicFlavour": "logicFlavour1"' + + ' },' + + ' "stateOutputs": {' + + ' "entry": [' + + ' {' + + ' "key": "key2",' + + ' "value": {' + + ' "nextState": {' + + ' "localName": "localName2"' + + ' },' + + ' "outgoingEvent": {' + + ' "name": "name4",' + + ' "version": "version4"' + + ' }' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "stateFinalizerLogicMap": {' + + ' "entry": [' + + ' {' + + ' "key": "key3",' + + ' "value": {' + + ' "logicFlavour": "logicFlavour2"' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "contextAlbumReference": [' + + ' {' + + ' "name": "name5",' + + ' "version": "version5"' + + ' }' + + ' ]' + + ' }' + + ' },' + + ' {' + + ' "key": "key11",' + + ' "value": {' + + ' "trigger": {' + + ' "name": "name12",' + + ' "version": "version12"' + + ' },' + + ' "taskReferences": {' + + ' "entry": [' + + ' {' + + ' "key": {' + + ' "name": "name13",' + + ' "version": "version13"' + + ' },' + + ' "version": "version12",' + + ' "value": {' + + ' "outputType": "outputType11",' + + ' "output": {' + + ' "localName": "localName11"' + + ' }' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "defaultTask": {' + + ' "name": "name14",' + + ' "version": "version14"' + + ' },' + + ' "taskSelectionLogic": {' + + ' "logicFlavour": "logicFlavour11"' + + ' },' + + ' "stateOutputs": {' + + ' "entry": [' + + ' {' + + ' "key": "key12",' + + ' "value": {' + + ' "nextState": {' + + ' "localName": "localName12"' + + ' },' + + ' "outgoingEvent": {' + + ' "name": "name14",' + + ' "version": "version14"' + + ' }' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "stateFinalizerLogicMap": {' + + ' "entry": [' + + ' {' + + ' "key": "key13",' + + ' "value": {' + + ' "logicFlavour": "logicFlavour12"' + + ' }' + + ' }' + + ' ]' + + ' },' + + ' "contextAlbumReference": [' + + ' {' + + ' "name": "name15",' + + ' "version": "version15"' + + ' }' + + ' ]' + + ' }' + + ' }' + + ' ]' + + ' }' + + ' }' + + '}' + ], content: ['01', '02'], - result: 'ok', - ok: true + result: 'SUCCESS' }; $.ajax = jest.fn().mockImplementation((args) => { diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskEditForm.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskEditForm.test.js index e9fcc9b..5e2d2ae 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskEditForm.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskEditForm.test.js @@ -41,14 +41,12 @@ const task = { }; let data = { - messages: { - message: [ - '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + - '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + - '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' - ] - }, - ok: true + messages: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"}},' + + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ], + result: 'SUCCESS' }; let contextAlbumReference = { diff --git a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskTab.test.js b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskTab.test.js index f593bd8..bf5faee 100644 --- a/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskTab.test.js +++ b/gui-editors/gui-editor-apex/src/main/webapp/js/__test__/ApexTaskTab.test.js @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2020-2021 Nordix Foundation. + * Copyright (C) 2020-2022 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,18 +21,16 @@ const mod = require('../ApexTaskTab'); let data = { - messages: { - message: [ - '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"},' + - '"taskLogic":{"logicFlavour":"logicFlavour"},"inputFields":{"entry": [{"key":"","value":{"fieldSchemaKey":{"name":"name"}}}]},' + - '"outputFields":{"entry": [{"key":"","value":{"fieldSchemaKey":{"name":"name"}}}]},' + - '"taskParameters":{"entry": [{"key":"","value":{"fieldSchemaKey":{"name":"name"}}}]},'+ - '"contextAlbumReference":[{"name":"name", "version":"version"}]},'+ - '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + - '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' - ] - }, - ok: true + messages: [ + '{"apexContextSchema": {"key":{"name": "name1", "version": "version1"}}, "apexTask":{"key":{"name": "name1", "version": "version1"},' + + '"taskLogic":{"logicFlavour":"logicFlavour"},"inputFields":{"entry": [{"key":"","value":{"fieldSchemaKey":{"name":"name"}}}]},' + + '"outputFields":{"entry": [{"key":"","value":{"fieldSchemaKey":{"name":"name"}}}]},' + + '"taskParameters":{"entry": [{"key":"","value":{"fieldSchemaKey":{"name":"name"}}}]},'+ + '"contextAlbumReference":[{"name":"name", "version":"version"}]},'+ + '"apexContextAlbum":{"key":{"name": "name1", "version": "version1"}},"apexEvent":{"key":{"name": "name1", "version": "version1"}},' + + '"apexPolicy":{"policyKey":{"name": "name1", "version": "version1"}}, "apexKeyInfo":{"key":{"name": "name1", "version": "version1"}}}' + ], + result: 'SUCCESS' }; test('test dom : taskTab_activate', () => { @@ -49,4 +47,4 @@ test('test reset', () => { const reset_mock = jest.fn(mod.taskTab_reset); reset_mock(); expect(reset_mock).toBeCalled(); -});
\ No newline at end of file +}); |