diff options
author | 2022-01-28 11:41:38 +0000 | |
---|---|---|
committer | 2022-02-23 09:50:14 +0000 | |
commit | 4a50604b767176aa323acae366fa762015a7f9f6 (patch) | |
tree | 065f6be626573df3da5df23b3b2d2533cb9ed819 /gui-editors/gui-editor-apex/src/main/java/org | |
parent | 6e3d850c1b6efda12a70a111c8734972c99e3db5 (diff) |
Apex Editor using Spring Boot
Changed Apex Editor to use Spring Boot (MVC)
Changed all tests to use JUnit 5
Added more tests for policy upload feature
Updated JS files to reflect JSON encoding change
Added Apex Editor README
Changed rest path to /policy/gui/v1/apex/editor
Issue-ID: POLICY-3896
Signed-off-by: danielhanrahan <daniel.hanrahan@est.tech>
Change-Id: I10f1ee3c40244a822a7032b4b24cb02060698fc3
Diffstat (limited to 'gui-editors/gui-editor-apex/src/main/java/org')
21 files changed, 497 insertions, 1191 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; |