diff options
author | 2020-09-11 14:28:32 +0100 | |
---|---|---|
committer | 2020-09-11 14:37:24 +0100 | |
commit | 9a9127b65920580de8b4a69479a9983481c8faf8 (patch) | |
tree | 35c6449e4850b661f86a639a33684e079beb836d /gui-editors/gui-editor-apex/src/main/java/org/onap | |
parent | afcf92da0d813028b48ea781df33148bc6f000b6 (diff) |
Add TOSCA support to Apex editor
The APEX editor now loads, saves, and downloads files in TOSCA format,
the same as the apex-pdp does.
The non-standard TOSCA handling for file upload has been refactored to
be aligned with the Policy Frameowkr TOSCA support.
Issue-ID: POLICY-2621
Change-Id: I1ec7475cbcc6ffc23de92687c9f284ac7dfbdd80
Signed-off-by: liamfallon <liam.fallon@est.tech>
Diffstat (limited to 'gui-editors/gui-editor-apex/src/main/java/org/onap')
17 files changed, 461 insertions, 1219 deletions
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 index 9d88a2d..d8a4030 100644 --- 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 @@ -22,13 +22,11 @@ package org.onap.policy.gui.editors.apex.rest; import java.io.PrintStream; -import org.onap.policy.common.parameters.ParameterService; 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. + * This class is the main class that is used to launch the Apex editor from the command line. * */ public class ApexEditorMain { @@ -61,7 +59,7 @@ public class ApexEditorMain { private ApexEditor apexEditor = null; // The parameters for the editor - private ApexEditorParameters parameters = null; + private static ApexEditorParameters parameters = null; // Output and error streams for messages private final PrintStream outStream; @@ -86,7 +84,7 @@ public class ApexEditorMain { throw new ApexEditorParameterException(REST_ENDPOINT_PREFIX + this.toString() + ") parameter error, " + e.getMessage() + '\n' + parser.getHelp(ApexEditorMain.class.getName()), e); } - if (parameters.isHelpSet()) { + if (parameters.isHelp()) { throw new ApexEditorParameterException(parser.getHelp(ApexEditorMain.class.getName())); } @@ -97,8 +95,6 @@ public class ApexEditorMain { + validationMessage + '\n' + parser.getHelp(ApexEditorMain.class.getName())); } - ParameterService.register(new UploadPluginConfigParameters()); - state = EditorState.READY; } @@ -184,6 +180,15 @@ public class ApexEditorMain { } /** + * Get the editor parameters. + * + * @return the parameters + */ + public static ApexEditorParameters getParameters() { + return parameters; + } + + /** * This class is a shutdown hook for the Apex editor command. */ private class ApexEditorShutdownHook implements Runnable { @@ -212,4 +217,3 @@ public class ApexEditorMain { } } } - 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 index 0033bcb..4337efc 100644 --- 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 @@ -46,19 +46,67 @@ public class ApexEditorParameterParser { * 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("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("USERID") + .required(false) + .type(String.class) + .build() + ); + // @formatter:on } /** @@ -107,6 +155,20 @@ public class ApexEditorParameterParser { } 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; } 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 index c4c36ff..e89e69f 100644 --- 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 @@ -21,8 +21,12 @@ 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 org.apache.commons.lang3.StringUtils; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -31,6 +35,7 @@ import org.slf4j.ext.XLoggerFactory; * * @author Liam Fallon (liam.fallon@ericsson.com) */ +@Data public class ApexEditorParameters { // Logger for this class private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEditorParameters.class); @@ -56,10 +61,12 @@ public class ApexEditorParameters { private static final String[] DEFAULT_PACKAGES = new String[] { "org.onap.policy.gui.editors.apex.rest" }; // The editor parameters - private boolean helpSet = false; + 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. @@ -71,6 +78,8 @@ public class ApexEditorParameters { validationMessage += validatePort(); validationMessage += validateTimeToLive(); validationMessage += validateUrl(); + validationMessage += validateUploadUrl(); + validationMessage += validateUploadUserid(); return validationMessage; } @@ -144,86 +153,22 @@ public class ApexEditorParameters { } } - /** - * Checks if is help set. - * - * @return true, if checks if is help set - */ - public boolean isHelpSet() { - return helpSet; - } - - /** - * Sets the help. - * - * @param help the help - */ - public void setHelp(final boolean help) { - this.helpSet = help; - } - - /** - * Gets the REST port. - * - * @return the REST port - */ - public int getRestPort() { - return restPort; - } - - /** - * Sets the REST port. - * - * @param incomingRestPort the REST port - */ - public void setRestPort(final int incomingRestPort) { - this.restPort = incomingRestPort; - } - - /** - * Gets the time to live. - * - * @return the time to live - */ - public long getTimeToLive() { - return timeToLive; - } - - /** - * Sets the time to live. - * - * @param timeToLive the time to live - */ - public void setTimeToLive(final long timeToLive) { - this.timeToLive = timeToLive; - } - - /** - * {@inheritDoc}. - */ - @Override - public String toString() { - final StringBuilder ret = new StringBuilder(); - ret.append(this.getClass().getSimpleName()).append(": URI=").append(this.getBaseUri()).append(", TTL=") - .append(this.getTimeToLive()).append("sec"); - return ret.toString(); - } - - /** - * Gets the base address to listen on. - * - * @return the listenAddress - */ - public String getListenAddress() { - return listenAddress; + 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 ""; } - /** - * Sets the base address to listen on. - * - * @param listenAddress the new listenAddress - */ - public void setListenAddress(final String listenAddress) { - this.listenAddress = listenAddress; + 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/UploadPluginConfigParameters.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParameters.java deleted file mode 100644 index e056339..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParameters.java +++ /dev/null @@ -1,82 +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; - -import java.util.Optional; -import lombok.Getter; -import lombok.Setter; -import org.apache.commons.lang3.StringUtils; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ParameterGroup; -import org.onap.policy.common.parameters.ValidationStatus; -import org.onap.policy.gui.editors.apex.rest.handling.config.PolicyUploadPluginConfigKey; - -@Getter -public class UploadPluginConfigParameters implements ParameterGroup { - - public static final String GROUP_NAME = "UploadParameters"; - - @Setter - private String name; - private boolean isEnabled; - private String url; - - public UploadPluginConfigParameters() { - this.name = GROUP_NAME; - initProperties(); - } - - private void initProperties() { - final String isEnabledProperty = System.getProperty(PolicyUploadPluginConfigKey.ENABLE.getKey()); - isEnabled = Boolean.parseBoolean(isEnabledProperty); - url = System.getProperty(PolicyUploadPluginConfigKey.URL.getKey()); - } - - @Override - public GroupValidationResult validate() { - final GroupValidationResult result = new GroupValidationResult(this); - if (isEnabled && StringUtils.isEmpty(url)) { - result.setResult("url", ValidationStatus.INVALID, - String.format("The URL for the upload endpoint must be provided as the java property '%s'", - PolicyUploadPluginConfigKey.URL.getKey())); - } - - return result; - } - - /** - * Gets a property value based on the key and type. - * - * @param <T> represents the class type - * @param key the property key - * @return the property value if it exists - */ - public <T> Optional<T> getValue(final PolicyUploadPluginConfigKey key) { - final Class<?> type = key.getType(); - if (key == PolicyUploadPluginConfigKey.URL && type.isInstance(url)) { - return (Optional<T>) Optional.of(type.cast(url)); - } - if (key == PolicyUploadPluginConfigKey.ENABLE && type.isInstance(isEnabled)) { - return (Optional<T>) Optional.of(type.cast(isEnabled)); - } - return Optional.empty(); - } - -} 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 3083c4a..ba3d5e7 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 @@ -22,7 +22,6 @@ package org.onap.policy.gui.editors.apex.rest.handling; import java.io.IOException; -import java.io.InputStream; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -33,18 +32,9 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; -import org.glassfish.jersey.media.multipart.FormDataParam; import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.apex.model.modelapi.ApexApiResult.Result; -import org.onap.policy.common.parameters.ParameterService; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.onap.policy.common.utils.coder.YamlJsonTranslator; import org.onap.policy.common.utils.resources.TextFileUtils; -import org.onap.policy.gui.editors.apex.rest.UploadPluginConfigParameters; -import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ApexConfigProcessor; -import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter; -import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor; -import org.onap.policy.gui.editors.apex.rest.handling.plugin.upload.UploadPluginClient; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -69,8 +59,8 @@ import org.slf4j.ext.XLoggerFactory; * */ @Path("editor/{session}") -@Produces({MediaType.APPLICATION_JSON}) -@Consumes({MediaType.APPLICATION_JSON}) +@Produces({ MediaType.APPLICATION_JSON }) +@Consumes({ MediaType.APPLICATION_JSON }) public class ApexEditorRestResource implements RestCommandHandler { // Get a reference to the logger @@ -101,7 +91,6 @@ public class ApexEditorRestResource implements RestCommandHandler { private static final TaskHandler TASK_HANDLER = new TaskHandler(); private static final PolicyHandler POLICY_HANDLER = new PolicyHandler(); - private final PolicyUploadHandler policyUploadHandler; //@formatter:on // The ID of this session. This gets injected from the URL. @@ -109,18 +98,6 @@ public class ApexEditorRestResource implements RestCommandHandler { private int sessionId = -1; /** - * Creates the ApexEditorRestResource instance. - */ - public ApexEditorRestResource() { - final StandardCoder standardCoder = new StandardCoder(); - policyUploadHandler = new PolicyUploadHandler( - new UploadPluginClient(), new PolicyToscaConverter(standardCoder, new YamlJsonTranslator()), - new ToscaTemplateProcessor(standardCoder), new ApexConfigProcessor(standardCoder), - ParameterService.get(UploadPluginConfigParameters.GROUP_NAME) - ); - } - - /** * 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. * @@ -144,7 +121,7 @@ public class ApexEditorRestResource implements RestCommandHandler { * Load the model from a JSON string for this session. * * @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. + * 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()} */ @@ -250,26 +227,14 @@ public class ApexEditorRestResource implements RestCommandHandler { } /** - * Uploads a Policy Model to a configured endpoint converting it to tosca based on the given apex config and tosca - * templates. + * Uploads a TOSCA Policy Model to a configured endpoint. * - * @param toscaTemplateFileStream the tosca template file input stream - * @param apexConfigFileStream the apex config file input stream * @return an ApexAPIResult that contains the operation status and success/error messages */ - @POST + @GET @Path("Model/Upload") - @Consumes({MediaType.MULTIPART_FORM_DATA}) - public ApexApiResult uploadModel(@FormDataParam("tosca-template-file") InputStream toscaTemplateFileStream, - @FormDataParam("apex-config-file") InputStream apexConfigFileStream, - @FormDataParam("userId") String userId) { - final ApexApiResult result = new ApexApiResult(); - final RestSession session = SESSION_HANDLER.getSession(sessionId, result); - if (session == null) { - return result; - } - return policyUploadHandler.doUpload(session.getApexModel(), toscaTemplateFileStream, - apexConfigFileStream, userId); + public ApexApiResult uploadModel() { + return processRestCommand(RestCommandType.MODEL, RestCommand.UPLOAD); } /** @@ -288,7 +253,7 @@ public class ApexEditorRestResource implements RestCommandHandler { * 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 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()} @@ -296,7 +261,7 @@ public class ApexEditorRestResource implements RestCommandHandler { @GET @Path("KeyInformation/Get") public ApexApiResult listKeyInformation(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { + @QueryParam(VERSION) final String version) { return processRestCommand(RestCommandType.KEY_INFO, RestCommand.LIST, name, version); } @@ -331,7 +296,7 @@ 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 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()} @@ -339,14 +304,14 @@ public class ApexEditorRestResource implements RestCommandHandler { @GET @Path("ContextSchema/Get") public ApexApiResult listContextSchemas(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { + @QueryParam(VERSION) final String version) { return processRestCommand(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 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()} @@ -354,7 +319,7 @@ public class ApexEditorRestResource implements RestCommandHandler { @DELETE @Path("ContextSchema/Delete") public ApexApiResult deleteContextSchema(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { + @QueryParam(VERSION) final String version) { return processRestCommand(RestCommandType.CONTEXT_SCHEMA, RestCommand.DELETE, name, version); } @@ -362,7 +327,7 @@ public class ApexEditorRestResource implements RestCommandHandler { * 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 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()} @@ -370,7 +335,7 @@ public class ApexEditorRestResource implements RestCommandHandler { @GET @Path("Validate/ContextSchema") public ApexApiResult validateContextSchemas(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { + @QueryParam(VERSION) final String version) { return processRestCommand(RestCommandType.CONTEXT_SCHEMA, RestCommand.VALIDATE, name, version); } @@ -405,7 +370,7 @@ 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 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()} @@ -413,14 +378,14 @@ public class ApexEditorRestResource implements RestCommandHandler { @GET @Path("ContextAlbum/Get") public ApexApiResult listContextAlbums(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { + @QueryParam(VERSION) final String version) { return processRestCommand(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 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()} @@ -428,7 +393,7 @@ public class ApexEditorRestResource implements RestCommandHandler { @DELETE @Path("ContextAlbum/Delete") public ApexApiResult deleteContextAlbum(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { + @QueryParam(VERSION) final String version) { return processRestCommand(RestCommandType.CONTEXT_ALBUM, RestCommand.DELETE, name, version); } @@ -436,7 +401,7 @@ public class ApexEditorRestResource implements RestCommandHandler { * 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 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()} @@ -444,7 +409,7 @@ public class ApexEditorRestResource implements RestCommandHandler { @GET @Path("Validate/ContextAlbum") public ApexApiResult validateContextAlbums(@QueryParam(NAME) final String name, - @QueryParam(VERSION) final String version) { + @QueryParam(VERSION) final String version) { return processRestCommand(RestCommandType.CONTEXT_ALBUM, RestCommand.VALIDATE, name, version); } @@ -479,7 +444,7 @@ 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 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()} @@ -493,7 +458,7 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * 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 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()} @@ -507,7 +472,7 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * 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 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()} @@ -549,7 +514,7 @@ 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 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()} @@ -563,7 +528,7 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * 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 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()} @@ -577,7 +542,7 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * 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 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()} @@ -605,14 +570,14 @@ public class ApexEditorRestResource implements RestCommandHandler { * Update a policy with the information in the JSON string passed. * * @param firstStatePeriodic indicates if periodic event should be created and added to model - * @param jsonString the JSON string to be parsed. See {@code BeanPolicy} + * @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) { + final String jsonString) { ApexApiResult result = processRestCommand(RestCommandType.POLICY, RestCommand.UPDATE, jsonString); if (result != null && result.isOk() && firstStatePeriodic) { @@ -626,7 +591,7 @@ 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 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()} @@ -640,7 +605,7 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * 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 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()} @@ -655,7 +620,7 @@ public class ApexEditorRestResource implements RestCommandHandler { * This method routes REST commands that take no parameters to their caller. * * @param commandType the type of REST command to process - * @param command the 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) { @@ -680,12 +645,12 @@ public class ApexEditorRestResource implements RestCommandHandler { * This method routes REST commands that take a JSON string to their caller. * * @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 + * @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) { + final String jsonString) { LOGGER.entry(commandType, jsonString); try { ApexApiResult result = new ApexApiResult(); @@ -707,13 +672,13 @@ public class ApexEditorRestResource implements RestCommandHandler { * This method routes REST commands that take a name and version to their caller. * * @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 + * @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) { + final String name, final String version) { LOGGER.entry(commandType, name, version); try { ApexApiResult result = new ApexApiResult(); @@ -734,14 +699,14 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * This method invokes callers to run REST commands that take no parameters. * - * @param session the Apex editor session + * @param session the Apex editor session * @param commandType the type of REST command to process - * @param command the REST command to process + * @param command the REST command to process * @return the result of the REST command */ @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); @@ -765,15 +730,15 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * This method invokes callers to run REST commands that take a JSON string. * - * @param session the Apex editor session + * @param session the Apex editor session * @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 + * @param command the REST command to process + * @param jsonString the JSON string received in the REST request * @return the result of the REST command */ @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); @@ -797,16 +762,16 @@ public class ApexEditorRestResource implements RestCommandHandler { /** * This method invokes callers to run REST commands that take a name and version. * - * @param session the Apex editor session + * @param session the Apex editor session * @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 + * @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 */ @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); @@ -836,7 +801,7 @@ public class ApexEditorRestResource implements RestCommandHandler { periodicEventJsonString = TextFileUtils.getTextFileAsString(PERIODIC_EVENT_TEMPLATE); } catch (IOException ioException) { String message = "read of periodic event tempalte from " + PERIODIC_EVENT_TEMPLATE + "failed: " - + ioException.getMessage(); + + ioException.getMessage(); LOGGER.debug(message, ioException); return new ApexApiResult(Result.FAILED, message); } diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResource.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResource.java deleted file mode 100644 index 76af06e..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResource.java +++ /dev/null @@ -1,83 +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; - -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -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.parameters.ParameterService; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.onap.policy.gui.editors.apex.rest.UploadPluginConfigParameters; -import org.onap.policy.gui.editors.apex.rest.handling.config.PolicyUploadPluginConfigKey; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Handles endpoints for the configuration properties. - */ -@Path("editor/config") -@Produces({MediaType.APPLICATION_JSON}) -@Consumes({MediaType.APPLICATION_JSON}) -public class ConfigurationRestResource { - - private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationRestResource.class); - private static final StandardCoder STANDARD_CODER = new StandardCoder(); - - private final UploadPluginConfigParameters uploadConfigParam; - - public ConfigurationRestResource() { - uploadConfigParam = ParameterService.get(UploadPluginConfigParameters.GROUP_NAME); - } - - /** - * Gets the configured properties. - * - * @return the properties as JSON in the ApexApiResult messages list. - */ - @GET - @Path("") - public ApexApiResult show() { - final ApexApiResult result = new ApexApiResult(Result.SUCCESS); - - final Map<String, Object> configMap = Stream.of(PolicyUploadPluginConfigKey.values()) - .filter(key -> uploadConfigParam.getValue(key).isPresent()) - .collect(Collectors.toMap(PolicyUploadPluginConfigKey::getKey, - configKey -> uploadConfigParam.getValue(configKey).get())); - try { - final String encode = STANDARD_CODER.encode(configMap); - result.addMessage(encode); - } catch (final CoderException e) { - result.setResult(Result.FAILED); - final String errorMsg = "Could not parse configuration parameters as JSON"; - result.addMessage(errorMsg); - LOGGER.error(errorMsg, e); - } - return result; - } - -} 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 3bedad2..9770710 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 @@ -75,6 +75,8 @@ public class ModelHandler implements RestCommandHandler { return listModel(session); case DOWNLOAD: return downloadModel(session); + case UPLOAD: + return uploadModel(session); case DELETE: return deleteModel(session); default: @@ -117,34 +119,31 @@ public class ModelHandler implements RestCommandHandler { * Load the model from a JSON string for this session. * * @param session the Apex model editing session - * @param jsonString the JSON string to be parsed. The returned value(s) will be - * similar to {@link AxPolicyModel}, with merged - * {@linkplain 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()} + * @param jsonString the JSON string to be parsed. The returned value(s) will be similar to {@link AxPolicyModel}, + * with merged {@linkplain 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()} */ private ApexApiResult loadFromString(final RestSession session, final String jsonString) { LOGGER.entry(jsonString); session.editModel(); - ApexApiResult result = session.getApexModelEdited().loadFromString(jsonString); + ApexApiResult result = session.loadFromString(jsonString); session.finishSession(result.isOk()); - LOGGER.exit("Model/Load" + (result != null && result.isOk() ? OK : NOT_OK)); + LOGGER.exit("Model/Load" + (result.isOk() ? OK : NOT_OK)); return result; } /** - * Analyse the model and return analysis results. If successful the analysis - * results will be available in the messages in the result. + * Analyse the model and return analysis results. If successful the analysis results will be available in the + * messages in the result. * * @param session the Apex model editing session - * @return an ApexAPIResult object. If successful then - * {@link ApexApiResult#isOk()} will return true. Any messages/errors - * can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ private ApexApiResult analyse(final RestSession session) { LOGGER.entry(); @@ -156,13 +155,12 @@ public class ModelHandler implements RestCommandHandler { } /** - * Validate the model and return validation results. If successful the - * validation results will be available in the messages in the result. + * Validate the model and return validation results. If successful the validation results will be available in the + * messages in the result. * * @param session the Apex model editing session - * @return an ApexAPIResult object. If successful then - * {@link ApexApiResult#isOk()} will return true. Any messages/errors - * can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ private ApexApiResult validate(final RestSession session) { LOGGER.entry(); @@ -177,11 +175,9 @@ public class ModelHandler implements RestCommandHandler { * Creates the new model model for this session. * * @param session the Apex model editing session - * @param jsonString the JSON string to be parsed containing the new model. See - * {@linkplain BeanModel} - * @return an ApexAPIResult object. If successful then - * {@link ApexApiResult#isOk()} will return true. Any messages/errors - * can be retrieved using {@link ApexApiResult#getMessages()} + * @param jsonString the JSON string to be parsed containing the new model. See {@linkplain BeanModel} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ private ApexApiResult createModel(final RestSession session, final String jsonString) { LOGGER.entry(jsonString); @@ -195,7 +191,7 @@ public class ModelHandler implements RestCommandHandler { session.finishSession(result.isOk()); - LOGGER.exit("Model/Create" + (result != null && result.isOk() ? OK : NOT_OK)); + LOGGER.exit("Model/Create" + (result.isOk() ? OK : NOT_OK)); return result; } @@ -203,11 +199,9 @@ public class ModelHandler implements RestCommandHandler { * Update the model for this session. * * @param session the Apex model editing session - * @param jsonString the JSON string to be parsed containing the updated model. - * See {@linkplain BeanModel} - * @return an ApexAPIResult object. If successful then - * {@link ApexApiResult#isOk()} will return true. Any messages/errors - * can be retrieved using {@link ApexApiResult#getMessages()} + * @param jsonString the JSON string to be parsed containing the updated model. See {@linkplain BeanModel} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ private ApexApiResult updateModel(final RestSession session, final String jsonString) { LOGGER.entry(jsonString); @@ -221,18 +215,17 @@ public class ModelHandler implements RestCommandHandler { session.finishSession(result.isOk()); - LOGGER.exit("Model/Update" + (result != null && result.isOk() ? OK : NOT_OK)); + LOGGER.exit("Model/Update" + (result.isOk() ? OK : NOT_OK)); return result; } /** - * 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 {@linkplain AxKey} + * 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 {@linkplain AxKey} * * @param session the Apex model editing session - * @return an ApexAPIResult object. If successful then - * {@link ApexApiResult#isOk()} will return true. Any messages/errors - * can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ private ApexApiResult getModelKey(final RestSession session) { LOGGER.entry(); @@ -244,15 +237,13 @@ public class ModelHandler implements RestCommandHandler { } /** - * Retrieve the model for this session. If successful the model will be - * available in the first message in the result. The returned value will be - * similar to a {@link AxPolicyModel}, with merged {@linkplain AxKeyInfo} for - * the root object. + * Retrieve the model for this session. If successful the model will be available in the first message in the + * result. The returned value will be similar to a {@link AxPolicyModel}, with merged {@linkplain AxKeyInfo} for the + * root object. * * @param session the Apex model editing session - * @return an ApexAPIResult object. If successful then - * {@link ApexApiResult#isOk()} will return true. Any messages/errors - * can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ private ApexApiResult listModel(final RestSession session) { LOGGER.entry(); @@ -261,7 +252,7 @@ public class ModelHandler implements RestCommandHandler { result = addKeyInfo2Messages(session, result); - LOGGER.exit("Model/Get" + (result != null && result.isOk() ? OK : NOT_OK)); + LOGGER.exit("Model/Get" + (result.isOk() ? OK : NOT_OK)); return result; } @@ -269,13 +260,27 @@ public class ModelHandler implements RestCommandHandler { * Download the model for this session as a String. * * @param session the Apex model editing session - * @return the model represented as a JSON string. See - * {@linkplain AxPolicyModel} + * @return the model represented as a JSON string. See {@linkplain AxPolicyModel} */ private ApexApiResult downloadModel(final RestSession session) { LOGGER.entry(); - ApexApiResult result = session.getApexModel().listModel(); + ApexApiResult result = session.downloadModel(); + + LOGGER.exit("Model/Download" + (result != null && result.isOk() ? OK : NOT_OK)); + return result; + } + + /** + * Upload the model for this session to the configured URL. + * + * @param session the Apex model editing session + * @return a result indicating if the upload was successful or not + */ + private ApexApiResult uploadModel(final RestSession session) { + LOGGER.entry(); + + ApexApiResult result = session.uploadModel(); LOGGER.exit("Model/Download" + (result != null && result.isOk() ? OK : NOT_OK)); return result; @@ -285,9 +290,8 @@ public class ModelHandler implements RestCommandHandler { * Delete the model for this session. * * @param session the Apex model editing session - * @return an ApexAPIResult object. If successful then - * {@link ApexApiResult#isOk()} will return true. Any messages/errors - * can be retrieved using {@link ApexApiResult#getMessages()} + * @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any + * messages/errors can be retrieved using {@link ApexApiResult#getMessages()} */ private ApexApiResult deleteModel(final RestSession session) { LOGGER.entry(); @@ -298,21 +302,18 @@ public class ModelHandler implements RestCommandHandler { session.finishSession(result.isOk()); - LOGGER.exit("Model/Delete" + (result != null && result.isOk() ? OK : NOT_OK)); + LOGGER.exit("Model/Delete" + (result.isOk() ? OK : NOT_OK)); return result; } /** - * The json strings representing the objects listed, stored in - * result.messages[], does not contain the AxKeyInformation for that object. - * This utility method retrieves the AxKeyInfo for each object and adds it to - * the json for the object. + * The json strings representing the objects listed, stored in result.messages[], does not contain the + * AxKeyInformation for that object. This utility method retrieves the AxKeyInfo for each object and adds it to the + * json for the object. * * @param session the Apex model editing session - * @param incomingResult The list result, containing JSON representations of - * objects stored in its "messages" array - * @return The list result, containing JSON augmented representations of objects - * stored in its "messages" array + * @param incomingResult The list result, containing JSON representations of objects stored in its "messages" array + * @return The list result, containing JSON augmented representations of objects stored in its "messages" array */ private ApexApiResult addKeyInfo2Messages(final RestSession session, final ApexApiResult incomingResult) { final ApexApiResult result = new ApexApiResult(incomingResult.getResult()); @@ -389,7 +390,7 @@ public class ModelHandler implements RestCommandHandler { * * @param jsonObject the object to query * @param fieldTag the tag of the field to condition - * @param value the default value of the field to condition + * @param value the default value of the field to condition * @return field read from the json */ private String readFieldFromJsonObject(final JsonObject jsonObject, final String fieldTag, final String value) { diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/PolicyUploadHandler.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/PolicyUploadHandler.java deleted file mode 100644 index 3540b2d..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/PolicyUploadHandler.java +++ /dev/null @@ -1,184 +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; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Optional; -import javax.ws.rs.core.Response; -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; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.gui.editors.apex.rest.UploadPluginConfigParameters; -import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ApexConfigProcessor; -import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter; -import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ProcessedTemplate; -import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor; -import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.exception.PolicyToscaConverterException; -import org.onap.policy.gui.editors.apex.rest.handling.plugin.upload.UploadPluginClient; -import org.onap.policy.gui.editors.apex.rest.handling.plugin.upload.UploadPolicyRequestDto; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * Handles the Policy Model upload. - */ -public class PolicyUploadHandler { - - private static final XLogger LOGGER = XLoggerFactory.getXLogger(PolicyUploadHandler.class); - private final PolicyToscaConverter policyToscaConverter; - private final ToscaTemplateProcessor toscaTemplateProcessor; - private final ApexConfigProcessor apexConfigProcessor; - private final UploadPluginClient uploadPluginClient; - private final UploadPluginConfigParameters uploadPluginConfigParameters; - - /** - * Creates the upload handler with its necessary dependencies. - * - * @param uploadPluginClient the UploadPluginClient instance - * @param policyToscaConverter the PolicyToscaConverter instance - * @param toscaTemplateProcessor the ToscaTemplateProcessor instance - * @param apexConfigProcessor the ApexConfigProcessor instance - * @param uploadPluginConfigParameters the Config instance - */ - public PolicyUploadHandler(final UploadPluginClient uploadPluginClient, - final PolicyToscaConverter policyToscaConverter, - final ToscaTemplateProcessor toscaTemplateProcessor, - final ApexConfigProcessor apexConfigProcessor, - final UploadPluginConfigParameters uploadPluginConfigParameters) { - this.uploadPluginClient = uploadPluginClient; - this.policyToscaConverter = policyToscaConverter; - this.toscaTemplateProcessor = toscaTemplateProcessor; - this.apexConfigProcessor = apexConfigProcessor; - this.uploadPluginConfigParameters = uploadPluginConfigParameters; - } - - /** - * Handles the policy model upload converting it to TOSCA with given template files. - * - * @param apexModel the apex model that contains the policy model - * @param toscaTemplateInputStream the tosca template input stream - * @param apexConfigInputStream the apex config input stream - * @return the result of the upload process - */ - public ApexApiResult doUpload(final ApexModel apexModel, final InputStream toscaTemplateInputStream, - final InputStream apexConfigInputStream, final String userId) { - final ProcessedTemplate processedToscaTemplate; - try { - processedToscaTemplate = toscaTemplateProcessor.process(toscaTemplateInputStream); - } catch (final IOException e) { - final ApexApiResult result = new ApexApiResult(Result.FAILED); - result.addThrowable(e); - final String errorMsg = "Could not process the tosca template file"; - result.addMessage(errorMsg); - LOGGER.error(errorMsg, e); - return result; - } - if (!processedToscaTemplate.isValid()) { - return buildResponse(processedToscaTemplate); - } - - final ProcessedTemplate processedApexConfig; - try { - processedApexConfig = apexConfigProcessor.process(apexConfigInputStream); - } catch (final IOException e) { - final ApexApiResult result = new ApexApiResult(Result.FAILED); - result.addThrowable(e); - final String errorMsg = "Could not process the apex config file"; - result.addMessage(errorMsg); - LOGGER.error(errorMsg, e); - return result; - } - if (!processedApexConfig.isValid()) { - return buildResponse(processedApexConfig); - } - return doUpload(apexModel, processedToscaTemplate.getContent(), processedApexConfig.getContent(), userId); - } - - private ApexApiResult doUpload(final ApexModel apexModel, final String toscaTemplate, final String apexConfig, - final String userId) { - LOGGER.entry(); - if (!isUploadPluginEnabled()) { - final ApexApiResult apexApiResult = new ApexApiResult(Result.FAILED); - apexApiResult.addMessage("Upload feature is disabled"); - return apexApiResult; - } - final AxPolicyModel policyModel = apexModel.getPolicyModel(); - final ApexApiResult result = apexModel.listModel(); - final UploadPolicyRequestDto uploadPolicyRequestDto = new UploadPolicyRequestDto(); - final AxArtifactKey policyKey = policyModel.getKeyInformation().getKey(); - final java.util.UUID uuid = policyModel.getKeyInformation().get(policyKey).getUuid(); - uploadPolicyRequestDto.setUserId(userId); - uploadPolicyRequestDto - .setFilename(String.format("%s.%s.%s", uuid, policyKey.getName(), policyKey.getVersion())); - final String apexPolicy = convert(result.getMessage(), toscaTemplate, apexConfig).orElse(null); - if (apexPolicy == null) { - final ApexApiResult apexApiResult = new ApexApiResult(Result.FAILED); - apexApiResult.addMessage( - String.format("An error has occurred while uploading the converting the Policy '%s' to YAML.", - policyModel.getId())); - LOGGER.exit("Model/Upload: NOT OK"); - return apexApiResult; - } - uploadPolicyRequestDto.setFileData( - Base64.getEncoder().encodeToString(apexPolicy.getBytes(StandardCharsets.UTF_8))); - final Response response = uploadPluginClient.upload(uploadPolicyRequestDto); - if (response.getStatus() == 201) { - final ApexApiResult apexApiResult = new ApexApiResult(Result.SUCCESS); - apexApiResult.addMessage(String.format("Policy '%s' uploaded successfully", policyModel.getId())); - LOGGER.exit("Model/Upload: OK"); - return apexApiResult; - } else { - final ApexApiResult apexApiResult = new ApexApiResult(Result.FAILED); - apexApiResult.addMessage( - String.format("An error has occurred while uploading the Policy '%s'. Status was %s", - policyModel.getId(), response.getStatus())); - LOGGER.exit("Model/Upload: NOT OK"); - return apexApiResult; - } - } - - private ApexApiResult buildResponse(final ProcessedTemplate processedTemplate) { - final ApexApiResult result = new ApexApiResult(Result.SUCCESS); - if (!processedTemplate.isValid()) { - result.setResult(Result.OTHER_ERROR); - processedTemplate.getErrorSet().forEach(result::addMessage); - } - return result; - } - - private boolean isUploadPluginEnabled() { - return uploadPluginConfigParameters.isEnabled(); - } - - private Optional<String> convert(final String apexPolicy, final String toscaTemplate, final String apexConfig) { - try { - return policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate); - } catch (final PolicyToscaConverterException e) { - LOGGER.error("Could not convert policy to TOSCA", e); - } - - return Optional.empty(); - } -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestCommand.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestCommand.java index 0b6a012..88524f4 100644 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestCommand.java +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestCommand.java @@ -61,5 +61,9 @@ public enum RestCommand { /** * Download the currently loaded apex model. */ - DOWNLOAD + DOWNLOAD, + /** + * Upload the currently loaded apex model. + */ + UPLOAD } 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 6e12648..c0c53cd 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 @@ -21,32 +21,106 @@ 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; import org.onap.policy.apex.model.modelapi.ApexModelFactory; +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; +import org.onap.policy.models.tosca.utils.ToscaUtils; /** - * This class represents an ongoing editor session in the Apex editor and holds - * the information for the session. + * This class represents an ongoing editor session in the Apex editor and holds the information for the session. * */ public class RestSession { + // The default TOSCA wrapper for an APEX policy + private static final String APEX_TOSCA_POLICY_TEMPLATE = "templates/ApexToscaPolicyTemplate.yaml"; + + // Recurring string constants + private static final String ENGINE_SERVICE_PARAMETERS = "engineServiceParameters"; + private static final String POLICY_TYPE_IMPL = "policy_type_impl"; + // The ID of the session private int sessionId; + // The TOSCA Service Template of the session + private ToscaServiceTemplate toscaServiceTemplate; + // The Apex policy model of the session private ApexModel apexModel; // The Apex policy model being edited private ApexModel apexModelEdited; + /** + * Constructor, create the session. + * + * @param sessionId the session ID of the session + * @throws ApexRuntimeException when the APEX TOSCA template file cannot be loaded + */ public RestSession(final int sessionId) { this.sessionId = sessionId; + + try { + this.toscaServiceTemplate = new StandardYamlCoder() + .decode(ResourceUtils.getResourceAsString(APEX_TOSCA_POLICY_TEMPLATE), ToscaServiceTemplate.class); + } catch (CoderException e) { + throw new ApexRuntimeException("could not load default APEX TOSCA template " + APEX_TOSCA_POLICY_TEMPLATE, + e); + } + this.apexModel = new ApexModelFactory().createApexModel(null, true); } /** + * Load the policy model from a TOSCA Service Template. + * + * @param toscaServiceTemplateString The TOSCA service template string + * @return the result of the lading operation + */ + public ApexApiResult loadFromString(final String toscaServiceTemplateString) { + try { + if (toscaServiceTemplateString.startsWith("{")) { + toscaServiceTemplate = new StandardCoder().decode(toscaServiceTemplateString, + ToscaServiceTemplate.class); + } else { + toscaServiceTemplate = new StandardYamlCoder().decode(toscaServiceTemplateString, + ToscaServiceTemplate.class); + } + } catch (Exception e) { + return new ApexApiResult(Result.FAILED, "incoming model is not a TOSCA Service template", e); + } + + if (!ToscaUtils.doPoliciesExist(new JpaToscaServiceTemplate(toscaServiceTemplate))) { + return new ApexApiResult(Result.FAILED, "no policies found on incoming TOSCA service template"); + } + + @SuppressWarnings("unchecked") + Map<String, Object> apexEngineServiceParameterMap = (Map<String, Object>) toscaServiceTemplate + .getToscaTopologyTemplate().getPoliciesAsMap().values().iterator().next().getProperties() + .get(ENGINE_SERVICE_PARAMETERS); + + String apexModelString; + try { + apexModelString = new StandardCoder().encode(apexEngineServiceParameterMap.get(POLICY_TYPE_IMPL)); + } catch (CoderException e) { + return new ApexApiResult(Result.FAILED, "APEX model not found TOSCA Service template", e); + } + + return apexModelEdited.loadFromString(apexModelString); + } + + /** * Commence making changes to the Apex model. * * @return the result of the edit commencement operation @@ -90,9 +164,63 @@ public class RestSession { } /** + * Download the apex model as a TOSCA service template YAML string. + * + * @return the apex model as a TOSCA service template YAML string + */ + public ApexApiResult downloadModel() { + ApexModel apexModelToDownload = (apexModelEdited == null ? apexModel : apexModelEdited); + + ToscaPolicy ap = toscaServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().values().iterator().next(); + + @SuppressWarnings("unchecked") + Map<String, Object> apexEngineServiceParameterMap = (Map<String, Object>) ap.getProperties() + .get(ENGINE_SERVICE_PARAMETERS); + + Object decoded = null; + try { + decoded = new StandardCoder().decode(apexModelToDownload.listModel().getMessage(), Object.class); + } catch (Exception e) { + return new ApexApiResult(Result.FAILED, "insertion of APEX model into TOSCA Service template failed", e); + } + + apexEngineServiceParameterMap.put(POLICY_TYPE_IMPL, decoded); + + ApexApiResult result = new ApexApiResult(); + try { + result.addMessage(new StandardYamlCoder().encode(toscaServiceTemplate)); + } catch (CoderException e) { + return new ApexApiResult(Result.FAILED, "encoding of TOSCA Service template into YAML failed", e); + } + + return result; + } + + /** + * Upload the apex model as a TOSCA service template YAML string to the configured URL. + * + * @return a result indicating if the upload was successful or not + */ + public ApexApiResult uploadModel() { + // 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(); + + String policyModelUUid = apexModelBeingUploaded.getPolicyModel().getKeyInformation().get(policyModelKey) + .getUuid().toString(); + return new PolicyUploadHandler().doUpload(result.getMessage(), policyModelKey, policyModelUUid); + } + + /** * Finish a session by committing or discarding the changes. * - * @param commitFlag if ture, commit changes otherwise discard them + * @param commitFlag if true, commit changes otherwise discard them */ public void finishSession(boolean commitFlag) { if (commitFlag) { diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessor.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessor.java deleted file mode 100644 index e05b833..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessor.java +++ /dev/null @@ -1,117 +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.converter.tosca; - -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ApexConfigProcessor.ErrorMessage.INVALID_APEX_CONFIG; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ApexConfigProcessor.ErrorMessage.INVALID_ENTRY; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ApexConfigProcessor.ErrorMessage.MISSING_ENTRY; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.ENGINE_SERVICE_PARAMETERS; - -import com.google.gson.JsonObject; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.HashSet; -import java.util.Set; -import lombok.AllArgsConstructor; -import org.apache.commons.io.IOUtils; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Process the Apex Config JSON template file. - */ -public class ApexConfigProcessor { - - private static final Logger LOGGER = LoggerFactory.getLogger(ApexConfigProcessor.class); - - private final StandardCoder standardCoder; - - public ApexConfigProcessor(final StandardCoder standardCoder) { - this.standardCoder = standardCoder; - } - - /** - * Process the Apex Config JSON template file. - * - * @param apexConfigInputStream the input stream for the Apex Config JSON template - * @return the result of the processing with the read JSON and its errors. - */ - public ProcessedTemplate process(final InputStream apexConfigInputStream) throws IOException { - final ProcessedTemplate processedTemplate = new ProcessedTemplate(); - final String templateAsString; - try (final InputStream inputStream = apexConfigInputStream) { - templateAsString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - } - final Set<String> errorSet = validate(templateAsString); - processedTemplate.setContent(templateAsString); - processedTemplate.addToErrors(errorSet); - - return processedTemplate; - } - - private Set<String> validate(final String apexConfig) { - final Set<String> errorSet = new HashSet<>(); - final JsonObject apexConfigJson; - try { - apexConfigJson = standardCoder.decode(apexConfig, JsonObject.class); - } catch (final CoderException e) { - LOGGER.debug(INVALID_APEX_CONFIG.getMessage(), e); - errorSet.add(INVALID_APEX_CONFIG.getMessage()); - return errorSet; - } - - final JsonObject topologyTemplate; - try { - topologyTemplate = apexConfigJson.getAsJsonObject(ENGINE_SERVICE_PARAMETERS.getKey()); - } catch (final Exception e) { - final String errorMsg = INVALID_ENTRY.getMessage(ENGINE_SERVICE_PARAMETERS.getKey()); - LOGGER.debug(errorMsg, e); - errorSet.add(errorMsg); - return errorSet; - } - - if (topologyTemplate == null) { - errorSet.add(MISSING_ENTRY.getMessage(ENGINE_SERVICE_PARAMETERS.getKey())); - return errorSet; - } - - return errorSet; - } - - /** - * Stores the possible error messages for the Apex Config template validation process. - */ - @AllArgsConstructor - public enum ErrorMessage { - MISSING_ENTRY("Missing '%s' entry"), - INVALID_ENTRY("Invalid entry '%s' provided"), - INVALID_APEX_CONFIG("Invalid apex config provided"); - - private final String messageFormat; - - public String getMessage(final String... params) { - return String.format(this.messageFormat, params); - } - } - -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverter.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverter.java deleted file mode 100644 index 0bacb24..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverter.java +++ /dev/null @@ -1,168 +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.converter.tosca; - -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.ENGINE_SERVICE_PARAMETERS; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.POLICIES; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.POLICY_TYPE_IMPL; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.PROPERTIES; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.TOPOLOGY_TEMPLATE; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import java.util.Map.Entry; -import java.util.Optional; -import lombok.Getter; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.onap.policy.common.utils.coder.YamlJsonTranslator; -import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.exception.PolicyToscaConverterException; - -/** - * Handles the conversion from policy JSON to policy YAML. - */ -public class PolicyToscaConverter { - - private final StandardCoder standardCoder; - private final YamlJsonTranslator yamlJsonTranslator; - - /** - * Creates a policy tosca converter. - * - * @param standardCoder the encoder that will handle JSON conversions - * @param yamlJsonTranslator the translator that will handle YAML conversions - */ - public PolicyToscaConverter(final StandardCoder standardCoder, final YamlJsonTranslator yamlJsonTranslator) { - this.standardCoder = standardCoder; - this.yamlJsonTranslator = yamlJsonTranslator; - } - - /** - * Converts the policy model to TOSCA, by merging the 3 given JSON models. - * - * @param policyModelJsonString the policy model JSON - * @param apexConfigJsonString the apex config JSON - * @param toscaTemplateJsonString the base TOSCA template in JSON format - * @return the merged policy model in YAML format - * @throws PolicyToscaConverterException when a JSON string could not be parsed to JsonObject or the resulting JSON - * could not be parsed to YAML. - */ - public Optional<String> convert(final String policyModelJsonString, final String apexConfigJsonString, - final String toscaTemplateJsonString) throws PolicyToscaConverterException { - final JsonObject apexConfigJson = decodeToJson(apexConfigJsonString); - final JsonObject policyModelJson = decodeToJson(policyModelJsonString); - final JsonObject toscaTemplateJson = decodeToJson(toscaTemplateJsonString); - - final JsonObject toscaPolicyProperties = readTopologyTemplateAsJsonObject(toscaTemplateJson); - final JsonObject toscaPolicy = readToscaPolicyAsJsonObject(toscaPolicyProperties); - final JsonObject toscaProperties = readPolicyPropertiesAsJsonObject(toscaPolicy); - - for (final Entry<String, JsonElement> entry : apexConfigJson.entrySet()) { - if (ENGINE_SERVICE_PARAMETERS.getKey().equals(entry.getKey())) { - final JsonObject engineServiceParameters = readEngineServiceParametersAsJsonObject(entry.getValue()); - engineServiceParameters.add(POLICY_TYPE_IMPL.getKey(), policyModelJson); - } - toscaProperties.add(entry.getKey(), entry.getValue()); - } - return Optional.ofNullable(convertToYaml(toscaTemplateJson)); - } - - private JsonObject readTopologyTemplateAsJsonObject(final JsonObject toscaTemplateJson) - throws PolicyToscaConverterException { - - try { - return toscaTemplateJson.get(TOPOLOGY_TEMPLATE.getKey()).getAsJsonObject(); - } catch (final Exception e) { - throw new PolicyToscaConverterException( - String.format("Could not read the '%s' entry in the Tosca Template", TOPOLOGY_TEMPLATE.getKey()), e); - } - } - - private JsonObject readEngineServiceParametersAsJsonObject(final JsonElement engineServiceParametersEntry) - throws PolicyToscaConverterException { - - try { - return engineServiceParametersEntry.getAsJsonObject(); - } catch (final Exception e) { - throw new PolicyToscaConverterException( - String.format("Could not read the '%s' in the Apex Config", ENGINE_SERVICE_PARAMETERS.getKey()), e); - } - } - - private JsonObject readToscaPolicyAsJsonObject(final JsonObject toscaPolicyProperties) - throws PolicyToscaConverterException { - - try { - return toscaPolicyProperties.get(POLICIES.getKey()).getAsJsonArray().get(0).getAsJsonObject(); - } catch (final Exception e) { - throw new PolicyToscaConverterException( - String.format("Could not read the first policy in the '%s' entry under '%s'", - POLICIES.getKey(), TOPOLOGY_TEMPLATE.getKey()), e); - } - } - - private JsonObject readPolicyPropertiesAsJsonObject(final JsonObject toscaPolicy) - throws PolicyToscaConverterException { - - try { - final String policyObjectKey = toscaPolicy.keySet().iterator().next(); - final JsonObject policyEntry = toscaPolicy.get(policyObjectKey).getAsJsonObject(); - return policyEntry.get(PROPERTIES.getKey()).getAsJsonObject(); - } catch (final Exception e) { - throw new PolicyToscaConverterException( - String.format("Could not read the policy '%s' entry", PROPERTIES.getKey()), e); - } - } - - private String convertToYaml(final JsonObject jsonObject) throws PolicyToscaConverterException { - try { - return yamlJsonTranslator.toYaml(jsonObject); - } catch (final Exception e) { - throw new PolicyToscaConverterException( - String.format("Could not convert JSON Object to YAML:%n%s", jsonObject.toString()), e); - } - } - - private JsonObject decodeToJson(final String jsonString) throws PolicyToscaConverterException { - try { - return standardCoder.decode(jsonString, JsonObject.class); - } catch (final CoderException e) { - throw new PolicyToscaConverterException( - String.format("Could not convert JSON string to JSON:%n%s", jsonString), e); - } - } - - @Getter - public enum ToscaKey { - TOPOLOGY_TEMPLATE("topology_template"), - TOSCA_DEFINITIONS_VERSION("tosca_definitions_version"), - PROPERTIES("properties"), - ENGINE_SERVICE_PARAMETERS("engineServiceParameters"), - POLICY_TYPE_IMPL("policy_type_impl"), - POLICIES("policies"); - - private final String key; - - ToscaKey(final String key) { - this.key = key; - } - } - -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ProcessedTemplate.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ProcessedTemplate.java deleted file mode 100644 index 1b4bb97..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ProcessedTemplate.java +++ /dev/null @@ -1,60 +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.converter.tosca; - -import java.util.HashSet; -import java.util.Set; -import lombok.Getter; -import lombok.Setter; -import org.apache.commons.collections4.CollectionUtils; - -@Getter -@Setter -public class ProcessedTemplate { - - private String content; - private final Set<String> errorSet; - - public ProcessedTemplate() { - errorSet = new HashSet<>(); - } - - /** - * Adds the given error messages to the errors collection. - * - * @param errorSet a set of error messages - */ - public void addToErrors(final Set<String> errorSet) { - if (CollectionUtils.isEmpty(errorSet)) { - return; - } - - this.errorSet.addAll(errorSet); - } - - /** - * Checks if the processed template is valid. - * - * @return {@code true} if the content is valid, {@code false} otherwise - */ - public boolean isValid() { - return CollectionUtils.isEmpty(errorSet); - } -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessor.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessor.java deleted file mode 100644 index 5539617..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessor.java +++ /dev/null @@ -1,179 +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.converter.tosca; - -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.POLICIES; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.PROPERTIES; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.TOPOLOGY_TEMPLATE; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.TOSCA_DEFINITIONS_VERSION; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.INVALID_ENTRY; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.INVALID_POLICY; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.INVALID_TOSCA_TEMPLATE; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.MISSING_ENTRY; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.MISSING_POLICY; -import static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.ToscaTemplateProcessor.ErrorMessage.ONLY_ONE_POLICY_ALLOWED; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import lombok.AllArgsConstructor; -import org.apache.commons.io.IOUtils; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Process the TOSCA JSON template file, base for the Policy Model TOSCA conversion. - */ -public class ToscaTemplateProcessor { - - private static final Logger LOGGER = LoggerFactory.getLogger(ToscaTemplateProcessor.class); - - private final StandardCoder jsonCoder; - - public ToscaTemplateProcessor(final StandardCoder jsonCoder) { - this.jsonCoder = jsonCoder; - } - - /** - * Process the TOSCA JSON template file. - * - * @param toscaTemplateInputStream the input stream for the TOSCA JSON template file - * @return the result of the processing with the read JSON and its errors. - */ - public ProcessedTemplate process(final InputStream toscaTemplateInputStream) throws IOException { - final ProcessedTemplate processedTemplate = new ProcessedTemplate(); - - final String templateAsString; - try (final InputStream inputStream = toscaTemplateInputStream) { - templateAsString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - } - - final Set<String> errorSet = validate(templateAsString); - processedTemplate.setContent(templateAsString); - processedTemplate.addToErrors(errorSet); - - return processedTemplate; - } - - private Set<String> validate(final String toscaTemplate) { - final Set<String> errorSet = new HashSet<>(); - final JsonObject toscaTemplateJson; - try { - toscaTemplateJson = jsonCoder.decode(toscaTemplate, JsonObject.class); - } catch (final CoderException e) { - LOGGER.debug(INVALID_TOSCA_TEMPLATE.getMessage(), e); - errorSet.add(INVALID_TOSCA_TEMPLATE.getMessage()); - return errorSet; - } - - final Optional<JsonPrimitive> toscaDefinitionVersionOpt = - readJsonEntry(TOSCA_DEFINITIONS_VERSION, toscaTemplateJson::getAsJsonPrimitive, errorSet); - if (toscaDefinitionVersionOpt.isEmpty()) { - return errorSet; - } - - final Optional<JsonObject> topologyTemplate = - readJsonEntry(TOPOLOGY_TEMPLATE, toscaTemplateJson::getAsJsonObject, errorSet); - if (topologyTemplate.isEmpty()) { - return errorSet; - } - - final Optional<JsonArray> policiesOpt = - readJsonEntry(POLICIES, topologyTemplate.get()::getAsJsonArray, errorSet); - if (policiesOpt.isEmpty()) { - return errorSet; - } - final JsonArray policies = policiesOpt.get(); - - if (policies.size() == 0) { - errorSet.add(MISSING_POLICY.getMessage()); - return errorSet; - } - - if (policies.size() > 1) { - errorSet.add(ONLY_ONE_POLICY_ALLOWED.getMessage()); - return errorSet; - } - - final JsonObject firstPolicy; - try { - final JsonObject firstPolicyObj = policies.get(0).getAsJsonObject(); - firstPolicy = firstPolicyObj.entrySet().iterator().next().getValue().getAsJsonObject(); - } catch (final Exception e) { - final String errorMsg = INVALID_POLICY.getMessage(); - LOGGER.debug(errorMsg, e); - errorSet.add(errorMsg); - return errorSet; - } - - readJsonEntry(PROPERTIES, firstPolicy::getAsJsonObject, errorSet); - - return errorSet; - } - - private <T> Optional<T> readJsonEntry(final ToscaKey toscaKey, - final Function<String, T> jsonFunction, final Set<String> errorSet) { - try { - final T json = jsonFunction.apply(toscaKey.getKey()); - if (json == null) { - errorSet.add(MISSING_ENTRY.getMessage(toscaKey.getKey())); - } - return Optional.ofNullable(json); - } catch (final Exception e) { - final String errorMsg = INVALID_ENTRY.getMessage(toscaKey.getKey()); - LOGGER.debug(errorMsg, e); - errorSet.add(errorMsg); - return Optional.empty(); - } - - } - - /** - * Stores the possible error messages for the Tosca template validation process. - */ - @AllArgsConstructor - public enum ErrorMessage { - MISSING_ENTRY("Missing '%s' entry"), - MISSING_POLICY("No policy was provided in the 'policies' list"), - INVALID_POLICY("Invalid policy was provided in the 'policies' list"), - ONLY_ONE_POLICY_ALLOWED("Only one policy entry is allowed in the 'policies' list"), - INVALID_TOSCA_TEMPLATE("Invalid tosca template provided"), - INVALID_ENTRY("Invalid entry '%s' provided"), - MISSING_PROPERTIES_ENTRY("Missing properties entry in '%s'"); - - private final String messageFormat; - - public String getMessage(final String... params) { - return String.format(this.messageFormat, params); - } - } - - -} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/exception/PolicyToscaConverterException.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/exception/PolicyToscaConverterException.java deleted file mode 100644 index 6b4eff1..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/exception/PolicyToscaConverterException.java +++ /dev/null @@ -1,28 +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.converter.tosca.exception; - -public class PolicyToscaConverterException extends Exception { - private static final long serialVersionUID = -7263407816909492236L; - - public PolicyToscaConverterException(final String message, final Throwable cause) { - super(message, cause); - } -} 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 new file mode 100644 index 0000000..5e3cf56 --- /dev/null +++ b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandler.java @@ -0,0 +1,103 @@ +/* + * ============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.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 javax.ws.rs.core.Response; +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; + +/** + * Handles the Policy Model upload. + */ +public class PolicyUploadHandler { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(PolicyUploadHandler.class); + + // Recurring string constants + private static final String MODEL_UPLOAD_NOT_OK = "Model/Upload: NOT OK"; + + /** + * 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 + * @return the result of the upload process + */ + public ApexApiResult doUpload(final String toscaServiceTemplate, final AxArtifactKey policyModelKey, + final String policyModelUuid) { + LOGGER.entry(); + + if (StringUtils.isBlank(ApexEditorMain.getParameters().getUploadUrl())) { + final ApexApiResult apexApiResult = new ApexApiResult(Result.FAILED); + apexApiResult.addMessage("Model download is disabled, parameter upload-url is not set on server"); + LOGGER.exit(MODEL_UPLOAD_NOT_OK); + return apexApiResult; + + } + + final UploadPolicyRequestDto uploadPolicyRequestDto = new UploadPolicyRequestDto(); + uploadPolicyRequestDto.setUserId(ApexEditorMain.getParameters().getUploadUserid()); + uploadPolicyRequestDto + .setFileData(Base64.getEncoder().encodeToString(toscaServiceTemplate.getBytes(StandardCharsets.UTF_8))); + uploadPolicyRequestDto.setFilename( + String.format("%s.%s.%s", policyModelUuid, policyModelKey.getName(), policyModelKey.getVersion())); + + try { + final Response response = ClientBuilder.newClient().target(ApexEditorMain.getParameters().getUploadUrl()) + .request(MediaType.APPLICATION_JSON) + .post(Entity.entity(uploadPolicyRequestDto, MediaType.APPLICATION_JSON)); + + if (response.getStatus() == 201) { + final ApexApiResult apexApiResult = new ApexApiResult(Result.SUCCESS); + String.format("uploading Policy '%s' to URL '%s' with userId '%s' was successful", + policyModelKey.getId(), ApexEditorMain.getParameters().getUploadUrl(), + ApexEditorMain.getParameters().getUploadUserid()); + LOGGER.exit("Model/Upload: OK"); + return apexApiResult; + } else { + final ApexApiResult apexApiResult = new ApexApiResult(Result.FAILED); + apexApiResult.addMessage( + String.format("uploading Policy '%s' to URL '%s' with userId '%s' failed with status %s", + policyModelKey.getId(), ApexEditorMain.getParameters().getUploadUrl(), + ApexEditorMain.getParameters().getUploadUserid(), response.getStatus())); + LOGGER.exit(MODEL_UPLOAD_NOT_OK); + return apexApiResult; + } + } catch (Exception e) { + final ApexApiResult apexApiResult = new ApexApiResult(Result.FAILED); + apexApiResult + .addMessage(String.format("uploading Policy '%s' to URL '%s' with userId '%s' failed with error %s", + policyModelKey.getId(), ApexEditorMain.getParameters().getUploadUrl(), + ApexEditorMain.getParameters().getUploadUserid(), e.getMessage())); + LOGGER.exit(MODEL_UPLOAD_NOT_OK); + return apexApiResult; + } + } +} diff --git a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClient.java b/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClient.java deleted file mode 100644 index d0c97c9..0000000 --- a/gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClient.java +++ /dev/null @@ -1,69 +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.plugin.upload; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import org.onap.policy.common.parameters.ParameterService; -import org.onap.policy.gui.editors.apex.rest.UploadPluginConfigParameters; - -/** - * Client for the Policy Model upload endpoint. - */ -public class UploadPluginClient { - - private final Client client; - private final UploadPluginConfigParameters uploadConfigParam; - - /** - * Create a upload plugin client. - */ - public UploadPluginClient() { - this(ClientBuilder.newClient(), ParameterService.get(UploadPluginConfigParameters.GROUP_NAME)); - } - - /** - * Create a upload plugin client. - * @param client the http client - * @param uploadConfigParam the upload configuration parameters - */ - UploadPluginClient(final Client client, - final UploadPluginConfigParameters uploadConfigParam) { - this.client = client; - this.uploadConfigParam = uploadConfigParam; - } - - /** - * Uploads the policy to the configured endpoint. - * - * @param uploadPolicyRequestDto the policy DTO to upload - * @return the request response - */ - public Response upload(final UploadPolicyRequestDto uploadPolicyRequestDto) { - return client - .target(uploadConfigParam.getUrl()) - .request(MediaType.APPLICATION_JSON) - .post(Entity.entity(uploadPolicyRequestDto, MediaType.APPLICATION_JSON)); - } - -} |