summaryrefslogtreecommitdiffstats
path: root/gui-editors/gui-editor-apex
diff options
context:
space:
mode:
authorliamfallon <liam.fallon@est.tech>2020-09-11 14:28:32 +0100
committerliamfallon <liam.fallon@est.tech>2020-09-11 14:37:24 +0100
commit9a9127b65920580de8b4a69479a9983481c8faf8 (patch)
tree35c6449e4850b661f86a639a33684e079beb836d /gui-editors/gui-editor-apex
parentafcf92da0d813028b48ea781df33148bc6f000b6 (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')
-rw-r--r--gui-editors/gui-editor-apex/pom.xml16
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorMain.java20
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameterParser.java84
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/ApexEditorParameters.java105
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParameters.java82
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResource.java139
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResource.java83
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/ModelHandler.java119
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/PolicyUploadHandler.java184
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestCommand.java6
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/RestSession.java134
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessor.java117
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverter.java168
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ProcessedTemplate.java60
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessor.java179
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/exception/PolicyToscaConverterException.java28
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/PolicyUploadHandler.java103
-rw-r--r--gui-editors/gui-editor-apex/src/main/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClient.java69
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/templates/ApexToscaPolicyTemplate.yaml17
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/css/upload/dialog.css56
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/dist/bundle.js1
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/index.html11
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexConfig.js62
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexContextSchemaEditForm.js5
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexFiles.js17
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexMain.js2
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexUpload.js61
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexUser.js32
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/js/__test__/ApexConfig.test.js43
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/js/__test__/ApexUser.test.js31
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/js/lib/pubsub/ba-tiny-pubsub.min.js4
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/package-lock.json42
-rw-r--r--gui-editors/gui-editor-apex/src/main/resources/webapp/upload/dialog.html68
-rw-r--r--gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/ApexEditorStartupTest.java143
-rw-r--r--gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/RestInterfaceTest.java47
-rw-r--r--gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParametersTest.java85
-rw-r--r--gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResourceTest.java2
-rw-r--r--gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResourceTest.java64
-rw-r--r--gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessorTest.java111
-rw-r--r--gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverterTest.java187
-rw-r--r--gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyUploadHandlerTest.java201
-rw-r--r--gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessorTest.java204
-rw-r--r--gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClientTest.java71
-rw-r--r--gui-editors/gui-editor-apex/src/test/resources/models/PolicyModel.json1521
-rw-r--r--gui-editors/gui-editor-apex/src/test/resources/models/PolicyModel.yaml538
45 files changed, 1960 insertions, 3362 deletions
diff --git a/gui-editors/gui-editor-apex/pom.xml b/gui-editors/gui-editor-apex/pom.xml
index 8c656d5..77ee266 100644
--- a/gui-editors/gui-editor-apex/pom.xml
+++ b/gui-editors/gui-editor-apex/pom.xml
@@ -70,6 +70,11 @@
</exclusions>
</dependency>
<dependency>
+ <groupId>org.onap.policy.models</groupId>
+ <artifactId>policy-models-tosca</artifactId>
+ <version>${policy.models.version}</version>
+ </dependency>
+ <dependency>
<groupId>org.onap.policy.apex-pdp.model</groupId>
<artifactId>model-api</artifactId>
<version>${policy.apex-pdp.version}</version>
@@ -98,6 +103,11 @@
<artifactId>commons-cli</artifactId>
</dependency>
<dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-text</artifactId>
+ <version>1.9</version>
+ </dependency>
+ <dependency>
<groupId>org.onap.policy.apex-pdp.client</groupId>
<artifactId>apex-client-common</artifactId>
<version>${policy.apex-pdp.version}</version>
@@ -108,7 +118,6 @@
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
- <version>${version.jersey}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
@@ -296,9 +305,10 @@
</filter>
</filters>
<transformers>
- <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer
- implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.onap.policy.gui.editors.apex.rest.ApexEditorMain</mainClass>
</transformer>
</transformers>
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));
- }
-
-}
diff --git a/gui-editors/gui-editor-apex/src/main/resources/templates/ApexToscaPolicyTemplate.yaml b/gui-editors/gui-editor-apex/src/main/resources/templates/ApexToscaPolicyTemplate.yaml
new file mode 100644
index 0000000..bcaf601
--- /dev/null
+++ b/gui-editors/gui-editor-apex/src/main/resources/templates/ApexToscaPolicyTemplate.yaml
@@ -0,0 +1,17 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+topology_template:
+ policies:
+ - onap.policies.native.apex.Template:
+ type: onap.policies.native.Apex
+ type_version: 1.0.0
+ properties:
+ engineServiceParameters:
+ name: TemplateApexEngine
+ version: 0.0.1
+ id: 1
+ instanceCount: 1
+ deploymentPort: 12561
+ engineParameters:
+ executorParameters:
+ contextParameters:
+ policy_type_impl:
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/css/upload/dialog.css b/gui-editors/gui-editor-apex/src/main/resources/webapp/css/upload/dialog.css
deleted file mode 100644
index 95f29b1..0000000
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/css/upload/dialog.css
+++ /dev/null
@@ -1,56 +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=========================================================
- */
-
-.upload-dialog {
- font-size: 16px;
- line-height: 19px;
-}
-
-.upload-dialog .ui-button {
- position: relative;
- display: inline-block;
- vertical-align: middle;
- color: #333333;
- background-color: #ffffff;
- border: none;
- min-width: 60px;
- box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.2);
- border-radius: 3px;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
- background-image: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.1) 100%);
- padding: 0 8px;
- height: 2.4rem;
- font-size: 1.2rem;
- white-space: nowrap;
- text-decoration: none;
- text-align: center;
- cursor: pointer;
-}
-
-.upload-dialog #upload-form {
- width: 100%;
- font-size: 16px;
- line-height: 19px;
-}
-
-.upload-dialog #upload-form input {
- width: 100%;
-} \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/dist/bundle.js b/gui-editors/gui-editor-apex/src/main/resources/webapp/dist/bundle.js
deleted file mode 100644
index 46c8469..0000000
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/dist/bundle.js
+++ /dev/null
@@ -1 +0,0 @@
-!function(e){var t={};function a(o){if(t[o])return t[o].exports;var n=t[o]={i:o,l:!1,exports:{}};return e[o].call(n.exports,n,n.exports,a),n.l=!0,n.exports}a.m=e,a.c=t,a.d=function(e,t,o){a.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},a.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.t=function(e,t){if(1&t&&(e=a(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(a.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)a.d(o,n,function(t){return e[t]}.bind(null,n));return o},a.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return a.d(t,"a",t),t},a.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},a.p="",a(a.s=0)}([function(e,t){var a=null;function o(){localStorage.removeItem("apex_session"),localStorage.removeItem("apex_model_loaded"),localStorage.removeItem("apex_tab_index")}$("#menu").fileMenu({slideSpeed:200}),$(document).ready((function(){pageControl_noModelMode(),function(){var e=location.protocol+"//"+window.location.hostname+(location.port?":"+location.port:"")+(location.pathname.endsWith("/editor/")?location.pathname.substring(0,location.pathname.indexOf("editor/")):location.pathname);if(localStorage.getItem("apex_session")){a=e+"apexservices/editor/"+localStorage.getItem("apex_session"),ajax_get(a+"/Model/GetKey",(function(e){if($("#statusMessageTable").append("<tr><td> REST root URL set to: "+a+"</td></tr>"),localStorage.getItem("apex_model_loaded")){var t=JSON.parse(e.messages.message[0]).apexArtifactKey;pageControl_modelMode(t.name,t.version,null),localStorage.getItem("apex_tab_index")&&$("#mainTabs").tabs({active:localStorage.getItem("apex_tab_index")})}}))}else{ajax_get(e+"apexservices/editor/-1/Session/Create",(function(t){localStorage.setItem("apex_session",t.messages.message[0]),a=e+"apexservices/editor/"+localStorage.getItem("apex_session"),$("#statusMessageTable").append("<tr><td> REST root URL set to: "+a+"</td></tr>")}))}}()})),$("#menu li").not(".emptyMessage").click((function(){switch(this.id){case"menuFileNew":newModelForm_activate(document.getElementById("mainArea"));break;case"menuFileOpen":files_fileOpen();break;case"menuFileDownload":files_fileDownload();break;case"menuFileUpload":uploadPlugin.openDialog();break;case"menuFileClear":if(confirm("Clear the current model?"))ajax_delete(a+"/Model/Delete",(function(e){localStorage.removeItem("apex_model_loaded"),localStorage.removeItem("apex_tab_index"),$("#mainTabs").tabs("option","active",0),pageControl_noModelMode()}));break;case"menuFileNewSession":o(),location.reload();break;case"menuFileClose":confirm("Close Apex Editor?")&&(o(),window.location.href=window.location.href+"close.html");break;case"menuModelAnalyse":modelHandling_analyse();break;case"menuModelValidate":modelHandling_validate();break;case"menuConceptsContextSchemas":$("#mainTabs").tabs("option","active",0);break;case"menuConceptsEvents":$("#mainTabs").tabs("option","active",1);break;case"menuConceptsContextAlbums":$("#mainTabs").tabs("option","active",2);break;case"menuConceptsTasks":$("#mainTabs").tabs("option","active",3);break;case"menuConceptsPolicies":$("#mainTabs").tabs("option","active",4);break;case"menuConceptsKeyInformation":$("#mainTabs").tabs("option","active",5)}}));var n=$(".ebInlineMessage").height();$(".ebInlineMessage").mouseenter((function(e){e.stopPropagation(),$(this).stop();var t=$(this).children(".ebInlineMessage-contentHolder").height();t>n&&$(".ebInlineMessage").animate({height:t+12},200)})),$(".ebInlineMessage").mouseleave((function(e){e.stopPropagation(),$(this).stop(),$(".ebInlineMessage").animate({height:n},200)})),$(document).ready((function(){$(".content").fadeIn()})),t.restRootURL={restRootURL:a}}]); \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/index.html b/gui-editors/gui-editor-apex/src/main/resources/webapp/index.html
index 7aa3508..d131d22 100644
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/index.html
+++ b/gui-editors/gui-editor-apex/src/main/resources/webapp/index.html
@@ -43,8 +43,6 @@
<!-- interface style -->
<link rel="stylesheet" type="text/css" href="css/interfaceAssets.css">
-<link rel="stylesheet" type="text/css" href="css/upload/dialog.css" />
-
<!-- JQuery style -->
<link rel="stylesheet" href="js/jquery-ui-1.12.1/jquery-ui.css">
@@ -216,9 +214,9 @@
<!-- edit area JS file -->
<script language="javascript" type="text/javascript"
src="js/edit_area/edit_area_full.js"></script>
- <!-- simple jquery pub/sub library -->
- <script type="text/javascript" src="js/lib/pubsub/ba-tiny-pubsub.min.js"></script>
<!-- Apex JS files -->
+ <script type="text/javascript" src="js/ApexFiles.js"></script>
+ <script type="text/javascript" src="js/ApexAjax.js"></script>
<script type="text/javascript" src="js/ApexTable.js"></script>
<script type="text/javascript" src="js/ApexContextSchemaTab.js"></script>
<script type="text/javascript" src="js/ApexContextSchemaEditForm.js"></script>
@@ -232,17 +230,12 @@
<script type="text/javascript" src="js/ApexPolicyEditForm_State.js"></script>
<script type="text/javascript" src="js/ApexPolicyEditForm.js"></script>
<script type="text/javascript" src="js/ApexKeyInformationTab.js"></script>
- <script type="text/javascript" src="js/ApexAjax.js"></script>
<script type="text/javascript" src="js/ApexPageControl.js"></script>
- <script type="text/javascript" src="js/ApexFiles.js"></script>
<script type="text/javascript" src="js/ApexFormUtils.js"></script>
<script type="text/javascript" src="js/ApexNewModelForm.js"></script>
<script type="text/javascript" src="js/ApexResultForm.js"></script>
<script type="text/javascript" src="js/ApexModelHandling.js"></script>
- <script type="text/javascript" src="js/ApexConfig.js"></script>
- <script type="text/javascript" src="js/ApexUpload.js"></script>
<script type="text/javascript" src="js/ApexMain.js"></script>
- <script type="text/javascript" src="js/ApexUser.js"></script>
</body>
</html>
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexConfig.js b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexConfig.js
deleted file mode 100644
index 9a842c2..0000000
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexConfig.js
+++ /dev/null
@@ -1,62 +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=========================================================
- */
-
-const configObj = {
- configMap: {},
- getConfig: function (configKey) {
- return this.configMap[configKey];
- },
- setConfig: function (configKey, configValue) {
- return this.configMap[configKey] = configValue;
- },
- readySignal: function () {
- $.publish("/config/ready");
- }
-}
-
-$(document).ready(function () {
- load();
-});
-
-const load = function(){
- $("#menuFileUpload").hide();
-
- const rootUrl = location.protocol
- + "//"
- + window.location.hostname
- + (location.port ? ':' + location.port : '');
-
- const configUrl = rootUrl + "/apexservices/editor/config";
-
- function loadConfiguration() {
- ajax_get(configUrl, function (data) {
- for (let i = 0; i < data.messages.message.length; i++) {
- const configEntry = JSON.parse(data.messages.message[i]);
- Object.keys(configEntry).forEach(key => {
- configObj.setConfig(key, configEntry[key]);
- });
- }
- configObj.readySignal();
- });
- }
- loadConfiguration();
-}
-
-module.exports = { configObj, load };
-module.exports.rootUrl = load.rootUrl;
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexContextSchemaEditForm.js b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexContextSchemaEditForm.js
index dac2e50..7eecb72 100644
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexContextSchemaEditForm.js
+++ b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexContextSchemaEditForm.js
@@ -19,11 +19,6 @@
* ============LICENSE_END=========================================================
*/
-const {ajax_put} = require("../../../../../target/classes/webapp/js/ApexAjax");
-const {ajax_post} = require("../../../../../target/classes/webapp/js/ApexAjax");
-const {ajax_delete} = require("../../../../../target/classes/webapp/js/ApexAjax");
-const {ajax_getWithKeyInfo} = require("../../../../../target/classes/webapp/js/ApexAjax");
-
function editContextSchemaForm_createContextSchema(formParent) {
return editContextSchemaForm_activate(formParent, "CREATE", null);
}
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexFiles.js b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexFiles.js
index 9171fd3..a8726e7 100644
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexFiles.js
+++ b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexFiles.js
@@ -19,9 +19,6 @@
* ============LICENSE_END=========================================================
*/
-const {ajax_get} = require("../../../../../target/classes/webapp/js/ApexAjax");
-const {ajax_put} = require("../../../../../target/classes/webapp/js/ApexAjax");
-
function files_fileOpen() {
$('<input type="file">').on('change', function() {
var reader = new FileReader();
@@ -53,4 +50,16 @@ function files_fileDownload() {
document.body.removeChild(downloadLink);
}
-module.exports = {files_fileDownload, files_fileOpen};
+function files_fileUpload() {
+ var requestURL = restRootURL + "/Model/Upload";
+
+ ajax_getOKOrFail(requestURL, function(data) {
+ var uploadResultString = "";
+ for (var i = 0; i < data.messages.message.length; i++) {
+ uploadResultString += (data.messages.message[i] + "\n");
+ }
+ resultForm_activate(document.getElementById("mainArea"), "Model Upload Result", uploadResultString);
+ });
+}
+
+module.exports = {files_fileUpload, files_fileDownload, files_fileOpen};
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexMain.js b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexMain.js
index 46d8398..9dea9b5 100644
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexMain.js
+++ b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexMain.js
@@ -44,7 +44,7 @@ $("#menu li").not(".emptyMessage").click(function() {
files_fileDownload();
break;
case "menuFileUpload":
- uploadPlugin.openDialog();
+ files_fileUpload();
break;
case "menuFileClear":
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexUpload.js b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexUpload.js
deleted file mode 100644
index a71853c..0000000
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexUpload.js
+++ /dev/null
@@ -1,61 +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=========================================================
- */
-
-$(document).ready(function () {
- $.subscribe("/config/ready", enableUpload);
-
- function enableUpload() {
- const menuFileUpload = $('#menuFileUpload');
- const isUploadEnabled = configObj.getConfig("plugin.policy.upload.enable");
- if (isUploadEnabled === "true" || isUploadEnabled === true) {
- menuFileUpload.show();
- } else {
- menuFileUpload.hide();
- }
- }
-
-});
-
-const uploadPlugin = {
- dialogDiv: $('#main-dialog'),
- openDialog: function () {
- this.dialogDiv.load('../upload/dialog.html');
- },
-
- upload: function (data, successCallback, errorCallback) {
- const requestURL = restRootURL + "/Model/Upload";
- $.ajax({
- type: 'POST',
- url: requestURL,
- data: data,
- contentType: false,
- processData: false
- }).done(function (data) {
- pageControl_successStatus(data);
- if (typeof successCallback === typeof Function) {
- successCallback(data);
- }
- }).fail(function (jqXHR, textStatus, errorThrown) {
- pageControl_restError(requestURL, jqXHR, textStatus, errorThrown);
- if (typeof errorCallback === typeof Function) {
- errorCallback(jqXHR, textStatus, errorThrown);
- }
- });
- }
-}
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexUser.js b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexUser.js
deleted file mode 100644
index e30f5dd..0000000
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexUser.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-const userManager = {
- userId: null
-};
-
-(function () {
- //grabbing the userId
- const urlParams = new URLSearchParams(window.location.search);
- userManager.userId = urlParams.get('userId');
-})();
-
-exports = {userManager}; \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/__test__/ApexConfig.test.js b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/__test__/ApexConfig.test.js
deleted file mode 100644
index 02d8406..0000000
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/__test__/ApexConfig.test.js
+++ /dev/null
@@ -1,43 +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=========================================================
- */
-
-const apexConfig = require('../ApexConfig');
-
-test('configObj called successfully', () => {
- expect(apexConfig.configObj.getConfig()).not.toBeNull();
- expect(apexConfig.configObj.setConfig()).not.toBeNull();
- expect(apexConfig.configObj).toHaveProperty('configMap');
-});
-
-test('load called successfully', () => {
- expect(apexConfig.rootUrl).not.toBe(null);
- const mock = jest.fn(apexConfig.load).mockImplementation(() => {
- function test (data) {
- for (let i = 0; i < data.messages.message.length; i++) {
- const configEntry = JSON.parse(data.messages.message[i]);
- Object.keys(configEntry).forEach(key => {
- configObj.setConfig(key, configEntry[key]);
- });
- }
- configObj.readySignal();
- };
- });
- mock();
- expect(mock).toHaveBeenCalledTimes(1);
-}); \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/__test__/ApexUser.test.js b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/__test__/ApexUser.test.js
deleted file mode 100644
index 1d445c4..0000000
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/__test__/ApexUser.test.js
+++ /dev/null
@@ -1,31 +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=========================================================
- */
-
-const user = require('../ApexUser');
-
-test('userManager test', () => {
- const userMock = {
- userId: u => {
- return `userId: ${u}`;
- },
- }
- const spy = jest.spyOn(userMock, 'userId');
- expect(userMock.userId('userTest')).toBe('userId: userTest');
- expect(spy).toHaveBeenCalledWith('userTest');
-}); \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/lib/pubsub/ba-tiny-pubsub.min.js b/gui-editors/gui-editor-apex/src/main/resources/webapp/js/lib/pubsub/ba-tiny-pubsub.min.js
deleted file mode 100644
index 635ab34..0000000
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/js/lib/pubsub/ba-tiny-pubsub.min.js
+++ /dev/null
@@ -1,4 +0,0 @@
-/*! Tiny Pub/Sub - v0.7.0 - 2013-01-29
-* https://github.com/cowboy/jquery-tiny-pubsub
-* Copyright (c) 2013 "Cowboy" Ben Alman; Licensed MIT */
-(function(n){var u=n({});n.subscribe=function(){u.on.apply(u,arguments)},n.unsubscribe=function(){u.off.apply(u,arguments)},n.publish=function(){u.trigger.apply(u,arguments)}})(jQuery); \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/package-lock.json b/gui-editors/gui-editor-apex/src/main/resources/webapp/package-lock.json
index 0b398d7..b218308 100644
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/package-lock.json
+++ b/gui-editors/gui-editor-apex/src/main/resources/webapp/package-lock.json
@@ -83,7 +83,11 @@
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
"dev": true,
- "optional": true
+ "optional": true,
+ "requires": {
+ "bindings": "^1.5.0",
+ "nan": "^2.12.1"
+ }
},
"glob-parent": {
"version": "3.1.0",
@@ -2741,6 +2745,16 @@
"dev": true,
"optional": true
},
+ "bindings": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
+ "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "file-uri-to-path": "1.0.0"
+ }
+ },
"bluebird": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
@@ -4384,6 +4398,13 @@
"integrity": "sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw==",
"dev": true
},
+ "file-uri-to-path": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
+ "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
+ "dev": true,
+ "optional": true
+ },
"fill-range": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz",
@@ -7440,6 +7461,13 @@
"integrity": "sha1-iZ8R2WhuXgXLkbNdXw5jt3PPyQE=",
"dev": true
},
+ "nan": {
+ "version": "2.14.1",
+ "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.1.tgz",
+ "integrity": "sha512-isWHgVjnFjh2x2yuJ/tj3JbwoHu3UC2dX5G/88Cm24yB6YopVgxvBObDY7n5xW6ExmFhJpSEQqFPvq9zaXc8Jw==",
+ "dev": true,
+ "optional": true
+ },
"nanomatch": {
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz",
@@ -10150,7 +10178,11 @@
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
"dev": true,
- "optional": true
+ "optional": true,
+ "requires": {
+ "bindings": "^1.5.0",
+ "nan": "^2.12.1"
+ }
},
"glob-parent": {
"version": "3.1.0",
@@ -10551,7 +10583,11 @@
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
"dev": true,
- "optional": true
+ "optional": true,
+ "requires": {
+ "bindings": "^1.5.0",
+ "nan": "^2.12.1"
+ }
},
"glob-parent": {
"version": "3.1.0",
diff --git a/gui-editors/gui-editor-apex/src/main/resources/webapp/upload/dialog.html b/gui-editors/gui-editor-apex/src/main/resources/webapp/upload/dialog.html
deleted file mode 100644
index 912bec4..0000000
--- a/gui-editors/gui-editor-apex/src/main/resources/webapp/upload/dialog.html
+++ /dev/null
@@ -1,68 +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=========================================================
- -->
-
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <title>Upload Policy</title>
- <script>
- $(document).ready(function () {
- function upload() {
- const data = new FormData();
- const apexConfigFile = $('#apex-config-file')[0].files[0];
- const toscaTemplateFile = $('#tosca-template-file')[0].files[0];
- data.append('apex-config-file', apexConfigFile);
- data.append('tosca-template-file', toscaTemplateFile);
- data.append('userId', userManager.userId);
- uploadPlugin.upload(data, function () {
- dialog.dialog("close");
- });
- }
-
- const dialog = $('#inner-dialog').dialog({
- height: 300,
- width: 435,
- modal: true,
- dialogClass: 'upload-dialog',
- buttons: {
- "Upload": upload,
- Cancel: function() {
- dialog.dialog("close");
- }
- }
- });
- });
-
- </script>
-</head>
-<body>
-<div id="inner-dialog" title="Upload Policy" class="upload-dialog">
- <p>Provide the following files to compose the policy TOSCA</p>
- <div id="upload-form">
- <label for="apex-config-file">Apex Config</label> <br/>
- <input id="apex-config-file" type="file" required="required" accept="application/json"
- class="ui-widget-content ui-corner-all"/> <br/>
- <label for="tosca-template-file">Tosca Template</label> <br/>
- <input id="tosca-template-file" type="file" required="required" accept="application/json"
- class="ui-widget-content ui-corner-all"/>
- </div>
-</div>
-</body>
-</html>
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/ApexEditorStartupTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/ApexEditorStartupTest.java
index c80b816..d78eba3 100644
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/ApexEditorStartupTest.java
+++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/ApexEditorStartupTest.java
@@ -50,16 +50,16 @@ public class ApexEditorStartupTest {
final String[] args = new String[] {};
final String outString = runEditor(args);
- assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], "
- + "State=READY) starting at http://localhost:18989/apexservices/"));
- assertTrue(outString.contains("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], "
- + "State=RUNNING) started at http://localhost:18989/apexservices/"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .endsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec],"
- + " State=STOPPED) shut down "));
+
+ assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain:"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("State=RUNNING) started"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("help=false"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("restPort=18989"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("timeToLive=-1"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("listenAddress=localhost"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("uploadUrl=null"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("uploadUserid=null"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").endsWith(" State=STOPPED) shut down "));
}
/**
@@ -73,8 +73,7 @@ public class ApexEditorStartupTest {
final String[] args = new String[] { "12321" };
assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class)
- .hasMessageContaining("Apex Editor REST endpoint (ApexEditorMain: Config=[null], State=STOPPED)"
- + " parameter error, too many command line arguments specified : [12321]");
+ .hasMessageContaining("parameter error, too many command line arguments specified : [12321]");
}
/**
@@ -88,8 +87,7 @@ public class ApexEditorStartupTest {
final String[] args = new String[] { "12321 12322 12323" };
assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class)
- .hasMessageContaining("Apex Editor REST endpoint (ApexEditorMain: Config=[null], State=STOPPED)"
- + " parameter error, too many command line arguments specified : [12321 12322 12323]");
+ .hasMessageContaining("parameter error, too many command line arguments specified : [12321 12322 12323]");
}
/**
@@ -102,9 +100,8 @@ public class ApexEditorStartupTest {
public void testBadArg2() throws IOException, InterruptedException {
final String[] args = new String[] { "-z" };
- assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class)
- .hasMessageContaining("Apex Editor REST endpoint (ApexEditorMain: Config=[null], State=STOPPED)"
- + " parameter error, invalid command line arguments specified : Unrecognized option: -z");
+ assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class).hasMessageContaining(
+ "parameter error, invalid command line arguments specified : Unrecognized option: -z");
}
/**
@@ -117,9 +114,8 @@ public class ApexEditorStartupTest {
public void testBadArg3() throws IOException, InterruptedException {
final String[] args = new String[] { "--hello" };
- assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class)
- .hasMessageContaining("Apex Editor REST endpoint (ApexEditorMain: Config=[null], State=STOPPED)"
- + " parameter error, invalid command line arguments specified : Unrecognized option: --hello");
+ assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class).hasMessageContaining(
+ "parameter error, invalid command line arguments specified : Unrecognized option: --hello");
}
/**
@@ -133,9 +129,7 @@ public class ApexEditorStartupTest {
final String[] args = new String[] { "-l", "+++++" };
assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class)
- .hasMessageContaining("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://+++++:18989/apexservices/, TTL=-1sec], "
- + "State=STOPPED) parameters invalid, listen address is not valid. "
+ .hasMessageContaining("parameters invalid, listen address is not valid. "
+ "Illegal character in hostname at index 7: http://+++++:18989/apexservices/");
}
@@ -179,16 +173,10 @@ public class ApexEditorStartupTest {
final String outString = runEditor(args);
- assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:12321/apexservices/, TTL=-1sec], "
- + "State=READY) starting at http://localhost:12321/apexservices/"));
- assertTrue(outString.contains("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:12321/apexservices/, TTL=-1sec], "
- + "State=RUNNING) started at http://localhost:12321/apexservices/"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .endsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:12321/apexservices/, TTL=-1sec],"
- + " State=STOPPED) shut down "));
+ assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain:"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("State=RUNNING) started"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("localhost:12321"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").endsWith(" State=STOPPED) shut down "));
}
/**
@@ -203,16 +191,10 @@ public class ApexEditorStartupTest {
final String outString = runEditor(args);
- assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:12321/apexservices/, TTL=-1sec], "
- + "State=READY) starting at http://localhost:12321/apexservices/"));
- assertTrue(outString.contains("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:12321/apexservices/, TTL=-1sec], "
- + "State=RUNNING) started at http://localhost:12321/apexservices/"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .endsWith("(ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:12321/apexservices/, TTL=-1sec],"
- + " State=STOPPED) shut down "));
+ assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain:"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("State=RUNNING) started"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("localhost:12321"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").endsWith(" State=STOPPED) shut down "));
}
/**
@@ -226,8 +208,7 @@ public class ApexEditorStartupTest {
final String[] args = new String[] { "-p 12321" };
assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class)
- .hasMessageContaining("Apex Editor REST endpoint (ApexEditorMain: Config=[null], State=STOPPED)"
- + " parameter error, error parsing argument \"port\" :For input string: \" 12321\"");
+ .hasMessageContaining("parameter error, error parsing argument \"port\" :For input string: \" 12321\"");
}
/**
@@ -241,9 +222,7 @@ public class ApexEditorStartupTest {
final String[] args = new String[] { "-p0" };
assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class)
- .hasMessageContaining("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:0/apexservices/, TTL=-1sec], "
- + "State=STOPPED) parameters invalid, port must be between 1024 and 65535");
+ .hasMessageContaining("parameters invalid, port must be between 1024 and 65535");
}
/**
@@ -257,9 +236,7 @@ public class ApexEditorStartupTest {
final String[] args = new String[] { "-p1023" };
assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class)
- .hasMessageContaining("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:1023/apexservices/, TTL=-1sec], "
- + "State=STOPPED) parameters invalid, port must be between 1024 and 65535");
+ .hasMessageContaining("parameters invalid, port must be between 1024 and 65535");
}
/**
@@ -273,9 +250,7 @@ public class ApexEditorStartupTest {
final String[] args = new String[] { "-p65536" };
assertThatThrownBy(() -> runEditor(args)).isInstanceOf(ApexEditorParameterException.class)
- .hasMessageContaining("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:65536/apexservices/, TTL=-1sec], "
- + "State=STOPPED) parameters invalid, port must be between 1024 and 65535");
+ .hasMessageContaining("parameters invalid, port must be between 1024 and 65535");
}
/**
@@ -290,17 +265,10 @@ public class ApexEditorStartupTest {
final String outString = runEditor(args);
- assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=10sec], "
- + "State=READY) starting at http://localhost:18989/apexservices/"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .contains("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=10sec], State=RUNNING)"
- + " started"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .endsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=10sec], State=STOPPED)"
- + " shut down "));
+ assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain:"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("State=RUNNING) started"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("timeToLive=10"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").endsWith(" State=STOPPED) shut down "));
}
/**
@@ -315,17 +283,10 @@ public class ApexEditorStartupTest {
final String outString = runEditor(args);
- assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=10sec], "
- + "State=READY) starting at http://localhost:18989/apexservices/"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .contains("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=10sec], State=RUNNING)"
- + " started"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .endsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=10sec], State=STOPPED)"
- + " shut down "));
+ assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain:"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("State=RUNNING) started"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("timeToLive=10"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").endsWith(" State=STOPPED) shut down "));
}
/**
@@ -340,17 +301,10 @@ public class ApexEditorStartupTest {
final String outString = runEditor(args);
- assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:12321/apexservices/, TTL=10sec], "
- + "State=READY) starting at http://localhost:12321/apexservices/"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .contains("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:12321/apexservices/, TTL=10sec], State=RUNNING)"
- + " started"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .endsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://localhost:12321/apexservices/, TTL=10sec], State=STOPPED)"
- + " shut down "));
+ assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain:"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("State=RUNNING) started"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("timeToLive=10"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").endsWith(" State=STOPPED) shut down "));
}
/**
@@ -365,17 +319,10 @@ public class ApexEditorStartupTest {
final String outString = runEditor(args);
- assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://127.0.0.1:12321/apexservices/, TTL=10sec], "
- + "State=READY) starting at http://127.0.0.1:12321/apexservices/"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .contains("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://127.0.0.1:12321/apexservices/, TTL=10sec], State=RUNNING)"
- + " started"));
- assertTrue(outString.replaceAll("[\\r?\\n]+", " ")
- .endsWith("Apex Editor REST endpoint (ApexEditorMain: "
- + "Config=[ApexEditorParameters: URI=http://127.0.0.1:12321/apexservices/, TTL=10sec], State=STOPPED)"
- + " shut down "));
+ assertTrue(outString.startsWith("Apex Editor REST endpoint (ApexEditorMain:"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("State=RUNNING) started"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").contains("timeToLive=10"));
+ assertTrue(outString.replaceAll("[\\r?\\n]+", " ").endsWith(" State=STOPPED) shut down "));
}
/**
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/RestInterfaceTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/RestInterfaceTest.java
index 60a2012..cf1c4fa 100644
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/RestInterfaceTest.java
+++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/RestInterfaceTest.java
@@ -42,10 +42,8 @@ import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
-import org.onap.policy.apex.model.basicmodel.handling.ApexModelStringWriter;
import org.onap.policy.apex.model.modelapi.ApexApiResult;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
-import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
import org.onap.policy.common.parameters.ParameterService;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.onap.policy.gui.editors.apex.rest.ApexEditorMain.EditorState;
@@ -56,7 +54,7 @@ import org.onap.policy.gui.editors.apex.rest.ApexEditorMain.EditorState;
public class RestInterfaceTest {
// CHECKSTYLE:OFF: MagicNumber
- private static final String TESTMODELFILE = "models/PolicyModel.json";
+ private static final String TESTMODELFILE = "models/PolicyModel.yaml";
private static final String TESTPORTNUM = "18989";
private static final long MAX_WAIT = 15000; // 15 sec
private static final InputStream SYSIN = System.in;
@@ -65,8 +63,7 @@ public class RestInterfaceTest {
private static ApexEditorMain editorMain;
private static WebTarget target;
- private static AxPolicyModel localmodel = null;
- private static String localmodelString = null;
+ private static String localModelString = null;
/**
* Sets up the tests.
@@ -103,10 +100,7 @@ public class RestInterfaceTest {
target = c.target(new ApexEditorParameters().getBaseUri());
// load a test model locally
- localmodel = new ApexModelReader<>(AxPolicyModel.class, false)
- .read(ResourceUtils.getResourceAsStream(TESTMODELFILE));
- localmodelString = new ApexModelStringWriter<AxPolicyModel>(false).writeJsonString(localmodel,
- AxPolicyModel.class);
+ localModelString = ResourceUtils.getResourceAsString(TESTMODELFILE);
// initialize a session ID
createNewSession();
@@ -159,8 +153,8 @@ public class RestInterfaceTest {
}
/**
- * Create a new session, Upload a test policy model, then get a policy, parse
- * it, and compare it to the same policy in the original model.
+ * Create a new session, Upload a test policy model, then get a policy, parse it, and compare it to the same policy
+ * in the original model.
*
* @throws ApexException if there is an Apex Error
* @throws JAXBException if there is a JaxB Error
@@ -170,7 +164,7 @@ public class RestInterfaceTest {
final int sessionId = createNewSession();
- uploadPolicy(sessionId, localmodelString);
+ uploadPolicy(sessionId, localModelString);
final ApexApiResult responseMsg = target.path("editor/" + sessionId + "/Policy/Get")
.queryParam("name", "policy").queryParam("version", "0.0.1").request().get(ApexApiResult.class);
@@ -180,29 +174,10 @@ public class RestInterfaceTest {
// object. Lets parse it
final String returnedPolicyAsString = responseMsg.getMessages().get(0);
ApexModelReader<AxPolicy> apexPolicyReader = new ApexModelReader<>(AxPolicy.class, false);
- final AxPolicy returnedpolicy = apexPolicyReader.read(returnedPolicyAsString);
- // AxPolicy returnedpolicy =
- // RestUtils.getConceptFromJSON(returnedPolicyAsString, AxPolicy.class);
-
- // Extract the local copy of that policy from the local Apex Policy Model
- final AxPolicy localpolicy = localmodel.getPolicies().get("policy", "0.0.1");
-
- // Write that local copy of the AxPolicy object to a Json String, ten parse it
- // again
- final ApexModelStringWriter<AxPolicy> apexModelWriter = new ApexModelStringWriter<>(false);
- final String localPolicyString = apexModelWriter.writeJsonString(localpolicy, AxPolicy.class);
- apexPolicyReader = new ApexModelReader<>(AxPolicy.class, false);
- final AxPolicy localpolicyReparsed = apexPolicyReader.read(localPolicyString);
- // AxPolicy localpolicy_reparsed =
- // RestUtils.getConceptFromJSON(returnedPolicyAsString, AxPolicy.class);
-
- assertNotNull(returnedpolicy);
- assertNotNull(localpolicy);
- assertNotNull(localpolicyReparsed);
- assertEquals(localpolicy, localpolicyReparsed);
- assertEquals(localpolicy, returnedpolicy);
- }
-
- // TODO Full unit testing of REST interface
+ final AxPolicy returnedPolicy = apexPolicyReader.read(returnedPolicyAsString);
+ assertNotNull(returnedPolicy);
+ assertEquals("state", returnedPolicy.getFirstState());
+ assertEquals(1, returnedPolicy.getStateMap().size());
+ }
}
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParametersTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParametersTest.java
deleted file mode 100644
index 3f743a7..0000000
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/UploadPluginConfigParametersTest.java
+++ /dev/null
@@ -1,85 +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 static org.assertj.core.api.Assertions.assertThat;
-
-import java.util.Optional;
-import org.junit.Test;
-import org.onap.policy.gui.editors.apex.rest.handling.config.PolicyUploadPluginConfigKey;
-
-public class UploadPluginConfigParametersTest {
-
- @Test
- public void setupPropertiesTest() {
- final String expectedUrl = "aUrl";
- final boolean expectedEnabled = true;
- System.setProperty(PolicyUploadPluginConfigKey.URL.getKey(), expectedUrl);
- System.setProperty(PolicyUploadPluginConfigKey.ENABLE.getKey(), String.valueOf(expectedEnabled));
- final UploadPluginConfigParameters uploadPluginConfigParameters = new UploadPluginConfigParameters();
- final String url = uploadPluginConfigParameters.getUrl();
- final Boolean isEnabled = uploadPluginConfigParameters.isEnabled();
- assertThat(url).isEqualTo(expectedUrl);
- assertThat(isEnabled).isEqualTo(expectedEnabled);
- }
-
- @Test
- public void testGetValue() {
- final String expectedUrl = "aUrl";
- final boolean expectedEnabled = true;
- System.setProperty(PolicyUploadPluginConfigKey.URL.getKey(), expectedUrl);
- System.setProperty(PolicyUploadPluginConfigKey.ENABLE.getKey(), String.valueOf(expectedEnabled));
- UploadPluginConfigParameters uploadPluginConfigParameters = new UploadPluginConfigParameters();
- Optional<String> actualUrl = uploadPluginConfigParameters.getValue(PolicyUploadPluginConfigKey.URL);
- assertThat(actualUrl).isPresent().contains(expectedUrl);
- Optional<Boolean> actualEnabled = uploadPluginConfigParameters.getValue(PolicyUploadPluginConfigKey.ENABLE);
- assertThat(actualEnabled).isPresent().contains(expectedEnabled);
-
- System.clearProperty(PolicyUploadPluginConfigKey.URL.getKey());
- uploadPluginConfigParameters = new UploadPluginConfigParameters();
- actualUrl = uploadPluginConfigParameters.getValue(PolicyUploadPluginConfigKey.URL);
- assertThat(actualUrl).isNotPresent();
-
- System.clearProperty(PolicyUploadPluginConfigKey.ENABLE.getKey());
- uploadPluginConfigParameters = new UploadPluginConfigParameters();
- actualEnabled = uploadPluginConfigParameters.getValue(PolicyUploadPluginConfigKey.ENABLE);
- assertThat(actualEnabled).isPresent();
- assertThat(actualEnabled.get()).isFalse();
- }
-
- @Test
- public void testValidate() {
- final String expectedUrl = "aUrl";
- final boolean expectedEnabled = true;
- System.setProperty(PolicyUploadPluginConfigKey.URL.getKey(), expectedUrl);
- System.setProperty(PolicyUploadPluginConfigKey.ENABLE.getKey(), String.valueOf(expectedEnabled));
- UploadPluginConfigParameters uploadPluginConfigParameters = new UploadPluginConfigParameters();
- assertThat(uploadPluginConfigParameters.isValid()).isTrue();
-
- System.clearProperty(PolicyUploadPluginConfigKey.URL.getKey());
- uploadPluginConfigParameters = new UploadPluginConfigParameters();
- assertThat(uploadPluginConfigParameters.isValid()).isFalse();
-
- System.clearProperty(PolicyUploadPluginConfigKey.ENABLE.getKey());
- uploadPluginConfigParameters = new UploadPluginConfigParameters();
- assertThat(uploadPluginConfigParameters.isValid()).isTrue();
- }
-} \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResourceTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResourceTest.java
index 9b0ce32..6e9dca4 100644
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResourceTest.java
+++ b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ApexEditorRestResourceTest.java
@@ -398,7 +398,7 @@ public class ApexEditorRestResourceTest extends JerseyTest {
.queryParam("version", (String) null).request().get(ApexApiResult.class);
assertEquals(ApexApiResult.Result.FAILED, result.getResult());
- final String modelString = TextFileUtils.getTextFileAsString("src/test/resources/models/PolicyModel.json");
+ final String modelString = TextFileUtils.getTextFileAsString("src/test/resources/models/PolicyModel.yaml");
Entity<String> modelEntity = Entity.entity("Somewhere over the rainbow", MediaType.APPLICATION_JSON);
result = target("editor/" + -12345 + "/Model/Load").request().put(modelEntity, ApexApiResult.class);
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResourceTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResourceTest.java
deleted file mode 100644
index 3820240..0000000
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/ConfigurationRestResourceTest.java
+++ /dev/null
@@ -1,64 +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 static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-import org.glassfish.jersey.server.ResourceConfig;
-import org.glassfish.jersey.test.JerseyTest;
-import org.junit.Test;
-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.gui.editors.apex.rest.UploadPluginConfigParameters;
-import org.onap.policy.gui.editors.apex.rest.handling.config.PolicyUploadPluginConfigKey;
-
-public class ConfigurationRestResourceTest extends JerseyTest {
-
- private String anUrl;
- private Boolean isEnabled;
-
- @Override
- protected Application configure() {
- anUrl = "url";
- isEnabled = true;
- System.setProperty(PolicyUploadPluginConfigKey.URL.getKey(), anUrl);
- System.setProperty(PolicyUploadPluginConfigKey.ENABLE.getKey(), String.valueOf(isEnabled));
- final UploadPluginConfigParameters uploadPluginConfigParameters = new UploadPluginConfigParameters();
- ParameterService.clear();
- ParameterService.register(uploadPluginConfigParameters);
- return new ResourceConfig(ConfigurationRestResource.class);
- }
-
- @Test
- public void testShowSuccess() {
- final Response response = target("/editor/config").request().get();
- assertEquals(Status.OK.getStatusCode(), response.getStatus());
- final ApexApiResult apexApiResult = response.readEntity(ApexApiResult.class);
- assertEquals(Result.SUCCESS, apexApiResult.getResult());
- final String message = apexApiResult.getMessage();
- assertThat(message).contains(String.format("\"%s\":\"%s\"", PolicyUploadPluginConfigKey.URL.getKey(), anUrl))
- .contains(String.format("\"%s\":%s", PolicyUploadPluginConfigKey.ENABLE.getKey(), isEnabled));
- }
-} \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessorTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessorTest.java
deleted file mode 100644
index 0842b1b..0000000
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ApexConfigProcessorTest.java
+++ /dev/null
@@ -1,111 +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.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.contains;
-import static org.hamcrest.Matchers.is;
-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 java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import org.junit.Test;
-import org.onap.policy.common.utils.coder.StandardCoder;
-
-public class ApexConfigProcessorTest {
-
- private final ApexConfigProcessor apexConfigProcessor = new ApexConfigProcessor(new StandardCoder());
- private final Path testResourcesPath = Paths.get("src", "test", "resources", "processor");
-
- @Test
- public void testProcessSuccess() throws IOException {
- final String fileName = "ApexConfig.json";
- final ProcessedTemplate process;
- try (final FileInputStream fileInputStream = readFileAsStream(fileName)) {
- process = apexConfigProcessor.process(fileInputStream);
- }
- assertThat("Template should be valid", process.isValid(), is(true));
- final String expectedContent = readFileAsString(fileName);
- assertThat("Content should be the same", process.getContent(), is(expectedContent));
- }
-
- @Test
- public void testProcessMissingPoliciesEntry() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream(
- "ApexConfig-missing-engineServiceParameters.json")) {
- processedTemplate = apexConfigProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false,
- List.of(MISSING_ENTRY.getMessage(ENGINE_SERVICE_PARAMETERS.getKey())));
- }
-
- @Test
- public void testProcessInvalidToscaTemplate() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ApexConfig-invalid.jsonbad")) {
- processedTemplate = apexConfigProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false, List.of(INVALID_APEX_CONFIG.getMessage()));
- }
-
- @Test
- public void testProcessInvalidEngineServiceParameters() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream(
- "ApexConfig-invalid-engineServiceParameters.json")) {
- processedTemplate = apexConfigProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false,
- List.of(INVALID_ENTRY.getMessage(ENGINE_SERVICE_PARAMETERS.getKey())));
- }
-
- private void assertProcessedTemplate(final ProcessedTemplate process, boolean isValid,
- final List<String> expectedErrorList) {
-
- assertThat("Template should be valid", process.isValid(), is(isValid));
- if (isValid || expectedErrorList == null) {
- return;
- }
- assertThat("Should contains the expected quantity of errors", process.getErrorSet().size(),
- is(expectedErrorList.size()));
- expectedErrorList.forEach(errorMsg -> assertThat("Should contains a specific error message",
- process.getErrorSet(), contains(errorMsg)));
- }
-
- private FileInputStream readFileAsStream(final String fileName) throws FileNotFoundException {
- final Path path = Paths.get(testResourcesPath.toString(), fileName);
- return new FileInputStream(path.toFile());
- }
-
- private String readFileAsString(final String fileName) throws IOException {
- final Path path = Paths.get(testResourcesPath.toString(), fileName);
- return Files.readString(path);
- }
-
-} \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverterTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverterTest.java
deleted file mode 100644
index ecf896e..0000000
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyToscaConverterTest.java
+++ /dev/null
@@ -1,187 +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.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doThrow;
-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 static org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.PolicyToscaConverter.ToscaKey.TOSCA_DEFINITIONS_VERSION;
-
-import com.google.gson.JsonObject;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.InjectMocks;
-import org.mockito.MockitoAnnotations;
-import org.mockito.Spy;
-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.coder.YamlJsonTranslator;
-import org.onap.policy.gui.editors.apex.rest.handling.converter.tosca.exception.PolicyToscaConverterException;
-
-public class PolicyToscaConverterTest {
-
- @Spy
- private final StandardCoder standardCoder = new StandardCoder();
- @Spy
- private final YamlJsonTranslator yamlJsonTranslator = new YamlJsonTranslator();
- @InjectMocks
- private PolicyToscaConverter policyToscaConverter;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void testConvertSuccess() throws IOException, PolicyToscaConverterException, CoderException {
- final String apexConfig = readResourceFileToString(Paths.get("converter", "ApexConfig.json"));
- final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json"));
- final String toscaTemplate = readResourceFileToString(Paths.get("converter", "ToscaTemplate.json"));
- final Optional<String> convert = policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate);
- assertTrue(convert.isPresent());
- final String convertedYaml = convert.get();
- final StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
- @SuppressWarnings("unchecked") final Map<String, Object> yamlAsMap =
- standardYamlCoder.decode(convertedYaml, Map.class);
- assertThat(yamlAsMap).containsKeys(TOSCA_DEFINITIONS_VERSION.getKey(), TOPOLOGY_TEMPLATE.getKey());
- @SuppressWarnings("unchecked") final Map<String, Object> topology_template =
- (Map<String, Object>) yamlAsMap.get(TOPOLOGY_TEMPLATE.getKey());
- assertThat(topology_template).containsKey(POLICIES.getKey());
- @SuppressWarnings("unchecked") final List<Object> policies =
- (List<Object>) topology_template.get(POLICIES.getKey());
- assertEquals(1, policies.size());
- @SuppressWarnings("unchecked") final Map<String, Object> firstPolicyMap = (Map<String, Object>) policies.get(0);
- assertEquals(1, firstPolicyMap.keySet().size());
- @SuppressWarnings("unchecked") final Map<String, Object> firstPolicy =
- (Map<String, Object>) firstPolicyMap.get(firstPolicyMap.keySet().iterator().next());
- assertThat(firstPolicy).containsKey(PROPERTIES.getKey());
- @SuppressWarnings("unchecked") final Map<String, Object> propertiesMap =
- (Map<String, Object>) firstPolicy.get(PROPERTIES.getKey());
- assertThat(propertiesMap).containsKey(ENGINE_SERVICE_PARAMETERS.getKey());
- @SuppressWarnings("unchecked") final Map<String, Object> engineServiceParametersProperty =
- (Map<String, Object>) propertiesMap.get(ENGINE_SERVICE_PARAMETERS.getKey());
- assertThat(engineServiceParametersProperty).containsKey(POLICY_TYPE_IMPL.getKey());
- }
-
- @Test
- public void testConvertInvalidJsonDecode() throws CoderException {
- final String invalidJson = "this is an invalid JSON";
- doThrow(CoderException.class).when(standardCoder).decode(eq(invalidJson), eq(JsonObject.class));
-
- final String expectedMsg = String.format("Could not convert JSON string to JSON:\n%s", invalidJson);
- assertThatThrownBy(() -> policyToscaConverter.convert(invalidJson, invalidJson, invalidJson))
- .isInstanceOf(PolicyToscaConverterException.class)
- .hasMessage(expectedMsg);
- }
-
- @Test
- public void testConvertInvalidJsonEncodeToString() throws IOException {
- final String apexConfig = readResourceFileToString(Paths.get("converter", "ApexConfig.json"));
- final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json"));
- final String toscaTemplate = readResourceFileToString(Paths.get("converter", "ToscaTemplate.json"));
-
- doThrow(RuntimeException.class).when(yamlJsonTranslator).toYaml(any(JsonObject.class));
-
- assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate))
- .isInstanceOf(PolicyToscaConverterException.class)
- .hasMessageContaining("Could not convert JSON Object to YAML:");
- }
-
- @Test
- public void testCouldNotReadFirstPolicy() throws IOException {
- final String apexConfig = readResourceFileToString(Paths.get("converter", "ApexConfig.json"));
- final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json"));
- final String toscaTemplate1 =
- readResourceFileToString(Paths.get("processor", "ToscaTemplate-missing-policies.json"));
- final String expectedError =
- String.format("Could not read the first policy in the '%s' entry under '%s'",
- POLICIES.getKey(), TOPOLOGY_TEMPLATE.getKey());
-
- assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate1))
- .isInstanceOf(PolicyToscaConverterException.class)
- .hasMessage(expectedError);
- final String toscaTemplate2 =
- readResourceFileToString(Paths.get("processor", "ToscaTemplate-missing-policy.json"));
-
- assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate2))
- .isInstanceOf(PolicyToscaConverterException.class)
- .hasMessage(expectedError);
- }
-
- @Test
- public void testCouldNotReadPolicyProperties() throws IOException {
- final String apexConfig = readResourceFileToString(Paths.get("converter", "ApexConfig.json"));
- final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json"));
- final String toscaTemplate =
- readResourceFileToString(Paths.get("processor", "ToscaTemplate-missing-properties.json"));
- assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate))
- .isInstanceOf(PolicyToscaConverterException.class)
- .hasMessage(String.format("Could not read the policy '%s' entry", PROPERTIES.getKey()));
- }
-
- @Test
- public void testCouldNotReadEngineServiceParameters() throws IOException {
- final String apexConfig =
- readResourceFileToString(Paths.get("converter", "ApexConfig-engineServiceParameters-notAnObject.json"));
- final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json"));
- final String toscaTemplate =
- readResourceFileToString(Paths.get("converter", "ToscaTemplate.json"));
- assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate))
- .isInstanceOf(PolicyToscaConverterException.class)
- .hasMessage(
- String.format("Could not read the '%s' in the Apex Config", ENGINE_SERVICE_PARAMETERS.getKey()));
- }
-
- @Test
- public void testCouldNotReadTopologyTemplate() throws IOException {
- final String apexConfig = readResourceFileToString(Paths.get("converter", "ApexConfig.json"));
- final String apexPolicy = readResourceFileToString(Paths.get("converter", "APEXgRPCPolicy.json"));
- final String toscaTemplate =
- readResourceFileToString(Paths.get("processor", "ToscaTemplate-missing-topology-template.json"));
- assertThatThrownBy(() -> policyToscaConverter.convert(apexPolicy, apexConfig, toscaTemplate))
- .isInstanceOf(PolicyToscaConverterException.class)
- .hasMessage(
- String.format("Could not read the '%s' entry in the Tosca Template", TOPOLOGY_TEMPLATE.getKey()));
- }
-
- private String readResourceFileToString(final Path filePathFromResources) throws IOException {
- final Path resourceDirectory = Paths.get("src", "test", "resources");
- final Path converter = Paths.get(resourceDirectory.toString(), filePathFromResources.toString());
- return Files.readString(converter);
- }
-
-} \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyUploadHandlerTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyUploadHandlerTest.java
deleted file mode 100644
index 6ec5eef..0000000
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/PolicyUploadHandlerTest.java
+++ /dev/null
@@ -1,201 +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.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Optional;
-import javax.ws.rs.core.Response;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
-import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo;
-import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation;
-import org.onap.policy.apex.model.modelapi.ApexApiResult;
-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.PolicyUploadHandler;
-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;
-
-public class PolicyUploadHandlerTest {
-
- private static final String USER_ID = "cs0008";
- @Mock
- private PolicyToscaConverter policyToscaConverter;
- @Mock
- private ToscaTemplateProcessor toscaTemplateProcessor;
- @Mock
- private ApexConfigProcessor apexConfigProcessor;
- @Mock
- private UploadPluginClient uploadPluginClient;
- @Mock
- private UploadPluginConfigParameters config;
-
- @InjectMocks
- private PolicyUploadHandler policyUploadHandler;
-
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
- when(config.isEnabled()).thenReturn(true);
- }
-
- @Test
- public void doUploadResponseSuccessAndFail() throws PolicyToscaConverterException, IOException {
- final ApexModel apexModel = mockApexModel();
- final ProcessedTemplate processedToscaTemplate = new ProcessedTemplate();
- processedToscaTemplate.setContent("tosca");
- final ProcessedTemplate processedApexConfig = new ProcessedTemplate();
- processedApexConfig.setContent("apexConfig");
- when(toscaTemplateProcessor.process(any(InputStream.class))).thenReturn(processedToscaTemplate);
- when(apexConfigProcessor.process(any(InputStream.class))).thenReturn(processedApexConfig);
- when(policyToscaConverter.convert(eq("policy\n"), eq("apexConfig"), eq("tosca")))
- .thenReturn(Optional.of("test"));
- when(uploadPluginClient.upload(any(UploadPolicyRequestDto.class)))
- .thenReturn(Response.ok().status(201).build());
-
- ApexApiResult apexApiResult = policyUploadHandler
- .doUpload(apexModel, mock(InputStream.class), mock(InputStream.class), USER_ID);
-
- assertThat("Response should be ok", apexApiResult.isOk(), is(true));
- String expectedSuccessMsg =
- String.format("Policy '%s' uploaded successfully", apexModel.getPolicyModel().getId());
- assertThat("Response message should be as expected",
- apexApiResult.getMessage(), is(expectedSuccessMsg + "\n"));
-
- when(uploadPluginClient.upload(any(UploadPolicyRequestDto.class)))
- .thenReturn(Response.serverError().build());
-
- apexApiResult = policyUploadHandler
- .doUpload(apexModel, mock(InputStream.class), mock(InputStream.class), USER_ID);
-
- assertThat("Response should not be ok", apexApiResult.isNok(), is(true));
- expectedSuccessMsg =
- String.format("An error has occurred while uploading the Policy '%s'. Status was %s",
- apexModel.getPolicyModel().getId(), 500);
- assertThat("Response message should be as expected",
- apexApiResult.getMessage(), is(expectedSuccessMsg + "\n"));
- }
-
- @Test
- public void doUploadPluginDisabled() throws IOException {
- when(config.isEnabled()).thenReturn(false);
-
- final ProcessedTemplate processedToscaTemplate = new ProcessedTemplate();
- final ProcessedTemplate processedApexConfig = new ProcessedTemplate();
- when(toscaTemplateProcessor.process(any(InputStream.class))).thenReturn(processedToscaTemplate);
- when(apexConfigProcessor.process(any(InputStream.class))).thenReturn(processedApexConfig);
- final ApexApiResult apexApiResult = policyUploadHandler
- .doUpload(mock(ApexModel.class), mock(InputStream.class), mock(InputStream.class), USER_ID);
-
- assertThat("Response should not be ok", apexApiResult.isNok(), is(true));
- assertThat("Response message should be as expected",
- apexApiResult.getMessage(), is("Upload feature is disabled\n"));
- }
-
- @Test
- public void doUploadInvalidToscaTemplate() throws IOException {
- when(config.isEnabled()).thenReturn(false);
-
- final ProcessedTemplate processedToscaTemplate = new ProcessedTemplate();
- final String errorMsg = "an error";
- processedToscaTemplate.addToErrors(Collections.singleton(errorMsg));
- when(toscaTemplateProcessor.process(any(InputStream.class))).thenReturn(processedToscaTemplate);
- final ApexApiResult apexApiResult = policyUploadHandler
- .doUpload(mock(ApexModel.class), mock(InputStream.class), mock(InputStream.class), USER_ID);
-
- assertThat("Response should not be ok", apexApiResult.isNok(), is(true));
- assertThat("Response message should be as expected",
- apexApiResult.getMessage(), is(errorMsg + "\n"));
- }
-
- @Test
- public void doUploadInvalidApexConfigTemplate() throws IOException {
- when(config.isEnabled()).thenReturn(false);
-
- when(toscaTemplateProcessor.process(any(InputStream.class))).thenReturn(new ProcessedTemplate());
- final ProcessedTemplate processedApexConfig = new ProcessedTemplate();
- final String errorMsg = "an error";
- processedApexConfig.addToErrors(Collections.singleton(errorMsg));
- when(apexConfigProcessor.process(any(InputStream.class))).thenReturn(processedApexConfig);
- final ApexApiResult apexApiResult = policyUploadHandler
- .doUpload(mock(ApexModel.class), mock(InputStream.class), mock(InputStream.class), USER_ID);
-
- assertThat("Response should not be ok", apexApiResult.isNok(), is(true));
- assertThat("Response message should be as expected",
- apexApiResult.getMessage(), is(errorMsg + "\n"));
- }
-
- @Test
- public void doUploadConversionFailed() throws PolicyToscaConverterException, IOException {
- final ApexModel apexModel = mockApexModel();
- final ProcessedTemplate processedToscaTemplate = new ProcessedTemplate();
- processedToscaTemplate.setContent("tosca");
- final ProcessedTemplate processedApexConfig = new ProcessedTemplate();
- processedApexConfig.setContent("apexConfig");
- when(toscaTemplateProcessor.process(any(InputStream.class))).thenReturn(processedToscaTemplate);
- when(apexConfigProcessor.process(any(InputStream.class))).thenReturn(processedApexConfig);
- when(policyToscaConverter.convert(eq("policy\n"), eq("apexConfig"), eq("tosca")))
- .thenThrow(PolicyToscaConverterException.class);
- when(uploadPluginClient.upload(any(UploadPolicyRequestDto.class)))
- .thenReturn(Response.ok().status(201).build());
-
- final ApexApiResult apexApiResult = policyUploadHandler
- .doUpload(apexModel, mock(InputStream.class), mock(InputStream.class), USER_ID);
-
- assertThat("Response should not be ok", apexApiResult.isNok(), is(true));
- final String expectedErrorMsg = String
- .format("An error has occurred while uploading the converting the Policy '%s' to YAML.",
- apexModel.getPolicyModel().getId());
- assertThat("Response message should be as expected",
- apexApiResult.getMessage(), is(expectedErrorMsg + "\n"));
- }
-
- private ApexModel mockApexModel() {
- final ApexModel apexModel = mock(ApexModel.class);
- final ApexApiResult listModelApexApiResult = new ApexApiResult();
- listModelApexApiResult.addMessage("policy");
- when(apexModel.listModel()).thenReturn(listModelApexApiResult);
- final AxPolicyModel axPolicyModel = new AxPolicyModel();
- final AxArtifactKey axArtifactKey = new AxArtifactKey("policyKey", "1.0.0");
- final Map<AxArtifactKey, AxKeyInfo> keyInfoMap = new HashMap<>();
- keyInfoMap.put(axArtifactKey, new AxKeyInfo(axArtifactKey));
- final AxKeyInformation axKeyInformation = new AxKeyInformation(axArtifactKey, keyInfoMap);
- axPolicyModel.setKeyInformation(axKeyInformation);
- when(apexModel.getPolicyModel()).thenReturn(axPolicyModel);
- return apexModel;
- }
-}
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessorTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessorTest.java
deleted file mode 100644
index 7166621..0000000
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/converter/tosca/ToscaTemplateProcessorTest.java
+++ /dev/null
@@ -1,204 +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.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.contains;
-import static org.hamcrest.Matchers.is;
-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 java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import org.junit.Test;
-import org.onap.policy.common.utils.coder.StandardCoder;
-
-public class ToscaTemplateProcessorTest {
-
- private final ToscaTemplateProcessor toscaTemplateProcessor = new ToscaTemplateProcessor(new StandardCoder());
- private final Path testResourcesPath = Paths.get("src", "test", "resources", "processor");
-
- @Test
- public void testProcessSuccess() throws IOException {
- final String fileName = "ToscaTemplate.json";
- final ProcessedTemplate process;
- try (final FileInputStream fileInputStream = readFileAsStream(fileName)) {
- process = toscaTemplateProcessor.process(fileInputStream);
- }
- assertThat("Template should be valid", process.isValid(), is(true));
- final String expectedContent = readFileAsString(fileName);
- assertThat("Content should be the same", process.getContent(), is(expectedContent));
- }
-
- @Test
- public void testProcessMissingPoliciesEntry() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-missing-policies.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false, List.of(MISSING_ENTRY.getMessage(POLICIES.getKey())));
- }
-
- @Test
- public void testProcessMissingTopologyTemplate() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-missing-topology-template.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false,
- List.of(MISSING_ENTRY.getMessage(TOPOLOGY_TEMPLATE.getKey())));
- }
-
- @Test
- public void testProcessMissingPolicy() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-missing-policy.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false, List.of(MISSING_POLICY.getMessage()));
- }
-
- @Test
- public void testProcessMissingToscaDefinitionsVersion() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream(
- "ToscaTemplate-missing-tosca-definitions-version.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false,
- List.of(MISSING_ENTRY.getMessage(TOSCA_DEFINITIONS_VERSION.getKey())));
- }
-
- @Test
- public void testProcessMissingProperties() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-missing-properties.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false, List.of(MISSING_ENTRY.getMessage(PROPERTIES.getKey())));
- }
-
- @Test
- public void testProcessMoreThanOnePolicy() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-more-than-one-policy.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false, List.of(ONLY_ONE_POLICY_ALLOWED.getMessage()));
- }
-
- @Test
- public void testProcessInvalidToscaTemplate() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-invalid.jsonbad")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false, List.of(INVALID_TOSCA_TEMPLATE.getMessage()));
- }
-
- @Test
- public void testProcessInvalidEntryToscaDefinitionsVersion() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-invalid-toscaDefinitions.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false,
- List.of(INVALID_ENTRY.getMessage(TOSCA_DEFINITIONS_VERSION.getKey())));
- }
-
- @Test
- public void testProcessInvalidEntryTopologyTemplate() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream(
- "ToscaTemplate-invalidEntry-topologyTemplate.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false,
- List.of(INVALID_ENTRY.getMessage(TOPOLOGY_TEMPLATE.getKey())));
- }
-
- @Test
- public void testProcessInvalidEntryPolicies() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-invalidEntry-policies.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false, List.of(INVALID_ENTRY.getMessage(POLICIES.getKey())));
- }
-
- @Test
- public void testProcessInvalidPolicy() throws IOException {
- ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-invalidPolicy1.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false, List.of(INVALID_POLICY.getMessage()));
-
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-invalidPolicy2.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false, List.of(INVALID_POLICY.getMessage()));
- }
-
- @Test
- public void testProcessInvalidEntryProperties() throws IOException {
- final ProcessedTemplate processedTemplate;
- try (final FileInputStream fileInputStream = readFileAsStream("ToscaTemplate-invalidEntry-properties.json")) {
- processedTemplate = toscaTemplateProcessor.process(fileInputStream);
- }
- assertProcessedTemplate(processedTemplate, false, List.of(INVALID_ENTRY.getMessage(PROPERTIES.getKey())));
- }
-
- private void assertProcessedTemplate(final ProcessedTemplate process, boolean isValid,
- final List<String> expectedErrorList) {
- assertThat("Template should be valid", process.isValid(), is(isValid));
- if (isValid || expectedErrorList == null) {
- return;
- }
- assertThat("Should contains the expected quantity of errors", process.getErrorSet().size(),
- is(expectedErrorList.size()));
- expectedErrorList.forEach(errorMsg -> assertThat("Should contains a specific error message",
- process.getErrorSet(), contains(errorMsg)));
- }
-
- private FileInputStream readFileAsStream(final String fileName) throws FileNotFoundException {
- final Path path = Paths.get(testResourcesPath.toString(), fileName);
- return new FileInputStream(path.toFile());
- }
-
- private String readFileAsString(final String fileName) throws IOException {
- final Path path = Paths.get(testResourcesPath.toString(), fileName);
- return Files.readString(path);
- }
-
-} \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClientTest.java b/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClientTest.java
deleted file mode 100644
index ab9445e..0000000
--- a/gui-editors/gui-editor-apex/src/test/java/org/onap/policy/gui/editors/apex/rest/handling/plugin/upload/UploadPluginClientTest.java
+++ /dev/null
@@ -1,71 +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 static org.junit.Assert.assertEquals;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.Invocation.Builder;
-import javax.ws.rs.client.WebTarget;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.onap.policy.gui.editors.apex.rest.UploadPluginConfigParameters;
-import org.onap.policy.gui.editors.apex.rest.handling.config.PolicyUploadPluginConfigKey;
-
-public class UploadPluginClientTest {
-
- private UploadPluginClient uploadPluginClient;
-
- @Mock
- private Client client;
-
- private static final String url = "aUrl";
-
- /**
- * Init the mocks and system properties.
- */
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- System.setProperty(PolicyUploadPluginConfigKey.URL.getKey(), url);
- final UploadPluginConfigParameters uploadPluginConfigParameters = new UploadPluginConfigParameters();
- uploadPluginClient = new UploadPluginClient(client, uploadPluginConfigParameters);
- }
-
- @Test
- public void upload() {
- final Builder mockBuilder = mock(Builder.class);
- final WebTarget mockWebTarget = mock(WebTarget.class);
- final Response mockResponse = mock(Response.class);
- doReturn(mockWebTarget).when(client).target(url);
- doReturn(mockBuilder).when(mockWebTarget).request(MediaType.APPLICATION_JSON);
- when(mockBuilder.post(any())).thenReturn(mockResponse);
- final Response actualResponse = uploadPluginClient.upload(new UploadPolicyRequestDto());
- assertEquals(mockResponse, actualResponse);
- }
-} \ No newline at end of file
diff --git a/gui-editors/gui-editor-apex/src/test/resources/models/PolicyModel.json b/gui-editors/gui-editor-apex/src/test/resources/models/PolicyModel.json
index 81c2226..9e3ea51 100644
--- a/gui-editors/gui-editor-apex/src/test/resources/models/PolicyModel.json
+++ b/gui-editors/gui-editor-apex/src/test/resources/models/PolicyModel.json
@@ -1,708 +1,825 @@
{
- "apexPolicyModel" : {
- "key" : {
- "name" : "PolicyModel",
- "version" : "0.0.1"
- },
- "keyInformation" : {
- "key" : {
- "name" : "KeyInfoMapKey",
- "version" : "0.0.1"
- },
- "keyInfoMap" : {
- "entry" : [ {
- "key" : {
- "name" : "ContextSchemas",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "ContextSchemas",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e000",
- "description" : "Generated description for concept referred to by key \"ContextSchemas:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "KeyInfoMapKey",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "KeyInfoMapKey",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e001",
- "description" : "Generated description for concept referred to by key \"KeyInfoMapKey:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "MapType",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "MapType",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e002",
- "description" : "Generated description for concept referred to by key \"MapType:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "PolicyModel",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "PolicyModel",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e003",
- "description" : "Generated description for concept referred to by key \"PolicyModel:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "StringType",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "StringType",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e004",
- "description" : "Generated description for concept referred to by key \"StringType:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "context",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "context",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e005",
- "description" : "Generated description for concept referred to by key \"context:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "contextAlbum0",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "contextAlbum0",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e006",
- "description" : "Generated description for concept referred to by key \"contextAlbum0:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "contextAlbum1",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "contextAlbum1",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e007",
- "description" : "Generated description for concept referred to by key \"contextAlbum1:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e008",
- "description" : "Generated description for concept referred to by key \"eventContextItem0:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e009",
- "description" : "Generated description for concept referred to by key \"eventContextItem1:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "events",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "events",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e010",
- "description" : "Generated description for concept referred to by key \"events:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "inEvent",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "inEvent",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e011",
- "description" : "Generated description for concept referred to by key \"inEvent:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "outEvent0",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "outEvent0",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e012",
- "description" : "Generated description for concept referred to by key \"outEvent0:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "outEvent1",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "outEvent1",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e013",
- "description" : "Generated description for concept referred to by key \"outEvent1:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "policies",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "policies",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e014",
- "description" : "Generated description for concept referred to by key \"policies:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "policy",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "policy",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e015",
- "description" : "Generated description for concept referred to by key \"policy:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "task",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "task",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e016",
- "description" : "Generated description for concept referred to by key \"task:0.0.1\""
- }
- }, {
- "key" : {
- "name" : "tasks",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "tasks",
- "version" : "0.0.1"
- },
- "UUID" : "0ce9168c-e6df-414f-9646-6da464b6e017",
- "description" : "Generated description for concept referred to by key \"tasks:0.0.1\""
- }
- } ]
- }
- },
- "policies" : {
- "key" : {
- "name" : "policies",
- "version" : "0.0.1"
- },
- "policyMap" : {
- "entry" : [ {
- "key" : {
- "name" : "policy",
- "version" : "0.0.1"
- },
- "value" : {
- "policyKey" : {
- "name" : "policy",
- "version" : "0.0.1"
- },
- "template" : "FREEFORM",
- "state" : {
- "entry" : [ {
- "key" : "state",
- "value" : {
- "stateKey" : {
- "parentKeyName" : "policy",
- "parentKeyVersion" : "0.0.1",
- "parentLocalName" : "NULL",
- "localName" : "state"
- },
- "trigger" : {
- "name" : "inEvent",
- "version" : "0.0.1"
- },
- "stateOutputs" : {
- "entry" : [ {
- "key" : "stateOutput0",
- "value" : {
- "key" : {
- "parentKeyName" : "policy",
- "parentKeyVersion" : "0.0.1",
- "parentLocalName" : "state",
- "localName" : "stateOutput0"
+ "tosca_definitions_version": "tosca_simple_yaml_1_0_0",
+ "topology_template": {
+ "policies": [
+ {
+ "onap.policies.native.apex.Vcpe": {
+ "type": "onap.policies.native.Apex",
+ "type_version": "1.0.0",
+ "properties": {
+ "engineServiceParameters": {
+ "name": "MyApexEngine",
+ "version": "0.0.1",
+ "id": 45,
+ "instanceCount": 4,
+ "deploymentPort": 12561,
+ "policyModelFileName": "/home/apexuser/examples/models/ONAPvCPE/ONAPvCPEPolicyModel.json",
+ "engineParameters": {
+ "executorParameters": {
+ "JAVASCRIPT": {
+ "parameterClassName": "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters"
+ }
+ },
+ "contextParameters": {
+ "parameterClassName": "org.onap.policy.apex.context.parameters.ContextParameters",
+ "schemaParameters": {
+ "Avro": {
+ "parameterClassName": "org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters"
+ },
+ "Java": {
+ "parameterClassName": "org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters",
+ "jsonAdapters": {
+ "Instant": {
+ "adaptedClass": "java.time.Instant",
+ "adaptorClass": "org.onap.policy.controlloop.util.Serialization$GsonInstantAdapter"
+ }
+ }
+ }
+ }
+ }
+ },
+ "policy_type_impl": {
+ "apexPolicyModel": {
+ "key": {
+ "name": "PolicyModel",
+ "version": "0.0.1"
},
- "outgoingEvent" : {
- "name" : "outEvent0",
- "version" : "0.0.1"
+ "keyInformation": {
+ "key": {
+ "name": "KeyInfoMapKey",
+ "version": "0.0.1"
+ },
+ "keyInfoMap": {
+ "entry": [
+ {
+ "key": {
+ "name": "ContextSchemas",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "ContextSchemas",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e000",
+ "description": "Generated description for concept referred to by key \"ContextSchemas:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "KeyInfoMapKey",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "KeyInfoMapKey",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e001",
+ "description": "Generated description for concept referred to by key \"KeyInfoMapKey:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "MapType",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "MapType",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e002",
+ "description": "Generated description for concept referred to by key \"MapType:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "PolicyModel",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "PolicyModel",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e003",
+ "description": "Generated description for concept referred to by key \"PolicyModel:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "StringType",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "StringType",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e004",
+ "description": "Generated description for concept referred to by key \"StringType:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "context",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "context",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e005",
+ "description": "Generated description for concept referred to by key \"context:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "contextAlbum0",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "contextAlbum0",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e006",
+ "description": "Generated description for concept referred to by key \"contextAlbum0:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "contextAlbum1",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "contextAlbum1",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e007",
+ "description": "Generated description for concept referred to by key \"contextAlbum1:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e008",
+ "description": "Generated description for concept referred to by key \"eventContextItem0:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e009",
+ "description": "Generated description for concept referred to by key \"eventContextItem1:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "events",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "events",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e010",
+ "description": "Generated description for concept referred to by key \"events:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "inEvent",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "inEvent",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e011",
+ "description": "Generated description for concept referred to by key \"inEvent:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "outEvent0",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "outEvent0",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e012",
+ "description": "Generated description for concept referred to by key \"outEvent0:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "outEvent1",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "outEvent1",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e013",
+ "description": "Generated description for concept referred to by key \"outEvent1:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "policies",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "policies",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e014",
+ "description": "Generated description for concept referred to by key \"policies:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "policy",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "policy",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e015",
+ "description": "Generated description for concept referred to by key \"policy:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "task",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "task",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e016",
+ "description": "Generated description for concept referred to by key \"task:0.0.1\""
+ }
+ },
+ {
+ "key": {
+ "name": "tasks",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "tasks",
+ "version": "0.0.1"
+ },
+ "UUID": "0ce9168c-e6df-414f-9646-6da464b6e017",
+ "description": "Generated description for concept referred to by key \"tasks:0.0.1\""
+ }
+ }
+ ]
+ }
},
- "nextState" : {
- "parentKeyName" : "NULL",
- "parentKeyVersion" : "0.0.0",
- "parentLocalName" : "NULL",
- "localName" : "NULL"
- }
- }
- } ]
- },
- "contextAlbumReference" : [ {
- "name" : "contextAlbum0",
- "version" : "0.0.1"
- }, {
- "name" : "contextAlbum1",
- "version" : "0.0.1"
- } ],
- "taskSelectionLogic" : {
- "key" : "taskSelectionLogic",
- "logicFlavour" : "MVEL",
- "logic" : "Some TS logic"
- },
- "stateFinalizerLogicMap" : {
- "entry" : [ ]
- },
- "defaultTask" : {
- "name" : "task",
- "version" : "0.0.1"
- },
- "taskReferences" : {
- "entry" : [ {
- "key" : {
- "name" : "task",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "parentKeyName" : "policy",
- "parentKeyVersion" : "0.0.1",
- "parentLocalName" : "state",
- "localName" : "task"
+ "policies": {
+ "key": {
+ "name": "policies",
+ "version": "0.0.1"
+ },
+ "policyMap": {
+ "entry": [
+ {
+ "key": {
+ "name": "policy",
+ "version": "0.0.1"
+ },
+ "value": {
+ "policyKey": {
+ "name": "policy",
+ "version": "0.0.1"
+ },
+ "template": "FREEFORM",
+ "state": {
+ "entry": [
+ {
+ "key": "state",
+ "value": {
+ "stateKey": {
+ "parentKeyName": "policy",
+ "parentKeyVersion": "0.0.1",
+ "parentLocalName": "NULL",
+ "localName": "state"
+ },
+ "trigger": {
+ "name": "inEvent",
+ "version": "0.0.1"
+ },
+ "stateOutputs": {
+ "entry": [
+ {
+ "key": "stateOutput0",
+ "value": {
+ "key": {
+ "parentKeyName": "policy",
+ "parentKeyVersion": "0.0.1",
+ "parentLocalName": "state",
+ "localName": "stateOutput0"
+ },
+ "outgoingEvent": {
+ "name": "outEvent0",
+ "version": "0.0.1"
+ },
+ "nextState": {
+ "parentKeyName": "NULL",
+ "parentKeyVersion": "0.0.0",
+ "parentLocalName": "NULL",
+ "localName": "NULL"
+ }
+ }
+ }
+ ]
+ },
+ "contextAlbumReference": [
+ {
+ "name": "contextAlbum0",
+ "version": "0.0.1"
+ },
+ {
+ "name": "contextAlbum1",
+ "version": "0.0.1"
+ }
+ ],
+ "taskSelectionLogic": {
+ "key": "taskSelectionLogic",
+ "logicFlavour": "MVEL",
+ "logic": "Some TS logic"
+ },
+ "stateFinalizerLogicMap": {
+ "entry": [
+ ]
+ },
+ "defaultTask": {
+ "name": "task",
+ "version": "0.0.1"
+ },
+ "taskReferences": {
+ "entry": [
+ {
+ "key": {
+ "name": "task",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "parentKeyName": "policy",
+ "parentKeyVersion": "0.0.1",
+ "parentLocalName": "state",
+ "localName": "task"
+ },
+ "outputType": "DIRECT",
+ "output": {
+ "parentKeyName": "policy",
+ "parentKeyVersion": "0.0.1",
+ "parentLocalName": "state",
+ "localName": "stateOutput0"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "firstState": "state"
+ }
+ }
+ ]
+ }
+ },
+ "tasks": {
+ "key": {
+ "name": "tasks",
+ "version": "0.0.1"
+ },
+ "taskMap": {
+ "entry": [
+ {
+ "key": {
+ "name": "task",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "task",
+ "version": "0.0.1"
+ },
+ "inputFields": {
+ "entry": [
+ {
+ "key": "IEPAR0",
+ "value": {
+ "key": "IEPAR0",
+ "fieldSchemaKey": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ }
+ }
+ },
+ {
+ "key": "IEPAR1",
+ "value": {
+ "key": "IEPAR1",
+ "fieldSchemaKey": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ }
+ }
+ }
+ ]
+ },
+ "outputFields": {
+ "entry": [
+ {
+ "key": "OE0PAR0",
+ "value": {
+ "key": "OE0PAR0",
+ "fieldSchemaKey": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ }
+ }
+ },
+ {
+ "key": "OE0PAR1",
+ "value": {
+ "key": "OE0PAR1",
+ "fieldSchemaKey": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ }
+ }
+ },
+ {
+ "key": "OE1PAR0",
+ "value": {
+ "key": "OE1PAR0",
+ "fieldSchemaKey": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ }
+ }
+ },
+ {
+ "key": "OE1PAR1",
+ "value": {
+ "key": "OE1PAR1",
+ "fieldSchemaKey": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ }
+ }
+ }
+ ]
+ },
+ "taskParameters": {
+ "entry": [
+ {
+ "key": "taskParameter0",
+ "value": {
+ "key": {
+ "parentKeyName": "task",
+ "parentKeyVersion": "0.0.1",
+ "parentLocalName": "NULL",
+ "localName": "taskParameter0"
+ },
+ "defaultValue": "Task parameter 0 value"
+ }
+ },
+ {
+ "key": "taskParameter1",
+ "value": {
+ "key": {
+ "parentKeyName": "task",
+ "parentKeyVersion": "0.0.1",
+ "parentLocalName": "NULL",
+ "localName": "taskParameter1"
+ },
+ "defaultValue": "Task parameter 1 value"
+ }
+ }
+ ]
+ },
+ "contextAlbumReference": [
+ {
+ "name": "contextAlbum0",
+ "version": "0.0.1"
+ },
+ {
+ "name": "contextAlbum1",
+ "version": "0.0.1"
+ }
+ ],
+ "taskLogic": {
+ "key": "taskLogic",
+ "logicFlavour": "MVEL",
+ "logic": "Some task logic"
+ }
+ }
+ }
+ ]
+ }
+ },
+ "events": {
+ "key": {
+ "name": "events",
+ "version": "0.0.1"
+ },
+ "eventMap": {
+ "entry": [
+ {
+ "key": {
+ "name": "inEvent",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "inEvent",
+ "version": "0.0.1"
+ },
+ "nameSpace": "org.onap.policy.apex.model.policymodel.events",
+ "source": "Source",
+ "target": "Target",
+ "parameter": {
+ "entry": [
+ {
+ "key": "IEPAR0",
+ "value": {
+ "key": "IEPAR0",
+ "fieldSchemaKey": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ }
+ }
+ },
+ {
+ "key": "IEPAR1",
+ "value": {
+ "key": "IEPAR1",
+ "fieldSchemaKey": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ }
+ }
+ }
+ ]
+ }
+ }
+ },
+ {
+ "key": {
+ "name": "outEvent0",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "outEvent0",
+ "version": "0.0.1"
+ },
+ "nameSpace": "org.onap.policy.apex.model.policymodel.events",
+ "source": "Source",
+ "target": "Target",
+ "parameter": {
+ "entry": [
+ {
+ "key": "OE0PAR0",
+ "value": {
+ "key": "OE0PAR0",
+ "fieldSchemaKey": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ }
+ }
+ },
+ {
+ "key": "OE0PAR1",
+ "value": {
+ "key": "OE0PAR1",
+ "fieldSchemaKey": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ }
+ }
+ },
+ {
+ "key": "OE1PAR0",
+ "value": {
+ "key": "OE1PAR0",
+ "fieldSchemaKey": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ }
+ }
+ },
+ {
+ "key": "OE1PAR1",
+ "value": {
+ "key": "OE1PAR1",
+ "fieldSchemaKey": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ }
+ }
+ }
+ ]
+ }
+ }
+ },
+ {
+ "key": {
+ "name": "outEvent1",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "outEvent1",
+ "version": "0.0.1"
+ },
+ "nameSpace": "org.onap.policy.apex.model.policymodel.events",
+ "source": "Source",
+ "target": "Target",
+ "parameter": {
+ "entry": [
+ {
+ "key": "OE1PAR0",
+ "value": {
+ "key": "OE1PAR0",
+ "fieldSchemaKey": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ }
+ }
+ },
+ {
+ "key": "OE1PAR1",
+ "value": {
+ "key": "OE1PAR1",
+ "fieldSchemaKey": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ },
+ "albums": {
+ "key": {
+ "name": "context",
+ "version": "0.0.1"
+ },
+ "albums": {
+ "entry": [
+ {
+ "key": {
+ "name": "contextAlbum0",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "contextAlbum0",
+ "version": "0.0.1"
+ },
+ "scope": "APPLICATION",
+ "isWritable": true,
+ "itemSchema": {
+ "name": "MapType",
+ "version": "0.0.1"
+ }
+ }
+ },
+ {
+ "key": {
+ "name": "contextAlbum1",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "contextAlbum1",
+ "version": "0.0.1"
+ },
+ "scope": "GLOBAL",
+ "isWritable": false,
+ "itemSchema": {
+ "name": "StringType",
+ "version": "0.0.1"
+ }
+ }
+ }
+ ]
+ }
},
- "outputType" : "DIRECT",
- "output" : {
- "parentKeyName" : "policy",
- "parentKeyVersion" : "0.0.1",
- "parentLocalName" : "state",
- "localName" : "stateOutput0"
+ "schemas": {
+ "key": {
+ "name": "ContextSchemas",
+ "version": "0.0.1"
+ },
+ "schemas": {
+ "entry": [
+ {
+ "key": {
+ "name": "MapType",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "MapType",
+ "version": "0.0.1"
+ },
+ "schemaFlavour": "Java",
+ "schemaDefinition": "org.onap.policy.apex.model.policymodel.concepts.TestContextItem00A"
+ }
+ },
+ {
+ "key": {
+ "name": "StringType",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "StringType",
+ "version": "0.0.1"
+ },
+ "schemaFlavour": "Java",
+ "schemaDefinition": "org.onap.policy.apex.model.policymodel.concepts.TestContextItem000"
+ }
+ },
+ {
+ "key": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "eventContextItem0",
+ "version": "0.0.1"
+ },
+ "schemaFlavour": "Java",
+ "schemaDefinition": "java.lang.String"
+ }
+ },
+ {
+ "key": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ },
+ "value": {
+ "key": {
+ "name": "eventContextItem1",
+ "version": "0.0.1"
+ },
+ "schemaFlavour": "Java",
+ "schemaDefinition": "java.lang.Long"
+ }
+ }
+ ]
+ }
}
- }
- } ]
- }
- }
- } ]
- },
- "firstState" : "state"
- }
- } ]
- }
- },
- "tasks" : {
- "key" : {
- "name" : "tasks",
- "version" : "0.0.1"
- },
- "taskMap" : {
- "entry" : [ {
- "key" : {
- "name" : "task",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "task",
- "version" : "0.0.1"
- },
- "inputFields" : {
- "entry" : [ {
- "key" : "IEPAR0",
- "value" : {
- "key" : "IEPAR0",
- "fieldSchemaKey" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- }
- }
- }, {
- "key" : "IEPAR1",
- "value" : {
- "key" : "IEPAR1",
- "fieldSchemaKey" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- }
- }
- } ]
- },
- "outputFields" : {
- "entry" : [ {
- "key" : "OE0PAR0",
- "value" : {
- "key" : "OE0PAR0",
- "fieldSchemaKey" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- }
- }
- }, {
- "key" : "OE0PAR1",
- "value" : {
- "key" : "OE0PAR1",
- "fieldSchemaKey" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- }
- }
- }, {
- "key" : "OE1PAR0",
- "value" : {
- "key" : "OE1PAR0",
- "fieldSchemaKey" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- }
- }
- }, {
- "key" : "OE1PAR1",
- "value" : {
- "key" : "OE1PAR1",
- "fieldSchemaKey" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- }
- }
- } ]
- },
- "taskParameters" : {
- "entry" : [ {
- "key" : "taskParameter0",
- "value" : {
- "key" : {
- "parentKeyName" : "task",
- "parentKeyVersion" : "0.0.1",
- "parentLocalName" : "NULL",
- "localName" : "taskParameter0"
- },
- "defaultValue" : "Task parameter 0 value"
- }
- }, {
- "key" : "taskParameter1",
- "value" : {
- "key" : {
- "parentKeyName" : "task",
- "parentKeyVersion" : "0.0.1",
- "parentLocalName" : "NULL",
- "localName" : "taskParameter1"
- },
- "defaultValue" : "Task parameter 1 value"
- }
- } ]
- },
- "contextAlbumReference" : [ {
- "name" : "contextAlbum0",
- "version" : "0.0.1"
- }, {
- "name" : "contextAlbum1",
- "version" : "0.0.1"
- } ],
- "taskLogic" : {
- "key" : "taskLogic",
- "logicFlavour" : "MVEL",
- "logic" : "Some task logic"
- }
- }
- } ]
- }
- },
- "events" : {
- "key" : {
- "name" : "events",
- "version" : "0.0.1"
- },
- "eventMap" : {
- "entry" : [ {
- "key" : {
- "name" : "inEvent",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "inEvent",
- "version" : "0.0.1"
- },
- "nameSpace" : "org.onap.policy.apex.model.policymodel.events",
- "source" : "Source",
- "target" : "Target",
- "parameter" : {
- "entry" : [ {
- "key" : "IEPAR0",
- "value" : {
- "key" : "IEPAR0",
- "fieldSchemaKey" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- }
- }
- }, {
- "key" : "IEPAR1",
- "value" : {
- "key" : "IEPAR1",
- "fieldSchemaKey" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- }
- }
- } ]
- }
- }
- }, {
- "key" : {
- "name" : "outEvent0",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "outEvent0",
- "version" : "0.0.1"
- },
- "nameSpace" : "org.onap.policy.apex.model.policymodel.events",
- "source" : "Source",
- "target" : "Target",
- "parameter" : {
- "entry" : [ {
- "key" : "OE0PAR0",
- "value" : {
- "key" : "OE0PAR0",
- "fieldSchemaKey" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- }
- }
- }, {
- "key" : "OE0PAR1",
- "value" : {
- "key" : "OE0PAR1",
- "fieldSchemaKey" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- }
- }
- }, {
- "key" : "OE1PAR0",
- "value" : {
- "key" : "OE1PAR0",
- "fieldSchemaKey" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- }
- }
- }, {
- "key" : "OE1PAR1",
- "value" : {
- "key" : "OE1PAR1",
- "fieldSchemaKey" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- }
- }
- } ]
- }
- }
- }, {
- "key" : {
- "name" : "outEvent1",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "outEvent1",
- "version" : "0.0.1"
- },
- "nameSpace" : "org.onap.policy.apex.model.policymodel.events",
- "source" : "Source",
- "target" : "Target",
- "parameter" : {
- "entry" : [ {
- "key" : "OE1PAR0",
- "value" : {
- "key" : "OE1PAR0",
- "fieldSchemaKey" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- }
- }
- }, {
- "key" : "OE1PAR1",
- "value" : {
- "key" : "OE1PAR1",
- "fieldSchemaKey" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- }
+ }
+ }
}
- } ]
- }
- }
- } ]
- }
- },
- "albums" : {
- "key" : {
- "name" : "context",
- "version" : "0.0.1"
- },
- "albums" : {
- "entry" : [ {
- "key" : {
- "name" : "contextAlbum0",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "contextAlbum0",
- "version" : "0.0.1"
- },
- "scope" : "APPLICATION",
- "isWritable" : true,
- "itemSchema" : {
- "name" : "MapType",
- "version" : "0.0.1"
- }
- }
- }, {
- "key" : {
- "name" : "contextAlbum1",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "contextAlbum1",
- "version" : "0.0.1"
- },
- "scope" : "GLOBAL",
- "isWritable" : false,
- "itemSchema" : {
- "name" : "StringType",
- "version" : "0.0.1"
- }
- }
- } ]
- }
- },
- "schemas" : {
- "key" : {
- "name" : "ContextSchemas",
- "version" : "0.0.1"
- },
- "schemas" : {
- "entry" : [ {
- "key" : {
- "name" : "MapType",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "MapType",
- "version" : "0.0.1"
- },
- "schemaFlavour" : "Java",
- "schemaDefinition" : "org.onap.policy.apex.model.policymodel.concepts.TestContextItem00A"
- }
- }, {
- "key" : {
- "name" : "StringType",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "StringType",
- "version" : "0.0.1"
- },
- "schemaFlavour" : "Java",
- "schemaDefinition" : "org.onap.policy.apex.model.policymodel.concepts.TestContextItem000"
- }
- }, {
- "key" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "eventContextItem0",
- "version" : "0.0.1"
- },
- "schemaFlavour" : "Java",
- "schemaDefinition" : "java.lang.String"
- }
- }, {
- "key" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "eventContextItem1",
- "version" : "0.0.1"
- },
- "schemaFlavour" : "Java",
- "schemaDefinition" : "java.lang.Long"
- }
- } ]
- }
- }
- }
-} \ No newline at end of file
+ }
+ }
+ }
+ ]
+ }
+}
diff --git a/gui-editors/gui-editor-apex/src/test/resources/models/PolicyModel.yaml b/gui-editors/gui-editor-apex/src/test/resources/models/PolicyModel.yaml
new file mode 100644
index 0000000..201085c
--- /dev/null
+++ b/gui-editors/gui-editor-apex/src/test/resources/models/PolicyModel.yaml
@@ -0,0 +1,538 @@
+---
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+topology_template:
+ policies:
+ - onap.policies.native.apex.Vcpe:
+ type: onap.policies.native.Apex
+ type_version: 1.0.0
+ properties:
+ engineServiceParameters:
+ name: MyApexEngine
+ version: 0.0.1
+ id: 45
+ instanceCount: 4
+ deploymentPort: 12561
+ policyModelFileName: "/home/apexuser/examples/models/ONAPvCPE/ONAPvCPEPolicyModel.json"
+ engineParameters:
+ executorParameters:
+ JAVASCRIPT:
+ parameterClassName: org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters
+ contextParameters:
+ parameterClassName: org.onap.policy.apex.context.parameters.ContextParameters
+ schemaParameters:
+ Avro:
+ parameterClassName: org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters
+ Java:
+ parameterClassName: org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters
+ jsonAdapters:
+ Instant:
+ adaptedClass: java.time.Instant
+ adaptorClass: org.onap.policy.controlloop.util.Serialization$GsonInstantAdapter
+ policy_type_impl:
+ apexPolicyModel:
+ key:
+ name: PolicyModel
+ version: 0.0.1
+ keyInformation:
+ key:
+ name: KeyInfoMapKey
+ version: 0.0.1
+ keyInfoMap:
+ entry:
+ - key:
+ name: ContextSchemas
+ version: 0.0.1
+ value:
+ key:
+ name: ContextSchemas
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e000
+ description: Generated description for concept referred to by
+ key "ContextSchemas:0.0.1"
+ - key:
+ name: KeyInfoMapKey
+ version: 0.0.1
+ value:
+ key:
+ name: KeyInfoMapKey
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e001
+ description: Generated description for concept referred to by
+ key "KeyInfoMapKey:0.0.1"
+ - key:
+ name: MapType
+ version: 0.0.1
+ value:
+ key:
+ name: MapType
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e002
+ description: Generated description for concept referred to by
+ key "MapType:0.0.1"
+ - key:
+ name: PolicyModel
+ version: 0.0.1
+ value:
+ key:
+ name: PolicyModel
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e003
+ description: Generated description for concept referred to by
+ key "PolicyModel:0.0.1"
+ - key:
+ name: StringType
+ version: 0.0.1
+ value:
+ key:
+ name: StringType
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e004
+ description: Generated description for concept referred to by
+ key "StringType:0.0.1"
+ - key:
+ name: context
+ version: 0.0.1
+ value:
+ key:
+ name: context
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e005
+ description: Generated description for concept referred to by
+ key "context:0.0.1"
+ - key:
+ name: contextAlbum0
+ version: 0.0.1
+ value:
+ key:
+ name: contextAlbum0
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e006
+ description: Generated description for concept referred to by
+ key "contextAlbum0:0.0.1"
+ - key:
+ name: contextAlbum1
+ version: 0.0.1
+ value:
+ key:
+ name: contextAlbum1
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e007
+ description: Generated description for concept referred to by
+ key "contextAlbum1:0.0.1"
+ - key:
+ name: eventContextItem0
+ version: 0.0.1
+ value:
+ key:
+ name: eventContextItem0
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e008
+ description: Generated description for concept referred to by
+ key "eventContextItem0:0.0.1"
+ - key:
+ name: eventContextItem1
+ version: 0.0.1
+ value:
+ key:
+ name: eventContextItem1
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e009
+ description: Generated description for concept referred to by
+ key "eventContextItem1:0.0.1"
+ - key:
+ name: events
+ version: 0.0.1
+ value:
+ key:
+ name: events
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e010
+ description: Generated description for concept referred to by
+ key "events:0.0.1"
+ - key:
+ name: inEvent
+ version: 0.0.1
+ value:
+ key:
+ name: inEvent
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e011
+ description: Generated description for concept referred to by
+ key "inEvent:0.0.1"
+ - key:
+ name: outEvent0
+ version: 0.0.1
+ value:
+ key:
+ name: outEvent0
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e012
+ description: Generated description for concept referred to by
+ key "outEvent0:0.0.1"
+ - key:
+ name: outEvent1
+ version: 0.0.1
+ value:
+ key:
+ name: outEvent1
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e013
+ description: Generated description for concept referred to by
+ key "outEvent1:0.0.1"
+ - key:
+ name: policies
+ version: 0.0.1
+ value:
+ key:
+ name: policies
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e014
+ description: Generated description for concept referred to by
+ key "policies:0.0.1"
+ - key:
+ name: policy
+ version: 0.0.1
+ value:
+ key:
+ name: policy
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e015
+ description: Generated description for concept referred to by
+ key "policy:0.0.1"
+ - key:
+ name: task
+ version: 0.0.1
+ value:
+ key:
+ name: task
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e016
+ description: Generated description for concept referred to by
+ key "task:0.0.1"
+ - key:
+ name: tasks
+ version: 0.0.1
+ value:
+ key:
+ name: tasks
+ version: 0.0.1
+ UUID: 0ce9168c-e6df-414f-9646-6da464b6e017
+ description: Generated description for concept referred to by
+ key "tasks:0.0.1"
+ policies:
+ key:
+ name: policies
+ version: 0.0.1
+ policyMap:
+ entry:
+ - key:
+ name: policy
+ version: 0.0.1
+ value:
+ policyKey:
+ name: policy
+ version: 0.0.1
+ template: FREEFORM
+ state:
+ entry:
+ - key: state
+ value:
+ stateKey:
+ parentKeyName: policy
+ parentKeyVersion: 0.0.1
+ parentLocalName: 'NULL'
+ localName: state
+ trigger:
+ name: inEvent
+ version: 0.0.1
+ stateOutputs:
+ entry:
+ - key: stateOutput0
+ value:
+ key:
+ parentKeyName: policy
+ parentKeyVersion: 0.0.1
+ parentLocalName: state
+ localName: stateOutput0
+ outgoingEvent:
+ name: outEvent0
+ version: 0.0.1
+ nextState:
+ parentKeyName: 'NULL'
+ parentKeyVersion: 0.0.0
+ parentLocalName: 'NULL'
+ localName: 'NULL'
+ contextAlbumReference:
+ - name: contextAlbum0
+ version: 0.0.1
+ - name: contextAlbum1
+ version: 0.0.1
+ taskSelectionLogic:
+ key: taskSelectionLogic
+ logicFlavour: MVEL
+ logic: Some TS logic
+ stateFinalizerLogicMap:
+ entry: []
+ defaultTask:
+ name: task
+ version: 0.0.1
+ taskReferences:
+ entry:
+ - key:
+ name: task
+ version: 0.0.1
+ value:
+ key:
+ parentKeyName: policy
+ parentKeyVersion: 0.0.1
+ parentLocalName: state
+ localName: task
+ outputType: DIRECT
+ output:
+ parentKeyName: policy
+ parentKeyVersion: 0.0.1
+ parentLocalName: state
+ localName: stateOutput0
+ firstState: state
+ tasks:
+ key:
+ name: tasks
+ version: 0.0.1
+ taskMap:
+ entry:
+ - key:
+ name: task
+ version: 0.0.1
+ value:
+ key:
+ name: task
+ version: 0.0.1
+ inputFields:
+ entry:
+ - key: IEPAR0
+ value:
+ key: IEPAR0
+ fieldSchemaKey:
+ name: eventContextItem0
+ version: 0.0.1
+ - key: IEPAR1
+ value:
+ key: IEPAR1
+ fieldSchemaKey:
+ name: eventContextItem1
+ version: 0.0.1
+ outputFields:
+ entry:
+ - key: OE0PAR0
+ value:
+ key: OE0PAR0
+ fieldSchemaKey:
+ name: eventContextItem0
+ version: 0.0.1
+ - key: OE0PAR1
+ value:
+ key: OE0PAR1
+ fieldSchemaKey:
+ name: eventContextItem1
+ version: 0.0.1
+ - key: OE1PAR0
+ value:
+ key: OE1PAR0
+ fieldSchemaKey:
+ name: eventContextItem0
+ version: 0.0.1
+ - key: OE1PAR1
+ value:
+ key: OE1PAR1
+ fieldSchemaKey:
+ name: eventContextItem1
+ version: 0.0.1
+ taskParameters:
+ entry:
+ - key: taskParameter0
+ value:
+ key:
+ parentKeyName: task
+ parentKeyVersion: 0.0.1
+ parentLocalName: 'NULL'
+ localName: taskParameter0
+ defaultValue: Task parameter 0 value
+ - key: taskParameter1
+ value:
+ key:
+ parentKeyName: task
+ parentKeyVersion: 0.0.1
+ parentLocalName: 'NULL'
+ localName: taskParameter1
+ defaultValue: Task parameter 1 value
+ contextAlbumReference:
+ - name: contextAlbum0
+ version: 0.0.1
+ - name: contextAlbum1
+ version: 0.0.1
+ taskLogic:
+ key: taskLogic
+ logicFlavour: MVEL
+ logic: Some task logic
+ events:
+ key:
+ name: events
+ version: 0.0.1
+ eventMap:
+ entry:
+ - key:
+ name: inEvent
+ version: 0.0.1
+ value:
+ key:
+ name: inEvent
+ version: 0.0.1
+ nameSpace: org.onap.policy.apex.model.policymodel.events
+ source: Source
+ target: Target
+ parameter:
+ entry:
+ - key: IEPAR0
+ value:
+ key: IEPAR0
+ fieldSchemaKey:
+ name: eventContextItem0
+ version: 0.0.1
+ - key: IEPAR1
+ value:
+ key: IEPAR1
+ fieldSchemaKey:
+ name: eventContextItem1
+ version: 0.0.1
+ - key:
+ name: outEvent0
+ version: 0.0.1
+ value:
+ key:
+ name: outEvent0
+ version: 0.0.1
+ nameSpace: org.onap.policy.apex.model.policymodel.events
+ source: Source
+ target: Target
+ parameter:
+ entry:
+ - key: OE0PAR0
+ value:
+ key: OE0PAR0
+ fieldSchemaKey:
+ name: eventContextItem0
+ version: 0.0.1
+ - key: OE0PAR1
+ value:
+ key: OE0PAR1
+ fieldSchemaKey:
+ name: eventContextItem1
+ version: 0.0.1
+ - key: OE1PAR0
+ value:
+ key: OE1PAR0
+ fieldSchemaKey:
+ name: eventContextItem0
+ version: 0.0.1
+ - key: OE1PAR1
+ value:
+ key: OE1PAR1
+ fieldSchemaKey:
+ name: eventContextItem1
+ version: 0.0.1
+ - key:
+ name: outEvent1
+ version: 0.0.1
+ value:
+ key:
+ name: outEvent1
+ version: 0.0.1
+ nameSpace: org.onap.policy.apex.model.policymodel.events
+ source: Source
+ target: Target
+ parameter:
+ entry:
+ - key: OE1PAR0
+ value:
+ key: OE1PAR0
+ fieldSchemaKey:
+ name: eventContextItem0
+ version: 0.0.1
+ - key: OE1PAR1
+ value:
+ key: OE1PAR1
+ fieldSchemaKey:
+ name: eventContextItem1
+ version: 0.0.1
+ albums:
+ key:
+ name: context
+ version: 0.0.1
+ albums:
+ entry:
+ - key:
+ name: contextAlbum0
+ version: 0.0.1
+ value:
+ key:
+ name: contextAlbum0
+ version: 0.0.1
+ scope: APPLICATION
+ isWritable: true
+ itemSchema:
+ name: MapType
+ version: 0.0.1
+ - key:
+ name: contextAlbum1
+ version: 0.0.1
+ value:
+ key:
+ name: contextAlbum1
+ version: 0.0.1
+ scope: GLOBAL
+ isWritable: false
+ itemSchema:
+ name: StringType
+ version: 0.0.1
+ schemas:
+ key:
+ name: ContextSchemas
+ version: 0.0.1
+ schemas:
+ entry:
+ - key:
+ name: MapType
+ version: 0.0.1
+ value:
+ key:
+ name: MapType
+ version: 0.0.1
+ schemaFlavour: Java
+ schemaDefinition: org.onap.policy.apex.model.policymodel.concepts.TestContextItem00A
+ - key:
+ name: StringType
+ version: 0.0.1
+ value:
+ key:
+ name: StringType
+ version: 0.0.1
+ schemaFlavour: Java
+ schemaDefinition: org.onap.policy.apex.model.policymodel.concepts.TestContextItem000
+ - key:
+ name: eventContextItem0
+ version: 0.0.1
+ value:
+ key:
+ name: eventContextItem0
+ version: 0.0.1
+ schemaFlavour: Java
+ schemaDefinition: java.lang.String
+ - key:
+ name: eventContextItem1
+ version: 0.0.1
+ value:
+ key:
+ name: eventContextItem1
+ version: 0.0.1
+ schemaFlavour: Java
+ schemaDefinition: java.lang.Long