diff options
author | liamfallon <liam.fallon@ericsson.com> | 2018-09-22 21:07:43 +0100 |
---|---|---|
committer | liamfallon <liam.fallon@ericsson.com> | 2018-09-22 21:15:22 +0100 |
commit | 6973ec9109fd2651e2284663b6c8039bd830a677 (patch) | |
tree | f1f02ef9e5400805e6c2179dc539ad15c3ce5334 | |
parent | a02548ec2e98a8a13cd76ecc83379b13cd26030b (diff) |
Fix sonar problems in Apex
Fixed some easy to resolve Sonar issues.
Issue-ID: POLICY-1034
Change-Id: Ia8e4606bd4307daca499b4a74c96135211e572fd
Signed-off-by: liamfallon <liam.fallon@ericsson.com>
51 files changed, 956 insertions, 541 deletions
diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgument.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgument.java index f1a6e7867..6dd2f14ee 100644 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgument.java +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineArgument.java @@ -141,4 +141,54 @@ public class CommandLineArgument implements Comparable<CommandLineArgument> { } return description.compareTo(otherArgument.description); } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((argumentName == null) ? 0 : argumentName.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + (nullable ? 1231 : 1237); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (obj == null) { + return false; + } + + if (getClass() != obj.getClass()) { + return false; + } + + CommandLineArgument other = (CommandLineArgument) obj; + if (argumentName == null) { + if (other.argumentName != null) { + return false; + } + } else if (!argumentName.equals(other.argumentName)) { + return false; + } + + if (description == null) { + if (other.description != null) { + return false; + } + } else if (!description.equals(other.description)) { + return false; + } + + return nullable == other.nullable; + } } diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommand.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommand.java index 6c651cb6b..beba91554 100644 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommand.java +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineCommand.java @@ -214,12 +214,33 @@ public class CommandLineCommand implements Comparable<CommandLineCommand> { return this.hashCode() - otherCommand.hashCode(); } - final CommandLineCommand other = otherCommand; + int result = compareKeywordList(otherCommand); + if (result != 0) { + return result; + } + + if (!argumentList.equals(otherCommand.argumentList)) { + return (argumentList.hashCode() - otherCommand.argumentList.hashCode()); + } + + if (systemCommand != otherCommand.systemCommand) { + return (this.hashCode() - otherCommand.hashCode()); + } + + return apiMethod.compareTo(otherCommand.apiMethod); + } + /** + * Compare the keyword lists of the commands. + * + * @param otherCommand the command to compare with + * @return the int + */ + private int compareKeywordList(final CommandLineCommand otherCommand) { for (int i = 0, j = 0;; i++, j++) { if (i < keywordlist.size() && j < otherCommand.keywordlist.size()) { - if (!keywordlist.get(i).equals(other.keywordlist.get(j))) { - return keywordlist.get(i).compareTo(other.keywordlist.get(j)); + if (!keywordlist.get(i).equals(otherCommand.keywordlist.get(j))) { + return keywordlist.get(i).compareTo(otherCommand.keywordlist.get(j)); } } else if (i == keywordlist.size() && j == otherCommand.keywordlist.size()) { break; @@ -229,12 +250,43 @@ public class CommandLineCommand implements Comparable<CommandLineCommand> { return 1; } } - if (!argumentList.equals(other.argumentList)) { - return (argumentList.hashCode() - other.argumentList.hashCode()); + + return 0; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((apiMethod == null) ? 0 : apiMethod.hashCode()); + result = prime * result + argumentList.hashCode(); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + keywordlist.hashCode(); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + (systemCommand ? 1231 : 1237); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (obj == null) { + return false; } - if (systemCommand != other.systemCommand) { - return (this.hashCode() - other.hashCode()); + + if (getClass() != obj.getClass()) { + return false; } - return apiMethod.compareTo(other.apiMethod); + + return this.compareTo((CommandLineCommand) obj) == 0; } } diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorLoop.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorLoop.java index 4f0aeb58b..b5e82103d 100644 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorLoop.java +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorLoop.java @@ -58,6 +58,7 @@ public class CommandLineEditorLoop { // Recurring string constants private static final String COMMAND = "command "; + private static final String COMMAND_LINE_ERROR = "command line error"; // The model handler that is handling the API towards the Apex model being editied private final ApexModelHandler modelHandler; @@ -134,7 +135,7 @@ public class CommandLineEditorLoop { catch (final CommandLineException e) { writer.println(e.getMessage()); errorCount++; - LOGGER.debug("command line error", e); + LOGGER.debug(COMMAND_LINE_ERROR, e); continue; } @@ -163,7 +164,7 @@ public class CommandLineEditorLoop { catch (final CommandLineException e) { writer.println(e.getMessage()); errorCount++; - LOGGER.debug("command line error", e); + LOGGER.debug(COMMAND_LINE_ERROR, e); continue; } @@ -204,10 +205,10 @@ public class CommandLineEditorLoop { catch (final CommandLineException e) { writer.println(e.getMessage()); errorCount++; - LOGGER.debug("command line error", e); + LOGGER.debug(COMMAND_LINE_ERROR, e); } catch (final Exception e) { e.printStackTrace(writer); - LOGGER.error("command line error", e); + LOGGER.error(COMMAND_LINE_ERROR, e); } } diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameterParser.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameterParser.java index a37d07fab..3465a6dd8 100644 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameterParser.java +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CommandLineParameterParser.java @@ -107,6 +107,45 @@ public class CommandLineParameterParser { "too many command line arguments specified : " + Arrays.toString(remainingArgs)); } + parseSIngleLetterOptions(commandLine, parameters); + parseDoubleLetterOptions(commandLine, parameters); + + return parameters; + } + + /** + * Parse options with just a single letter. + * + * @param commandLine the command line + * @param parameters the parsed parameters + */ + private void parseDoubleLetterOptions(CommandLine commandLine, final CommandLineParameters parameters) { + if (commandLine.hasOption("nl")) { + parameters.setSuppressLog(true); + } + if (commandLine.hasOption("nm")) { + parameters.setSuppressModelOutput(true); + } + if (commandLine.hasOption("if")) { + parameters.setIgnoreCommandFailuresSet(true); + parameters.setIgnoreCommandFailures(Boolean.valueOf(commandLine.getOptionValue("if"))); + } else { + parameters.setIgnoreCommandFailuresSet(false); + } + if (commandLine.hasOption("wd")) { + parameters.setWorkingDirectory(commandLine.getOptionValue("wd")); + } else { + parameters.setWorkingDirectory(Paths.get("").toAbsolutePath().toString()); + } + } + + /** + * Parse options with two letters. + * + * @param commandLine the command line + * @param parameters the parsed parameters + */ + private void parseSIngleLetterOptions(CommandLine commandLine, final CommandLineParameters parameters) { if (commandLine.hasOption('h')) { parameters.setHelp(true); } @@ -122,31 +161,12 @@ public class CommandLineParameterParser { if (commandLine.hasOption('l')) { parameters.setLogFileName(commandLine.getOptionValue('l')); } - if (commandLine.hasOption("nl")) { - parameters.setSuppressLog(true); - } - if (commandLine.hasOption("nm")) { - parameters.setSuppressModelOutput(true); - } if (commandLine.hasOption('i')) { parameters.setInputModelFileName(commandLine.getOptionValue('i')); } if (commandLine.hasOption('o')) { parameters.setOutputModelFileName(commandLine.getOptionValue('o')); } - if (commandLine.hasOption("if")) { - parameters.setIgnoreCommandFailuresSet(true); - parameters.setIgnoreCommandFailures(Boolean.valueOf(commandLine.getOptionValue("if"))); - } else { - parameters.setIgnoreCommandFailuresSet(false); - } - if (commandLine.hasOption("wd")) { - parameters.setWorkingDirectory(commandLine.getOptionValue("wd")); - } else { - parameters.setWorkingDirectory(Paths.get("").toAbsolutePath().toString()); - } - - return parameters; } /** diff --git a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/KeywordNode.java b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/KeywordNode.java index c8bc7a083..c16bbf568 100644 --- a/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/KeywordNode.java +++ b/auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/KeywordNode.java @@ -186,4 +186,31 @@ public class KeywordNode implements Comparable<KeywordNode> { } return command.compareTo(otherKeywordNode.command); } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((children == null) ? 0 : children.hashCode()); + result = prime * result + ((command == null) ? 0 : command.hashCode()); + result = prime * result + ((keyword == null) ? 0 : keyword.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (obj == null) { + return false; + } + + if (getClass() != obj.getClass()) { + return false; + } + + return this.compareTo((KeywordNode) obj) == 0; + } } diff --git a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestMain.java b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestMain.java index 134914f11..8f6dcd089 100644 --- a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestMain.java +++ b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ApexDeploymentRestMain.java @@ -54,20 +54,6 @@ public class ApexDeploymentRestMain { private ApexDeploymentRest apexDeploymentRest = null; /** - * Main method, main entry point for command. - * - * @param args The command line arguments for the client - */ - public static void main(final String[] args) { - try { - final ApexDeploymentRestMain restMain = new ApexDeploymentRestMain(args, System.out); - restMain.init(); - } catch (final Exception e) { - LOGGER.error("start failed", e); - } - } - - /** * Constructor, kicks off the rest service. * * @param args The command line arguments for the RESTful service @@ -201,4 +187,17 @@ public class ApexDeploymentRestMain { } } + /** + * Main method, main entry point for command. + * + * @param args The command line arguments for the client + */ + public static void main(final String[] args) { + try { + final ApexDeploymentRestMain restMain = new ApexDeploymentRestMain(args, System.out); + restMain.init(); + } catch (final Exception e) { + LOGGER.error("start failed", e); + } + } } diff --git a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ParameterCheck.java b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ParameterCheck.java index 5026c5162..4e75763db 100644 --- a/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ParameterCheck.java +++ b/client/client-deployment/src/main/java/org/onap/policy/apex/client/deployment/rest/ParameterCheck.java @@ -32,6 +32,12 @@ import org.slf4j.ext.XLoggerFactory; * @author Liam Fallon (liam.fallon@ericsson.com) */ public final class ParameterCheck { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ParameterCheck.class); + + private static final String HOSTNAME_PAR = "hostname"; + private static final String PORT_PAR = "port"; + private static final String AXARTIFACTKEY_PAR = "AxArtifactKey"; + // Recurring string constants private static final String OF_PARAMETER = "\"of parameter \""; private static final String VALUE = "value \""; @@ -58,12 +64,6 @@ public final class ParameterCheck { STOP } - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ParameterCheck.class); - - private static final String HOSTNAME_PAR = "hostname"; - private static final String PORT_PAR = "port"; - private static final String AXARTIFACTKEY_PAR = "AxArtifactKey"; - /** * Gets the host name. * diff --git a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/handling/RestCommandHandler.java b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/handling/RestCommandHandler.java index c4fd6d6f4..5921c8960 100644 --- a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/handling/RestCommandHandler.java +++ b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/handling/RestCommandHandler.java @@ -23,7 +23,6 @@ package org.onap.policy.apex.client.editor.rest.handling; import org.onap.policy.apex.model.modelapi.ApexApiResult; import org.onap.policy.apex.model.modelapi.ApexApiResult.Result; -// TODO: Auto-generated Javadoc /** * This interface defines the methods that a REST handler must implement to handle REST editor commands. * diff --git a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/handling/bean/BeanBase.java b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/handling/bean/BeanBase.java index 20f8d6f07..6ac5c48e1 100644 --- a/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/handling/bean/BeanBase.java +++ b/client/client-editor/src/main/java/org/onap/policy/apex/client/editor/rest/handling/bean/BeanBase.java @@ -31,6 +31,9 @@ public abstract class BeanBase { private static final String PROBLEM_RETRIEVING_FIELD_PREFIX = "Problem retrieving field called ('"; private static final String JSON_BEAN_SUFFIX = "') from JSON bean "; + // Magic numbers + private static final int GET_LENGTH = 3; + /** * Gets a named field from the bean. * @@ -38,20 +41,14 @@ public abstract class BeanBase { * @return the value for the field */ public String get(final String field) { - // CHECKSTYLE:OFF: MagicNumber // use getter preferably for (final Method method : this.getClass().getMethods()) { - if ((method.getName().startsWith("get")) && (method.getName().length() == (field.length() + 3))) { - if (method.getName().toLowerCase().endsWith(field.toLowerCase())) { - try { - return (String) method.invoke(this); - } catch (final Exception e) { - throw new IllegalArgumentException( - PROBLEM_RETRIEVING_FIELD_PREFIX + field + JSON_BEAN_SUFFIX + this, e); - } - } + if (method.getName().startsWith("get") && method.getName().length() == (field.length() + GET_LENGTH) + && method.getName().toLowerCase().endsWith(field.toLowerCase())) { + return invokeGetterMethod(field, method); } } + // Use field approach if (field != null) { try { @@ -61,10 +58,24 @@ public abstract class BeanBase { return (String) (f.get(this)); } } catch (final Exception e) { - throw new IllegalArgumentException( - PROBLEM_RETRIEVING_FIELD_PREFIX + field + JSON_BEAN_SUFFIX + this, e); + throw new IllegalArgumentException(PROBLEM_RETRIEVING_FIELD_PREFIX + field + JSON_BEAN_SUFFIX + this, + e); } } throw new IllegalArgumentException(PROBLEM_RETRIEVING_FIELD_PREFIX + field + JSON_BEAN_SUFFIX + this); } + + /** + * Invoke a getter method on a bean. + * + * @param field the field that the getter gets a value for + * @param method the method to invoke + */ + private String invokeGetterMethod(final String field, final Method method) { + try { + return (String) method.invoke(this); + } catch (final Exception e) { + throw new IllegalArgumentException(PROBLEM_RETRIEVING_FIELD_PREFIX + field + JSON_BEAN_SUFFIX + this, e); + } + } } diff --git a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestMain.java b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestMain.java index b11cd7ff3..7b9f4187d 100644 --- a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestMain.java +++ b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ApexServicesRestMain.java @@ -65,20 +65,6 @@ public class ApexServicesRestMain { private final PrintStream outStream; /** - * Main method, main entry point for command. - * - * @param args The command line arguments for the editor - */ - public static void main(final String[] args) { - try { - final ApexServicesRestMain editorMain = new ApexServicesRestMain(args, System.out); - editorMain.init(); - } catch (final Exception e) { - LOGGER.error("error starting REST client", e); - } - } - - /** * Constructor, kicks off the editor. * * @param args The command line arguments for the editor @@ -213,4 +199,17 @@ public class ApexServicesRestMain { } } } + /** + * Main method, main entry point for command. + * + * @param args The command line arguments for the editor + */ + public static void main(final String[] args) { + try { + final ApexServicesRestMain editorMain = new ApexServicesRestMain(args, System.out); + editorMain.init(); + } catch (final Exception e) { + LOGGER.error("error starting REST client", e); + } + } } diff --git a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ParameterCheck.java b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ParameterCheck.java index 301b19f38..9832f4317 100644 --- a/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ParameterCheck.java +++ b/client/client-full/src/main/java/org/onap/policy/apex/client/full/rest/ParameterCheck.java @@ -32,6 +32,12 @@ import org.slf4j.ext.XLoggerFactory; * @author Liam Fallon (liam.fallon@ericsson.com) */ public final class ParameterCheck { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ParameterCheck.class); + + private static final String HOSTNAME_PAR = "hostname"; + private static final String PORT_PAR = "port"; + private static final String AXARTIFACTKEY_PAR = "AxArtifactKey"; + // Recurring string constants private static final String PARAMETER = "parameter \""; private static final String NOT_FOUND = "\" not found"; @@ -56,12 +62,6 @@ public final class ParameterCheck { STOP } - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ParameterCheck.class); - - private static final String HOSTNAME_PAR = "hostname"; - private static final String PORT_PAR = "port"; - private static final String AXARTIFACTKEY_PAR = "AxArtifactKey"; - /** * Gets the host name. * diff --git a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestMain.java b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestMain.java index e1b5a9174..523a6eebb 100644 --- a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestMain.java +++ b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestMain.java @@ -54,20 +54,6 @@ public class ApexMonitoringRestMain { private ApexMonitoringRest apexMonitoringRest = null; /** - * Main method, main entry point for command. - * - * @param args The command line arguments for the client - */ - public static void main(final String[] args) { - try { - final ApexMonitoringRestMain restMain = new ApexMonitoringRestMain(args, System.out); - restMain.init(); - } catch (final Exception e) { - LOGGER.error("start failed", e); - } - } - - /** * Constructor, kicks off the rest service. * * @param args The command line arguments for the RESTful service @@ -201,4 +187,17 @@ public class ApexMonitoringRestMain { } } + /** + * Main method, main entry point for command. + * + * @param args The command line arguments for the client + */ + public static void main(final String[] args) { + try { + final ApexMonitoringRestMain restMain = new ApexMonitoringRestMain(args, System.out); + restMain.init(); + } catch (final Exception e) { + LOGGER.error("start failed", e); + } + } } diff --git a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ParameterCheck.java b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ParameterCheck.java index 46e1452a5..acaee5fdb 100644 --- a/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ParameterCheck.java +++ b/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ParameterCheck.java @@ -32,6 +32,12 @@ import org.slf4j.ext.XLoggerFactory; * @author Liam Fallon (liam.fallon@ericsson.com) */ public final class ParameterCheck { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ParameterCheck.class); + + private static final String HOSTNAME_PAR = "hostname"; + private static final String PORT_PAR = "port"; + private static final String AXARTIFACTKEY_PAR = "AxArtifactKey"; + // Recurring string constants private static final String PARAMETER = "parameter \""; private static final String NOT_FOUND = "\" not found"; @@ -56,12 +62,6 @@ public final class ParameterCheck { STOP } - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ParameterCheck.class); - - private static final String HOSTNAME_PAR = "hostname"; - private static final String PORT_PAR = "port"; - private static final String AXARTIFACTKEY_PAR = "AxArtifactKey"; - /** * Gets the host name. * diff --git a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextAlbumUpdate.java b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextAlbumUpdate.java index 0d2528791..50f968997 100644 --- a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextAlbumUpdate.java +++ b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextAlbumUpdate.java @@ -54,7 +54,7 @@ public class ContextAlbumUpdate { * @throws IOException the IO exception * @throws ApexException the apex exception */ - public void testContextAlbumUpdate() throws IOException, ApexException { + public void testContextAlbumUpdate() throws ApexException { LOGGER.debug("Running TestContextAlbumUpdate test . . ."); final AxArtifactKey distributorKey = new AxArtifactKey(APEX_DISTRIBUTOR, VERSION); diff --git a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextInstantiation.java b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextInstantiation.java index 17c98a12d..8c4f40a5a 100644 --- a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextInstantiation.java +++ b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextInstantiation.java @@ -133,218 +133,211 @@ public class ContextInstantiation { final Distributor contextDistributor = getDistributor(); - try { + final ContextAlbum policyContextAlbum = contextDistributor + .createContextAlbum(new AxArtifactKey(POLICY_CONTEXT_ALBUM, VERSION)); + + assertNotNull(policyContextAlbum); + policyContextAlbum.setUserArtifactStack(Constants.getAxArtifactKeyArray()); + + final Date testDate = new Date(); + + final TestContextDateTzItem tci9 = getTestContextDateTzItem(testDate); + final TestContextDateLocaleItem tciA = getTestContextDateLocaleItem(testDate); + + final TestPolicyContextItem policyContext = getTestPolicyContextItem(policyContextAlbum, testDate); + + final Map<String, Object> valueMap0 = new HashMap<>(); + valueMap0.put(TEST_POLICY_CONTEXT_ITEM, policyContext); + + policyContextAlbum.putAll(valueMap0); + + final TestPolicyContextItem contextItem = (TestPolicyContextItem) policyContextAlbum + .get(TEST_POLICY_CONTEXT_ITEM); + assertEquals(STRING_VAL, contextItem.getTestPolicyContextItem000().getStringValue()); + + assertEquals(LONG_VAL, contextItem.getTestPolicyContextItem001().getLongValue()); + assertDouble(contextItem.getTestPolicyContextItem002().getDoubleValue(), PI_VAL); + assertTrue(contextItem.getTestPolicyContextItem003().getFlag()); + assertEquals(contextItem.getTestPolicyContextItem004().getLongValue(), testDate.getTime()); + assertEquals(TEST_HASH_MAP, contextItem.getTestPolicyContextItem005().getMapValue()); + + final TestGlobalContextItem globalContext = getTestGlobalContextItem(contextDistributor, testDate, tci9, + tciA); + + final Map<String, Object> valueMap1 = new HashMap<>(); + valueMap1.put(GLOBAL_CONTEXT_KEY, globalContext); + + final ContextAlbum globalContextAlbum = getContextAlbum(contextDistributor); + + globalContextAlbum.putAll(valueMap1); - final ContextAlbum policyContextAlbum = contextDistributor - .createContextAlbum(new AxArtifactKey(POLICY_CONTEXT_ALBUM, VERSION)); + final TestGlobalContextItem globalContextItem = (TestGlobalContextItem) globalContextAlbum + .get(GLOBAL_CONTEXT_KEY); - assertNotNull(policyContextAlbum); - policyContextAlbum.setUserArtifactStack(Constants.getAxArtifactKeyArray()); + assertFalse(globalContextItem.getTestGlobalContextItem000().getFlag()); - final Date testDate = new Date(); + assertEquals(BYTE_VAL, globalContextItem.getTestGlobalContextItem001().getByteValue()); - final TestContextDateTzItem tci9 = getTestContextDateTzItem(testDate); - final TestContextDateLocaleItem tciA = getTestContextDateLocaleItem(testDate); + assertEquals(INT_VAL, globalContextItem.getTestGlobalContextItem002().getIntValue()); + assertEquals(LONG_VAL, globalContextItem.getTestGlobalContextItem003().getLongValue()); + assertFloat(FLOAT_VAL, globalContextItem.getTestGlobalContextItem004().getFloatValue()); - final TestPolicyContextItem policyContext = getTestPolicyContextItem(policyContextAlbum, testDate); + assertDouble(PI_VAL, globalContextItem.getTestGlobalContextItem005().getDoubleValue()); + assertEquals(STRING_GLOBAL_VAL, globalContextItem.getTestGlobalContextItem006().getStringValue()); - final Map<String, Object> valueMap0 = new HashMap<>(); - valueMap0.put(TEST_POLICY_CONTEXT_ITEM, policyContext); + assertEquals((Long) testDate.getTime(), globalContextItem.getTestGlobalContextItem007().getLongValue()); + assertEquals(testDate, globalContextItem.getTestGlobalContextItem008().getDateValue()); + assertEquals(tci9.getDateValue().getTime(), + globalContextItem.getTestGlobalContextItem009().getDateValue().getTime()); - policyContextAlbum.putAll(valueMap0); + assertEquals(tciA.getDateValue().getTime(), + globalContextItem.getTestGlobalContextItem00A().getDateValue().getTime()); - final TestPolicyContextItem contextItem = (TestPolicyContextItem) policyContextAlbum - .get(TEST_POLICY_CONTEXT_ITEM); - assertEquals(STRING_VAL, contextItem.getTestPolicyContextItem000().getStringValue()); + assertEquals(TEST_TREE_SET, globalContextItem.getTestGlobalContextItem00B().getSetValue()); + assertEquals(TEST_HASH_MAP, globalContextItem.getTestGlobalContextItem00C().getMapValue()); - assertEquals(LONG_VAL, contextItem.getTestPolicyContextItem001().getLongValue()); - assertDouble(contextItem.getTestPolicyContextItem002().getDoubleValue(), PI_VAL); - assertTrue(contextItem.getTestPolicyContextItem003().getFlag()); - assertEquals(contextItem.getTestPolicyContextItem004().getLongValue(), testDate.getTime()); - assertEquals(TEST_HASH_MAP, contextItem.getTestPolicyContextItem005().getMapValue()); + final AxContextModel externalContextModel = TestContextAlbumFactory.createExternalContextModel(); - final TestGlobalContextItem globalContext = getTestGlobalContextItem(contextDistributor, testDate, tci9, - tciA); + final TestContextDateTzItem tci9A = new TestContextDateTzItem(tci9); + final TestContextDateLocaleItem tciAa = new TestContextDateLocaleItem(tciA); + final TestExternalContextItem externalContext = getTestExternalContextItem(testDate, tci9A, tciAa); - final Map<String, Object> valueMap1 = new HashMap<>(); - valueMap1.put(GLOBAL_CONTEXT_KEY, globalContext); + final Map<String, Object> valueMap2 = new HashMap<>(); + valueMap2.put(EXTERNAL_CONTEXT, externalContext); - final ContextAlbum globalContextAlbum = getContextAlbum(contextDistributor); + contextDistributor.clear(); + contextDistributor.init(new AxArtifactKey("ClearedandInittedDistributor", VERSION)); + contextDistributor.registerModel(externalContextModel); - globalContextAlbum.putAll(valueMap1); + final AxArtifactKey axContextAlbumKey = new AxArtifactKey(EXTERNAL_CONTEXT_ALBUM, VERSION); + final ContextAlbum externalContextAlbum = contextDistributor.createContextAlbum(axContextAlbumKey); + assertNotNull(externalContextAlbum); + externalContextAlbum.setUserArtifactStack(Constants.getAxArtifactKeyArray()); - final TestGlobalContextItem globalContextItem = (TestGlobalContextItem) globalContextAlbum - .get(GLOBAL_CONTEXT_KEY); + externalContextAlbum.putAll(valueMap2); + externalContextAlbum.getAlbumDefinition().setWritable(false); - assertFalse(globalContextItem.getTestGlobalContextItem000().getFlag()); + TestExternalContextItem externalContextItem = (TestExternalContextItem) externalContextAlbum + .get(EXTERNAL_CONTEXT); - assertEquals(BYTE_VAL, globalContextItem.getTestGlobalContextItem001().getByteValue()); + assertFalse(externalContextItem.getTestExternalContextItem000().getFlag()); + assertEquals(BYTE_VAL, externalContextItem.getTestExternalContextItem001().getByteValue()); + assertEquals(INT_VAL, externalContextItem.getTestExternalContextItem002().getIntValue()); - assertEquals(INT_VAL, globalContextItem.getTestGlobalContextItem002().getIntValue()); - assertEquals(LONG_VAL, globalContextItem.getTestGlobalContextItem003().getLongValue()); - assertFloat(FLOAT_VAL, globalContextItem.getTestGlobalContextItem004().getFloatValue()); + assertFloat(LONG_VAL, externalContextItem.getTestExternalContextItem003().getLongValue()); + assertFloat(FLOAT_VAL, externalContextItem.getTestExternalContextItem004().getFloatValue()); - assertDouble(PI_VAL, globalContextItem.getTestGlobalContextItem005().getDoubleValue()); - assertEquals(STRING_GLOBAL_VAL, globalContextItem.getTestGlobalContextItem006().getStringValue()); + assertDouble(PI_VAL, externalContextItem.getTestExternalContextItem005().getDoubleValue()); + assertEquals(STRING_EXT_VAL, externalContextItem.getTestExternalContextItem006().getStringValue()); + assertEquals((Long) testDate.getTime(), externalContextItem.getTestExternalContextItem007().getLongValue()); + assertEquals(testDate, externalContextItem.getTestExternalContextItem008().getDateValue()); + assertEquals(tci9A.getDateValue().getTime(), + externalContextItem.getTestExternalContextItem009().getDateValue().getTime()); - assertEquals((Long) testDate.getTime(), globalContextItem.getTestGlobalContextItem007().getLongValue()); - assertEquals(testDate, globalContextItem.getTestGlobalContextItem008().getDateValue()); - assertEquals(tci9.getDateValue().getTime(), - globalContextItem.getTestGlobalContextItem009().getDateValue().getTime()); + assertEquals(tciAa.getDateValue().getTime(), + externalContextItem.getTestExternalContextItem00A().getDateValue().getTime()); + assertEquals(TEST_TREE_SET, externalContextItem.getTestExternalContextItem00B().getSetValue()); + assertEquals(TEST_HASH_MAP, externalContextItem.getTestExternalContextItem00C().getMapValue()); - assertEquals(tciA.getDateValue().getTime(), - globalContextItem.getTestGlobalContextItem00A().getDateValue().getTime()); + final Collection<Object> mapValues = externalContextAlbum.values(); + assertTrue(externalContextAlbum.values().containsAll(mapValues)); + + // Check that clearing does not work + try { + externalContextAlbum.clear(); + fail(EXCEPTION_MESSAGE); + } catch (final ContextRuntimeException e) { + assertEquals("album \"ExternalContextAlbum:0.0.1\" clear() not allowed on read only albums", + e.getMessage()); + LOGGER.trace(NORMAL_TEST_EXCEPTION, e); + } + + assertEquals(1, externalContextAlbum.size()); + + assertContextAlbumContains(externalContext, externalContextAlbum); + + final Set<Entry<String, Object>> entrySet = externalContextAlbum.entrySet(); + assertEquals(1, entrySet.size()); + + try { + externalContextAlbum.get(null); + } catch (final ContextRuntimeException e) { + assertEquals("album \"ExternalContextAlbum:0.0.1\" null keys are illegal on keys for get()", + e.getMessage()); + LOGGER.trace(NORMAL_TEST_EXCEPTION, e); + } - assertEquals(TEST_TREE_SET, globalContextItem.getTestGlobalContextItem00B().getSetValue()); - assertEquals(TEST_HASH_MAP, globalContextItem.getTestGlobalContextItem00C().getMapValue()); + final Object aObject = externalContextAlbum.get(EXTERNAL_CONTEXT); + assertEquals(aObject, externalContext); - final AxContextModel externalContextModel = TestContextAlbumFactory.createExternalContextModel(); + // put null keys should fail, throws a runtime exception + try { + externalContextAlbum.put(null, null); + } catch (final ContextRuntimeException e) { + assertEquals("album \"ExternalContextAlbum:0.0.1\" null keys are illegal on keys for put()", + e.getMessage()); + LOGGER.trace(NORMAL_TEST_EXCEPTION, e); + } - final TestContextDateTzItem tci9A = new TestContextDateTzItem(tci9); - final TestContextDateLocaleItem tciAa = new TestContextDateLocaleItem(tciA); - final TestExternalContextItem externalContext = getTestExternalContextItem(testDate, tci9A, tciAa); + try { + externalContextAlbum.put("TestExternalContextItem00A", null); + } catch (final ContextRuntimeException e) { + assertEquals(NULL_VALUES_ILLEGAL_TAG + "\"TestExternalContextItem00A\" for put()", e.getMessage()); + LOGGER.trace(NORMAL_TEST_EXCEPTION, e); + } + assertEquals(tciAa, externalContextItem.getTestExternalContextItem00A()); - final Map<String, Object> valueMap2 = new HashMap<>(); - valueMap2.put(EXTERNAL_CONTEXT, externalContext); + // Should return the hash set + assertEquals(TEST_TREE_SET, externalContextItem.getTestExternalContextItem00B().getSetValue()); - contextDistributor.clear(); - contextDistributor.init(new AxArtifactKey("ClearedandInittedDistributor", VERSION)); - contextDistributor.registerModel(externalContextModel); + assertTrue(externalContextAlbum.values().containsAll(mapValues)); - final AxArtifactKey axContextAlbumKey = new AxArtifactKey(EXTERNAL_CONTEXT_ALBUM, VERSION); - final ContextAlbum externalContextAlbum = contextDistributor.createContextAlbum(axContextAlbumKey); - assertNotNull(externalContextAlbum); - externalContextAlbum.setUserArtifactStack(Constants.getAxArtifactKeyArray()); + // Set the write flag back as it should be + externalContextAlbum.getAlbumDefinition().setWritable(true); - externalContextAlbum.putAll(valueMap2); - externalContextAlbum.getAlbumDefinition().setWritable(false); + // Put should return the previous contextItem + final TestExternalContextItem externalContextOther = new TestExternalContextItem(); + externalContextOther.setTestExternalContextItem002(new TestContextIntItem()); + externalContextOther.getTestExternalContextItem002().setIntValue(INT_VAL_2); - TestExternalContextItem externalContextItem = (TestExternalContextItem) externalContextAlbum - .get(EXTERNAL_CONTEXT); + assertTrue(externalContextAlbum.put(EXTERNAL_CONTEXT, externalContextOther).equals(externalContext)); + externalContextItem = (TestExternalContextItem) externalContextAlbum.get(EXTERNAL_CONTEXT); + assertEquals(INT_VAL_2, externalContextItem.getTestExternalContextItem002().getIntValue()); + assertTrue(externalContextAlbum.put(EXTERNAL_CONTEXT, externalContext).equals(externalContextOther)); + externalContextItem = (TestExternalContextItem) externalContextAlbum.get(EXTERNAL_CONTEXT); + assertEquals(INT_VAL_3, externalContextItem.getTestExternalContextItem002().getIntValue()); - assertFalse(externalContextItem.getTestExternalContextItem000().getFlag()); - assertEquals(BYTE_VAL, externalContextItem.getTestExternalContextItem001().getByteValue()); - assertEquals(INT_VAL, externalContextItem.getTestExternalContextItem002().getIntValue()); + try { + externalContextAlbum.put("TestExternalContextItem00A", null); + } catch (final ContextRuntimeException e) { + assert (e.getMessage().equals(NULL_VALUES_ILLEGAL_TAG + "\"TestExternalContextItem00A\" for put()")); + LOGGER.trace(NORMAL_TEST_EXCEPTION, e); + } + assertTrue(externalContextAlbum.get(EXTERNAL_CONTEXT).equals(externalContext)); - assertFloat(LONG_VAL, externalContextItem.getTestExternalContextItem003().getLongValue()); - assertFloat(FLOAT_VAL, externalContextItem.getTestExternalContextItem004().getFloatValue()); + try { + externalContextAlbum.put("TestExternalContextItemFFF", null); + } catch (final ContextRuntimeException e) { + assert (e.getMessage().equals(NULL_VALUES_ILLEGAL_TAG + "\"TestExternalContextItemFFF\" for put()")); + LOGGER.trace(NORMAL_TEST_EXCEPTION, e); + } + assertEquals(1, externalContextAlbum.size()); - assertDouble(PI_VAL, externalContextItem.getTestExternalContextItem005().getDoubleValue()); - assertEquals(STRING_EXT_VAL, externalContextItem.getTestExternalContextItem006().getStringValue()); - assertEquals((Long) testDate.getTime(), externalContextItem.getTestExternalContextItem007().getLongValue()); - assertEquals(testDate, externalContextItem.getTestExternalContextItem008().getDateValue()); - assertEquals(tci9A.getDateValue().getTime(), - externalContextItem.getTestExternalContextItem009().getDateValue().getTime()); - - assertEquals(tciAa.getDateValue().getTime(), - externalContextItem.getTestExternalContextItem00A().getDateValue().getTime()); - assertEquals(TEST_TREE_SET, externalContextItem.getTestExternalContextItem00B().getSetValue()); - assertEquals(TEST_HASH_MAP, externalContextItem.getTestExternalContextItem00C().getMapValue()); - - final Collection<Object> mapValues = externalContextAlbum.values(); - assertTrue(externalContextAlbum.values().containsAll(mapValues)); - - // Check that clearing does not work - try { - externalContextAlbum.clear(); - fail(EXCEPTION_MESSAGE); - } catch (final ContextRuntimeException e) { - assertEquals("album \"ExternalContextAlbum:0.0.1\" clear() not allowed on read only albums", - e.getMessage()); - LOGGER.trace(NORMAL_TEST_EXCEPTION, e); - } - - assertEquals(1, externalContextAlbum.size()); - - assertContextAlbumContains(externalContext, externalContextAlbum); - - final Set<Entry<String, Object>> entrySet = externalContextAlbum.entrySet(); - assertEquals(1, entrySet.size()); - - try { - externalContextAlbum.get(null); - } catch (final ContextRuntimeException e) { - assertEquals("album \"ExternalContextAlbum:0.0.1\" null keys are illegal on keys for get()", - e.getMessage()); - LOGGER.trace(NORMAL_TEST_EXCEPTION, e); - } - - final Object aObject = externalContextAlbum.get(EXTERNAL_CONTEXT); - assertEquals(aObject, externalContext); - - // put null keys should fail, throws a runtime exception - try { - externalContextAlbum.put(null, null); - } catch (final ContextRuntimeException e) { - assertEquals("album \"ExternalContextAlbum:0.0.1\" null keys are illegal on keys for put()", - e.getMessage()); - LOGGER.trace(NORMAL_TEST_EXCEPTION, e); - } - - try { - externalContextAlbum.put("TestExternalContextItem00A", null); - } catch (final ContextRuntimeException e) { - assertEquals(NULL_VALUES_ILLEGAL_TAG + "\"TestExternalContextItem00A\" for put()", e.getMessage()); - LOGGER.trace(NORMAL_TEST_EXCEPTION, e); - } - assertEquals(tciAa, externalContextItem.getTestExternalContextItem00A()); - - // Should return the hash set - assertEquals(TEST_TREE_SET, externalContextItem.getTestExternalContextItem00B().getSetValue()); - - assertTrue(externalContextAlbum.values().containsAll(mapValues)); - - // Set the write flag back as it should be - externalContextAlbum.getAlbumDefinition().setWritable(true); - - // Put should return the previous contextItem - final TestExternalContextItem externalContextOther = new TestExternalContextItem(); - externalContextOther.setTestExternalContextItem002(new TestContextIntItem()); - externalContextOther.getTestExternalContextItem002().setIntValue(INT_VAL_2); - - assertTrue(externalContextAlbum.put(EXTERNAL_CONTEXT, externalContextOther).equals(externalContext)); - externalContextItem = (TestExternalContextItem) externalContextAlbum.get(EXTERNAL_CONTEXT); - assertEquals(INT_VAL_2, externalContextItem.getTestExternalContextItem002().getIntValue()); - assertTrue(externalContextAlbum.put(EXTERNAL_CONTEXT, externalContext).equals(externalContextOther)); - externalContextItem = (TestExternalContextItem) externalContextAlbum.get(EXTERNAL_CONTEXT); - assertEquals(INT_VAL_3, externalContextItem.getTestExternalContextItem002().getIntValue()); - - try { - externalContextAlbum.put("TestExternalContextItem00A", null); - } catch (final ContextRuntimeException e) { - assert (e.getMessage().equals(NULL_VALUES_ILLEGAL_TAG + "\"TestExternalContextItem00A\" for put()")); - LOGGER.trace(NORMAL_TEST_EXCEPTION, e); - } - assertTrue(externalContextAlbum.get(EXTERNAL_CONTEXT).equals(externalContext)); - - try { - externalContextAlbum.put("TestExternalContextItemFFF", null); - } catch (final ContextRuntimeException e) { - assert (e.getMessage().equals(NULL_VALUES_ILLEGAL_TAG + "\"TestExternalContextItemFFF\" for put()")); - LOGGER.trace(NORMAL_TEST_EXCEPTION, e); - } - assertEquals(1, externalContextAlbum.size()); - - try { - externalContextAlbum.put("TestExternalContextItemFFF", null); - } catch (final ContextRuntimeException e) { - assertEquals(NULL_VALUES_ILLEGAL_TAG + "\"TestExternalContextItemFFF\" for put()", e.getMessage()); - LOGGER.trace(NORMAL_TEST_EXCEPTION, e); - } - assertEquals(1, externalContextAlbum.size()); - - // Should ignore remove - externalContextAlbum.remove("TestExternalContextItem017"); - assertEquals(1, externalContextAlbum.size()); - assertEquals(1, externalContextAlbum.values().size()); - assertTrue(externalContextAlbum.values().containsAll(mapValues)); - } catch (final Exception exception) { - LOGGER.error("Unexpected Error:", exception); - throw exception; - } finally { - contextDistributor.clear(); + try { + externalContextAlbum.put("TestExternalContextItemFFF", null); + } catch (final ContextRuntimeException e) { + assertEquals(NULL_VALUES_ILLEGAL_TAG + "\"TestExternalContextItemFFF\" for put()", e.getMessage()); + LOGGER.trace(NORMAL_TEST_EXCEPTION, e); } + assertEquals(1, externalContextAlbum.size()); + + // Should ignore remove + externalContextAlbum.remove("TestExternalContextItem017"); + assertEquals(1, externalContextAlbum.size()); + assertEquals(1, externalContextAlbum.values().size()); + assertTrue(externalContextAlbum.values().containsAll(mapValues)); + contextDistributor.clear(); } private void assertContextAlbumContains(final TestExternalContextItem externalContext, diff --git a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextUpdate.java b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextUpdate.java index d6a55effb..65f50d703 100644 --- a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextUpdate.java +++ b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/distribution/ContextUpdate.java @@ -77,7 +77,7 @@ public class ContextUpdate { * @throws IOException the IO exception * @throws ApexException the apex exception */ - public void testContextUpdate() throws IOException, ApexException { + public void testContextUpdate() throws ApexException { LOGGER.debug("Running TestContextUpdate test . . ."); final Distributor contextDistributor = getDistributor(); diff --git a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContext.java b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContext.java index 87ffa3b40..ee0a1072c 100644 --- a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContext.java +++ b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContext.java @@ -67,7 +67,7 @@ public class ConcurrentContext { * @throws ApexException the Apex exception occurs in handling Apex */ public Map<String, TestContextLongItem> testConcurrentContext() - throws IOException, ApexException { + throws ApexException { try { setupAndVerifyContext(); diff --git a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContextJvm.java b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContextJvm.java index b8e052947..cd2c2ed1f 100644 --- a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContextJvm.java +++ b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContextJvm.java @@ -24,6 +24,7 @@ import com.google.gson.Gson; import java.net.InetAddress; import java.net.NetworkInterface; +import java.net.SocketException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -193,7 +194,7 @@ public final class ConcurrentContextJvm { * * @throws Exception on configuration errors */ - public static void configure() throws Exception { + public static void configure() throws ApexException { System.setProperty("java.net.preferIPv4Stack", "true"); // The JGroups IP address must be set to a real (not loopback) IP address for Infinispan to // work. IN order to @@ -204,7 +205,13 @@ public final class ConcurrentContextJvm { // on a host final TreeSet<String> ipAddressSet = new TreeSet<>(); - final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); + Enumeration<NetworkInterface> nets; + try { + nets = NetworkInterface.getNetworkInterfaces(); + } catch (SocketException e) { + throw new ApexException("cound not get network interfaces for test", e); + } + for (final NetworkInterface netint : Collections.list(nets)) { final Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); for (final InetAddress inetAddress : Collections.list(inetAddresses)) { @@ -216,7 +223,7 @@ public final class ConcurrentContextJvm { } if (ipAddressSet.isEmpty()) { - throw new Exception("cound not find real IP address for test"); + throw new ApexException("cound not find real IP address for test"); } LOGGER.info("Setting jgroups.tcp.address to: " + ipAddressSet.first()); System.setProperty("jgroups.tcp.address", ipAddressSet.first()); diff --git a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContextJvmThread.java b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContextJvmThread.java index dca72391a..9e23175fb 100644 --- a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContextJvmThread.java +++ b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/locking/ConcurrentContextJvmThread.java @@ -102,19 +102,27 @@ public class ConcurrentContextJvmThread implements Runnable, Closeable { LOGGER.info(line); } - // Wait to get exit value - try { - final int exitValue = process.waitFor(); - LOGGER.info("\n\nJVM " + jvm + " finished, exit value is " + exitValue); - } catch (final InterruptedException e) { - LOGGER.warn("Thread was interrupted"); - Thread.currentThread().interrupt(); - } + waitForExitValue(); + } catch (final Exception ioException) { LOGGER.error("Error occured while writing JVM Output for command ", ioException); } } + /** + * Wait for an exit value from the the JVM. + */ + private void waitForExitValue() { + // Wait to get exit value + try { + final int exitValue = process.waitFor(); + LOGGER.info("\n\nJVM " + jvm + " finished, exit value is " + exitValue); + } catch (final InterruptedException e) { + LOGGER.warn("Thread was interrupted"); + Thread.currentThread().interrupt(); + } + } + @Override public void close() { diff --git a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/utils/Constants.java b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/utils/Constants.java index 4761bc6f1..ba620d1f4 100644 --- a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/utils/Constants.java +++ b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/utils/Constants.java @@ -65,6 +65,11 @@ public class Constants { private static final AxArtifactKey[] USED_ARTIFACT_STACK_ARRAY = new AxArtifactKey[] {KEY, KEY2, KEY3}; /** + * Instantiates a new constants. + */ + private Constants() {} + + /** * Gets the ax artifact key array. * * @return the ax artifact key array @@ -72,10 +77,4 @@ public class Constants { public static final AxArtifactKey[] getAxArtifactKeyArray() { return USED_ARTIFACT_STACK_ARRAY; } - - /** - * Instantiates a new constants. - */ - private Constants() {} - } diff --git a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/utils/ZooKeeperServerServiceProvider.java b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/utils/ZooKeeperServerServiceProvider.java index 301e8cc61..1c28388ad 100644 --- a/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/utils/ZooKeeperServerServiceProvider.java +++ b/context/context-test-utils/src/main/java/org/onap/policy/apex/context/test/utils/ZooKeeperServerServiceProvider.java @@ -26,7 +26,7 @@ import java.net.InetSocketAddress; import org.apache.zookeeper.server.NIOServerCnxnFactory; import org.apache.zookeeper.server.ZooKeeperServer; - +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -68,12 +68,30 @@ public class ZooKeeperServerServiceProvider { * @throws IOException the IO exception occurs while setting up Zookeeper server * @throws InterruptedException the interrupted exception occurs while setting up Zookeeper server */ - public void startZookeeperServer() throws IOException, InterruptedException { + public void startZookeeperServer() throws ApexException { LOGGER.info("Starting up ZooKeeperServer using address: {} and port: {}", addr.getAddress(), addr.getPort()); - final ZooKeeperServer server = new ZooKeeperServer(zookeeperDirectory, zookeeperDirectory, 5000); - zookeeperFactory = new NIOServerCnxnFactory(); - zookeeperFactory.configure(addr, 100); - zookeeperFactory.startup(server); + + ZooKeeperServer server; + try { + server = new ZooKeeperServer(zookeeperDirectory, zookeeperDirectory, 5000); + zookeeperFactory = new NIOServerCnxnFactory(); + zookeeperFactory.configure(addr, 100); + } + catch (IOException ioe) { + String message = "exception on starting Zookeeper server"; + LOGGER.warn(message, ioe); + throw new ApexException(message, ioe); + } + + try { + zookeeperFactory.startup(server); + } + catch (InterruptedException | IOException ie) { + String message = "Zookeeper server start failed"; + LOGGER.warn(message, ie); + throw new ApexException(message, ie); + } + } /** diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/ApexEngine.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/ApexEngine.java index b2978a0c0..2c5167d1b 100644 --- a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/ApexEngine.java +++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/ApexEngine.java @@ -43,15 +43,6 @@ import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; */ public interface ApexEngine { /** - * The amount of milliseconds to wait for the current Apex engine to timeout on engine stop - * requests. If the timeout is exceeded, the stop aborts. - */ - int STOP_EXECUTION_WAIT_TIMEOUT = 3000; - - /** The wait increment (or pause time) when waiting for the Apex engine to stop. */ - int APEX_ENGINE_STOP_EXECUTION_WAIT_INCREMENT = 100; - - /** * Update the Apex model to be used by the Apex engine. The engine must be in state "STOPPED" * when the model is updated. The engine will replace the current model with the incoming model * if the model of the engine was previously updated and the value of common context is diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineConstants.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineConstants.java new file mode 100644 index 000000000..e01feb730 --- /dev/null +++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineConstants.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.core.engine.engine.impl; + +/** + * Constants for the Apex engine. + * + */ +public abstract class ApexEngineConstants { + /** + * The amount of milliseconds to wait for the current Apex engine to timeout on engine stop + * requests. If the timeout is exceeded, the stop aborts. + */ + public static final int STOP_EXECUTION_WAIT_TIMEOUT = 3000; + + /** The wait increment (or pause time) when waiting for the Apex engine to stop. */ + public static final int APEX_ENGINE_STOP_EXECUTION_WAIT_INCREMENT = 100; + + /** + * Private constructor to prevent subclassing. + */ + private ApexEngineConstants() { + // Constructor to avoid subclassing + } +} diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImpl.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImpl.java index 6f2bab0b9..022617864 100644 --- a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImpl.java +++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImpl.java @@ -161,8 +161,7 @@ public class ApexEngineImpl implements ApexEngine { LOGGER.entry("start()" + key); if (state != AxEngineState.STOPPED) { - String message = START + key.getId() + "," + state - + ", cannot start engine, engine not in state STOPPED"; + String message = START + key.getId() + "," + state + ", cannot start engine, engine not in state STOPPED"; LOGGER.warn(message); throw new ApexException(message); } @@ -203,7 +202,9 @@ public class ApexEngineImpl implements ApexEngine { LOGGER.entry("stop()->" + key); // Stop the engine if it is in state READY, if it is in state EXECUTING, wait for execution to finish - for (int increment = STOP_EXECUTION_WAIT_TIMEOUT; increment > 0; increment = STOP_EXECUTION_WAIT_TIMEOUT) { + for (int increment = ApexEngineConstants.STOP_EXECUTION_WAIT_TIMEOUT; + increment > 0; + increment = ApexEngineConstants.STOP_EXECUTION_WAIT_TIMEOUT) { synchronized (state) { switch (state) { // Already stopped diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/Executor.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/Executor.java index 9941c6de8..22a23d062 100644 --- a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/Executor.java +++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/Executor.java @@ -23,6 +23,7 @@ package org.onap.policy.apex.core.engine.executor; import org.onap.policy.apex.context.ContextException; import org.onap.policy.apex.core.engine.ExecutorParameters; import org.onap.policy.apex.core.engine.executor.exception.StateMachineException; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; /** @@ -70,7 +71,7 @@ public interface Executor<I, O, S, C> { * @throws StateMachineException on an execution error * @throws ContextException on context errors */ - O execute(long executionId, I incomingEntity) throws StateMachineException, ContextException; + O execute(long executionId, I incomingEntity) throws ApexException; /** * Carry out the preparatory work for execution. @@ -80,7 +81,7 @@ public interface Executor<I, O, S, C> { * @throws StateMachineException on an execution error * @throws ContextException on context errors */ - void executePre(long executionId, I incomingEntity) throws StateMachineException, ContextException; + void executePre(long executionId, I incomingEntity) throws ApexException; /** * Carry out the post work for execution, the returning entity should be set by the child @@ -91,7 +92,7 @@ public interface Executor<I, O, S, C> { * @throws StateMachineException on an execution error * @throws ContextException On context errors */ - void executePost(boolean returnValue) throws StateMachineException, ContextException; + void executePost(boolean returnValue) throws ApexException; /** * Cleans up after processing. diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskExecutor.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskExecutor.java index 814f257f7..2a62f3ae2 100644 --- a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskExecutor.java +++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskExecutor.java @@ -181,23 +181,7 @@ public abstract class TaskExecutor // Copy any unset fields from the input to the output if their data type and names are // identical for (final String field : axTask.getOutputFields().keySet()) { - // Check if the field exists and is not set on the output - if (!getOutgoing().containsKey(field) || getOutgoing().get(field) != null) { - continue; - } - - // This field is not in the output, check if it's on the input and is the same type - // (Note here, the output - // field definition has to exist so it's not - // null checked) - final AxInputField inputFieldDef = axTask.getInputFields().get(field); - final AxOutputField outputFieldDef = axTask.getOutputFields().get(field); - if (inputFieldDef == null || !inputFieldDef.getSchema().equals(outputFieldDef.getSchema())) { - continue; - } - - // We have an input field that matches our output field, copy the value across - getOutgoing().put(field, getIncoming().get(field)); + copyInputField2Output(field); } // Finally, check that the outgoing fields have all the output fields defined for this state @@ -233,6 +217,32 @@ public abstract class TaskExecutor LOGGER.debug(message); } + /** + * If the input field exists on the output and it is not set in the task, then it should + * be copied to the output. + * + * @param field the input field + */ + private void copyInputField2Output(String field) { + // Check if the field exists and is not set on the output + if (!getOutgoing().containsKey(field) || getOutgoing().get(field) != null) { + return; + } + + // This field is not in the output, check if it's on the input and is the same type + // (Note here, the output + // field definition has to exist so it's not + // null checked) + final AxInputField inputFieldDef = axTask.getInputFields().get(field); + final AxOutputField outputFieldDef = axTask.getOutputFields().get(field); + if (inputFieldDef == null || !inputFieldDef.getSchema().equals(outputFieldDef.getSchema())) { + return; + } + + // We have an input field that matches our output field, copy the value across + getOutgoing().put(field, getIncoming().get(field)); + } + /* * (non-Javadoc) * diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java index c70c9feb6..9dbfe266f 100644 --- a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java @@ -38,6 +38,9 @@ public class AnomalyDetection implements Serializable { private boolean firstRound = true; private int frequency = 0; + private List<Double> anomalyScores = new LinkedList<>(); + private List<Double> frequencyForecasted; + /** * The Constructor creates an AnomalyDetection instance. */ @@ -46,9 +49,6 @@ public class AnomalyDetection implements Serializable { frequency = 0; } - private List<Double> anomalyScores = new LinkedList<>(); - private List<Double> frequencyForecasted; - /** * Checks if the AnomalyDetection instance is initialized. * diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicyDecideTaskSelectionLogic.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicyDecideTaskSelectionLogic.java index 5ee114e0e..ffbaf5905 100644 --- a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicyDecideTaskSelectionLogic.java +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicyDecideTaskSelectionLogic.java @@ -47,6 +47,13 @@ public class AnomalyDetectionPolicyDecideTaskSelectionLogic { private static final double ANOMALY_SENSITIVITY = 0.05; private static final int FREQUENCY = 360; + /* + * Some utility methods + */ + // exponential = 2(n+1) + private static final double EMA_EXPONENT = 2.0 / (7.0 + 1.0); + private static final double EMA_EXPONENT_1 = (1.0 - EMA_EXPONENT); + /** * A map to hold the Anomaly degree/levels/probabilities required for each task.<br> * If there is no task defined for a calculated anomaly-degree, then the default task is @@ -295,13 +302,6 @@ public class AnomalyDetectionPolicyDecideTaskSelectionLogic { return pvalue; } - /* - * Some utility methods - */ - // exponential = 2(n+1) - private static final double EMA_EXPONENT = 2.0 / (7.0 + 1.0); - private static final double EMA_EXPONENT_1 = (1.0 - EMA_EXPONENT); - /** * exponential moving average. * diff --git a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaHelper.java b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaHelper.java index ed2b521c4..015d9ea30 100644 --- a/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaHelper.java +++ b/plugins/plugins-context/plugins-context-schema/plugins-context-schema-avro/src/main/java/org/onap/policy/apex/plugins/context/schema/avro/AvroSchemaHelper.java @@ -166,21 +166,7 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { private String getStringObject(final Object object) { try { if (isObjectString(object)) { - String objectString = object.toString().trim(); - if (objectString.length() == 0) { - return "\"\""; - } else if (objectString.length() == 1) { - return "\"" + objectString + "\""; - } else { - // All strings must be quoted for decoding - if (objectString.charAt(0) != '"') { - objectString = '"' + objectString; - } - if (objectString.charAt(objectString.length() - 1) != '"') { - objectString += '"'; - } - } - return objectString; + return getObjectString(object); } else { return (String) object; } @@ -194,6 +180,30 @@ public class AvroSchemaHelper extends AbstractSchemaHelper { } } + /** + * Get a string object. + * + * @param object the string object + * @return the string + */ + private String getObjectString(final Object object) { + String objectString = object.toString().trim(); + if (objectString.length() == 0) { + return "\"\""; + } else if (objectString.length() == 1) { + return "\"" + objectString + "\""; + } else { + // All strings must be quoted for decoding + if (objectString.charAt(0) != '"') { + objectString = '"' + objectString; + } + if (objectString.charAt(objectString.length() - 1) != '"') { + objectString += '"'; + } + } + return objectString; + } + private boolean isObjectString(final Object object) { return object != null && avroSchema.getType().equals(Schema.Type.STRING); } diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JmsCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JmsCarrierTechnologyParameters.java index 8b120ca3a..d4cb2ab9a 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JmsCarrierTechnologyParameters.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/JmsCarrierTechnologyParameters.java @@ -328,38 +328,38 @@ public class JmsCarrierTechnologyParameters extends CarrierTechnologyParameters public GroupValidationResult validate() { final GroupValidationResult result = super.validate(); - if (initialContextFactory == null || initialContextFactory.trim().length() == 0) { + if (isNullOrBlank(initialContextFactory)) { result.setResult("initialContextFactory", ValidationStatus.INVALID, "initialContextFactory must be specified as a string that is a class that implements the " + "interface org.jboss.naming.remote.client.InitialContextFactory"); } - if (providerUrl == null || providerUrl.trim().length() == 0) { + if (isNullOrBlank(providerUrl)) { result.setResult("providerUrl", ValidationStatus.INVALID, "providerUrl must be specified as a URL string that specifies the location of " + "configuration information for the service provider to use " + "such as remote://localhost:4447"); } - if (securityPrincipal == null || securityPrincipal.trim().length() == 0) { + if (isNullOrBlank(securityPrincipal)) { result.setResult("securityPrincipal", ValidationStatus.INVALID, "securityPrincipal must be specified the identity of the principal for authenticating " + "the caller to the service"); } - if (securityCredentials == null || securityCredentials.trim().length() == 0) { + if (isNullOrBlank(securityCredentials)) { result.setResult("securityCredentials", ValidationStatus.INVALID, " securityCredentials must be specified as the credentials of the " + "principal for authenticating the caller to the service"); } - if (producerTopic == null || producerTopic.trim().length() == 0) { + if (isNullOrBlank(producerTopic)) { result.setResult("producerTopic", ValidationStatus.INVALID, " producerTopic must be a string that identifies the JMS topic " + "on which Apex will send events"); } - if (consumerTopic == null || consumerTopic.trim().length() == 0) { + if (isNullOrBlank(consumerTopic)) { result.setResult("consumerTopic", ValidationStatus.INVALID, " consumerTopic must be a string that identifies the JMS topic " + "on which Apex will recieve events"); @@ -372,4 +372,14 @@ public class JmsCarrierTechnologyParameters extends CarrierTechnologyParameters return result; } + + /** + * Check if the string is null or blank. + * + * @param stringValue the string value + * @return + */ + private boolean isNullOrBlank(final String stringValue) { + return stringValue == null || stringValue.trim().length() == 0; + } } diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaConsumer.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaConsumer.java index 94ac2bcca..affd10ccb 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaConsumer.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/ApexKafkaConsumer.java @@ -166,10 +166,7 @@ public class ApexKafkaConsumer implements ApexEventConsumer, Runnable { final ConsumerRecords<String, String> records = kafkaConsumer.poll(kafkaConsumerProperties.getConsumerPollDuration().toMillis()); for (final ConsumerRecord<String, String> record : records) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("event received for {} for forwarding to Apex engine : {} {}", - this.getClass().getName() + ":" + this.name, record.key(), record.value()); - } + traceIfTraceEnabled(record); eventReceiver.receiveEvent(record.value()); } } catch (final Exception e) { @@ -182,6 +179,18 @@ public class ApexKafkaConsumer implements ApexEventConsumer, Runnable { } } + /** + * Trace a record if trace is enabled. + * + * @param record the record to trace + */ + private void traceIfTraceEnabled(final ConsumerRecord<String, String> record) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("event received for {} for forwarding to Apex engine : {} {}", + this.getClass().getName() + ":" + this.name, record.key(), record.value()); + } + } + /* * (non-Javadoc) * diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KafkaCarrierTechnologyParameters.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KafkaCarrierTechnologyParameters.java index 7c24ce1aa..851741611 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KafkaCarrierTechnologyParameters.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-kafka/src/main/java/org/onap/policy/apex/plugins/event/carrier/kafka/KafkaCarrierTechnologyParameters.java @@ -62,10 +62,8 @@ public class KafkaCarrierTechnologyParameters extends CarrierTechnologyParameter private static final String DEFAULT_PROD_TOPIC = "apex-out"; private static final int DEFAULT_CONS_POLL_TIME = 100; private static final String[] DEFAULT_CONS_TOPICLIST = {"apex-in"}; - private static final String DEFAULT_KEY_SERZER = "org.apache.kafka.common.serialization.StringSerializer"; - private static final String DEFAULT_VAL_SERZER = "org.apache.kafka.common.serialization.StringSerializer"; - private static final String DEFAULT_KEY_DESZER = "org.apache.kafka.common.serialization.StringDeserializer"; - private static final String DEFAULT_VALUE_DESZER = "org.apache.kafka.common.serialization.StringDeserializer"; + private static final String DEFAULT_STRING_SERZER = "org.apache.kafka.common.serialization.StringSerializer"; + private static final String DEFAULT_STRING_DESZER = "org.apache.kafka.common.serialization.StringDeserializer"; // Parameter property map tokens private static final String PROPERTY_BOOTSTRAP_SERVERS = "bootstrap.servers"; @@ -97,10 +95,10 @@ public class KafkaCarrierTechnologyParameters extends CarrierTechnologyParameter private String producerTopic = DEFAULT_PROD_TOPIC; private int consumerPollTime = DEFAULT_CONS_POLL_TIME; private String[] consumerTopicList = DEFAULT_CONS_TOPICLIST; - private String keySerializer = DEFAULT_KEY_SERZER; - private String valueSerializer = DEFAULT_VAL_SERZER; - private String keyDeserializer = DEFAULT_KEY_DESZER; - private String valueDeserializer = DEFAULT_VALUE_DESZER; + private String keySerializer = DEFAULT_STRING_SERZER; + private String valueSerializer = DEFAULT_STRING_SERZER; + private String keyDeserializer = DEFAULT_STRING_DESZER; + private String valueDeserializer = DEFAULT_STRING_DESZER; // @formatter:on /** @@ -325,6 +323,23 @@ public class KafkaCarrierTechnologyParameters extends CarrierTechnologyParameter public GroupValidationResult validate() { final GroupValidationResult result = super.validate(); + validateStringParameters(result); + + validateNumericParameters(result); + + validateConsumerTopicList(result); + + validateSerializersAndDeserializers(result); + + return result; + } + + /** + * Validate that string parameters are correct. + * + * @param result the result of the validation + */ + private void validateStringParameters(final GroupValidationResult result) { if (isNullOrBlank(bootstrapServers)) { result.setResult("bootstrapServers", ValidationStatus.INVALID, "not specified, must be specified as a string of form host:port"); @@ -335,6 +350,22 @@ public class KafkaCarrierTechnologyParameters extends CarrierTechnologyParameter "not specified, must be specified as a string with values [0|1|all]"); } + if (isNullOrBlank(groupId)) { + result.setResult("groupId", ValidationStatus.INVALID, SPECIFY_AS_STRING_MESSAGE); + } + + if (isNullOrBlank(producerTopic)) { + result.setResult("producerTopic", ValidationStatus.INVALID, + SPECIFY_AS_STRING_MESSAGE); + } + } + + /** + * Check if numeric parameters are valid. + * + * @param result the result of the validation + */ + private void validateNumericParameters(final GroupValidationResult result) { if (retries < 0) { result.setResult(PROPERTY_RETRIES, ValidationStatus.INVALID, "[" + retries + "] invalid, must be specified as retries >= 0"); @@ -355,10 +386,6 @@ public class KafkaCarrierTechnologyParameters extends CarrierTechnologyParameter "[" + bufferMemory + "] invalid, must be specified as bufferMemory >= 0"); } - if (isNullOrBlank(groupId)) { - result.setResult("groupId", ValidationStatus.INVALID, SPECIFY_AS_STRING_MESSAGE); - } - if (autoCommitTime < 0) { result.setResult("autoCommitTime", ValidationStatus.INVALID, "[" + autoCommitTime + "] invalid, must be specified as autoCommitTime >= 0"); @@ -369,18 +396,18 @@ public class KafkaCarrierTechnologyParameters extends CarrierTechnologyParameter "[" + sessionTimeout + "] invalid, must be specified as sessionTimeout >= 0"); } - if (isNullOrBlank(producerTopic)) { - result.setResult("producerTopic", ValidationStatus.INVALID, - SPECIFY_AS_STRING_MESSAGE); - } - if (consumerPollTime < 0) { result.setResult("consumerPollTime", ValidationStatus.INVALID, "[" + consumerPollTime + "] invalid, must be specified as consumerPollTime >= 0"); } + } - validateConsumerTopicList(result); - + /** + * Validate the serializers and deserializers. + * + * @param result the result of the validation. + */ + private void validateSerializersAndDeserializers(final GroupValidationResult result) { if (isNullOrBlank(keySerializer)) { result.setResult("keySerializer", ValidationStatus.INVALID, SPECIFY_AS_STRING_MESSAGE); @@ -400,8 +427,6 @@ public class KafkaCarrierTechnologyParameters extends CarrierTechnologyParameter result.setResult("valueDeserializer", ValidationStatus.INVALID, SPECIFY_AS_STRING_MESSAGE); } - - return result; } private void validateConsumerTopicList(final GroupValidationResult result) { diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/Apex2YamlEventConverter.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/Apex2YamlEventConverter.java index 4bf10e4ae..f3afdde32 100644 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/Apex2YamlEventConverter.java +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/main/java/org/onap/policy/apex/plugins/event/protocol/yaml/Apex2YamlEventConverter.java @@ -267,6 +267,23 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { version = eventDefinition.getKey().getVersion(); } + String namespace = getEventHeaderNamespace(yamlMap, name, eventDefinition); + + String source = getEventHeaderSource(yamlMap, eventDefinition); + + String target = getHeaderTarget(yamlMap, eventDefinition); + + return new ApexEvent(name, version, namespace, source, target); + } + + /** + * Get the event header name space. + * + * @param yamlMap the YAML map to read from + * @param eventDefinition the event definition + * @return the event header name space + */ + private String getEventHeaderNamespace(final Map<?, ?> yamlMap, String name, final AxEvent eventDefinition) { // Check the name space is OK if it is defined, if not, use the name space from the model String namespace = getYamlStringField(yamlMap, ApexEvent.NAMESPACE_HEADER_FIELD, yamlPars.getNameSpaceAlias(), ApexEvent.NAMESPACE_REGEXP, false); @@ -279,22 +296,41 @@ public class Apex2YamlEventConverter implements ApexEventProtocolConverter { } else { namespace = eventDefinition.getNameSpace(); } + return namespace; + } + /** + * Get the event header source. + * + * @param yamlMap the YAML map to read from + * @param eventDefinition the event definition + * @return the event header source + */ + private String getEventHeaderSource(final Map<?, ?> yamlMap, final AxEvent eventDefinition) { // For source, use the defined source only if the source is not found on the incoming event String source = getYamlStringField(yamlMap, ApexEvent.SOURCE_HEADER_FIELD, yamlPars.getSourceAlias(), ApexEvent.SOURCE_REGEXP, false); if (source == null) { source = eventDefinition.getSource(); } + return source; + } + /** + * Get the event header target. + * + * @param yamlMap the YAML map to read from + * @param eventDefinition the event definition + * @return the event header target + */ + private String getHeaderTarget(final Map<?, ?> yamlMap, final AxEvent eventDefinition) { // For target, use the defined source only if the source is not found on the incoming event String target = getYamlStringField(yamlMap, ApexEvent.TARGET_HEADER_FIELD, yamlPars.getTargetAlias(), ApexEvent.TARGET_REGEXP, false); if (target == null) { target = eventDefinition.getTarget(); } - - return new ApexEvent(name, version, namespace, source, target); + return target; } /** diff --git a/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskExecutor.java b/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskExecutor.java index 39ca0dc43..bddb63b42 100644 --- a/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskExecutor.java +++ b/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskExecutor.java @@ -100,23 +100,7 @@ public class JythonTaskExecutor extends TaskExecutor { // Set up the Jython engine interpreter.set("executor", getExecutionContext()); interpreter.exec(compiled); - try { - final Object ret = interpreter.get("returnValue", java.lang.Boolean.class); - if (ret == null) { - LOGGER.error("execute: task logic failed to set a return value for task \"" - + getSubject().getKey().getId() + "\""); - throw new StateMachineException("execute: task logic failed to set a return value for task \"" - + getSubject().getKey().getId() + "\""); - } - returnValue = (Boolean) ret; - } catch (NullPointerException | ClassCastException e) { - LOGGER.error("execute: task selection logic failed to set a correct return value for state \"" - + getSubject().getKey().getId() + "\"", e); - throw new StateMachineException( - "execute: task selection logic failed to set a return value for state \"" - + getSubject().getKey().getId() + "\"", - e); - } + returnValue = handleInterpreterResult(); } /* */ } catch (final Exception e) { @@ -137,6 +121,35 @@ public class JythonTaskExecutor extends TaskExecutor { } /** + * Handle the result returned by the interpreter. + * + * @return true if the result was successful + * @throws StateMachineException on interpreter failures + */ + private boolean handleInterpreterResult() throws StateMachineException { + boolean returnValue = false; + + try { + final Object ret = interpreter.get("returnValue", java.lang.Boolean.class); + if (ret == null) { + LOGGER.error("execute: task logic failed to set a return value for task \"" + + getSubject().getKey().getId() + "\""); + throw new StateMachineException("execute: task logic failed to set a return value for task \"" + + getSubject().getKey().getId() + "\""); + } + returnValue = (Boolean) ret; + } catch (NullPointerException | ClassCastException e) { + LOGGER.error("execute: task selection logic failed to set a correct return value for state \"" + + getSubject().getKey().getId() + "\"", e); + throw new StateMachineException( + "execute: task selection logic failed to set a return value for state \"" + + getSubject().getKey().getId() + "\"", + e); + } + return returnValue; + } + + /** * Cleans up the task after processing. * * @throws StateMachineException thrown when a state machine execution error occurs diff --git a/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskSelectExecutor.java b/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskSelectExecutor.java index 3ff061fa4..9a2433122 100644 --- a/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskSelectExecutor.java +++ b/plugins/plugins-executor/plugins-executor-jython/src/main/java/org/onap/policy/apex/plugins/executor/jython/JythonTaskSelectExecutor.java @@ -103,25 +103,7 @@ public class JythonTaskSelectExecutor extends TaskSelectExecutor { // Set up the Jython engine interpreter.set("executor", getExecutionContext()); interpreter.exec(compiled); - - try { - final Object ret = interpreter.get("returnValue", java.lang.Boolean.class); - if (ret == null) { - LOGGER.error(TSL_FAILED_PREFIX - + getSubject().getKey().getId() + "\""); - throw new StateMachineException( - TSL_FAILED_PREFIX - + getSubject().getKey().getId() + "\""); - } - returnValue = (Boolean) ret; - } catch (NullPointerException | ClassCastException e) { - LOGGER.error("execute: task selection logic failed to set a correct return value for state \"" - + getSubject().getKey().getId() + "\"", e); - throw new StateMachineException( - TSL_FAILED_PREFIX - + getSubject().getKey().getId() + "\"", - e); - } + returnValue = handleInterpreterResult(); } /* */ } catch (final Exception e) { @@ -143,6 +125,36 @@ public class JythonTaskSelectExecutor extends TaskSelectExecutor { } /** + * Handle the result returned by the interpreter. + * + * @return true if the result was successful + * @throws StateMachineException on interpreter errors + */ + private boolean handleInterpreterResult() throws StateMachineException { + boolean returnValue = false; + + try { + final Object ret = interpreter.get("returnValue", java.lang.Boolean.class); + if (ret == null) { + LOGGER.error(TSL_FAILED_PREFIX + + getSubject().getKey().getId() + "\""); + throw new StateMachineException( + TSL_FAILED_PREFIX + + getSubject().getKey().getId() + "\""); + } + returnValue = (Boolean) ret; + } catch (NullPointerException | ClassCastException e) { + LOGGER.error("execute: task selection logic failed to set a correct return value for state \"" + + getSubject().getKey().getId() + "\"", e); + throw new StateMachineException( + TSL_FAILED_PREFIX + + getSubject().getKey().getId() + "\"", + e); + } + return returnValue; + } + + /** * Cleans up the task after processing. * * @throws StateMachineException thrown when a state machine execution error occurs diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java index 5a0d11d4c..368305efa 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java @@ -102,7 +102,7 @@ public class ApexEvent extends HashMap<String, Object> implements Serializable { public static final String SOURCE_REGEXP = "^$|[A-Za-z0-9\\.\\-_:]+"; /** The target of an Apex event must match this regular expression. */ - public static final String TARGET_REGEXP = "^$|[A-Za-z0-9\\.\\-_:]+"; + public static final String TARGET_REGEXP = SOURCE_REGEXP; // The fields of the event // @formatter:off @@ -121,16 +121,6 @@ public class ApexEvent extends HashMap<String, Object> implements Serializable { private String exceptionMessage; /** - * Private utility to get the next candidate value for a Execution ID. This value will always be - * unique in a single JVM - * - * @return the next candidate value for a Execution ID - */ - private static synchronized long getNextExecutionId() { - return nextExecutionID.getAndIncrement(); - } - - /** * Instantiates a new apex event. * * @param name the name of the event @@ -152,6 +142,16 @@ public class ApexEvent extends HashMap<String, Object> implements Serializable { } /** + * Private utility to get the next candidate value for a Execution ID. This value will always be + * unique in a single JVM + * + * @return the next candidate value for a Execution ID + */ + private static synchronized long getNextExecutionId() { + return nextExecutionID.getAndIncrement(); + } + + /** * Check that a field of the event is valid. * * @param fieldName the name of the field to check diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java index 32f87a7cc..fbb1ec053 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java @@ -51,7 +51,7 @@ public class ApexPeriodicEventGenerator extends TimerTask { public static final String PERIODIC_EVENT_SOURCE = "internal"; /** The target of the periodic event. */ - public static final String PERIODIC_EVENT_TARGET = "internal"; + public static final String PERIODIC_EVENT_TARGET = PERIODIC_EVENT_SOURCE; /** * The field name in the periodic event for the delay between occurrences of the periodic event. diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java index 532fdb9c7..77be038e5 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java @@ -94,7 +94,7 @@ public class ApexEventMarshaller implements ApexEventListener, Runnable { * @throws ApexActivatorException on errors initializing the producer * @throws ApexEventException on errors initializing event handling */ - public void init() throws ApexActivatorException, ApexEventException { + public void init() throws ApexEventException { // Create the producer for sending events and the converter for transforming events producer = new EventProducerFactory().createProducer(name, producerParameters); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java index 1d1b64e37..97aa25fbe 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java @@ -216,15 +216,10 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { try { final List<ApexEvent> apexEventList = converter.toApexEvent(consumerParameters.getEventName(), event); for (final ApexEvent apexEvent : apexEventList) { - // Check if we are filtering events on this unmarshaler, if so check the event name - // against the filter - if (consumerParameters.isSetEventNameFilter() - && !apexEvent.getName().matches(consumerParameters.getEventNameFilter())) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("onMessage(): event {} not processed, filtered out by filter", apexEvent, - consumerParameters.getEventNameFilter()); - } + isEventFilteredOut(apexEvent); + // Check if this event is filtered out by the incoming filter + if (isEventFilteredOut(apexEvent)) { // Ignore this event continue; } @@ -252,6 +247,29 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { } /** + * Check if an event is filtered out and ignored. + * + * @param apexEvent the event to check + */ + private boolean isEventFilteredOut(final ApexEvent apexEvent) { + // Check if we are filtering events on this unmarshaler, if so check the event name + // against the filter + if (consumerParameters.isSetEventNameFilter() + && !apexEvent.getName().matches(consumerParameters.getEventNameFilter())) { + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("onMessage(): event {} not processed, filtered out by filter", apexEvent, + consumerParameters.getEventNameFilter()); + } + + return true; + } + else { + return false; + } + } + + /** * Run a thread that runs forever (well until system termination anyway) and listens for incoming events on the * queue. */ diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java index dc5e91979..56b3b84c4 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java @@ -714,9 +714,8 @@ final class EngineWorker implements EngineService { try { if (event != null) { - if (debugEnabled) { - LOGGER.debug("Trigger Event {} forwarded to the Apex engine", event); - } + debugEventIfDebugEnabled(event); + final EnEvent enevent = apexEnEventConverter.fromApexEvent(event); engine.handleEvent(enevent); } @@ -729,5 +728,16 @@ final class EngineWorker implements EngineService { } LOGGER.debug("Engine {} completed processing", engineWorkerKey); } + + /** + * Debug the event if debug is enabled. + * + * @param event the event to debug + */ + private void debugEventIfDebugEnabled(ApexEvent event) { + if (debugEnabled) { + LOGGER.debug("Trigger Event {} forwarded to the Apex engine", event); + } + } } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java index 907baad40..4bbc5fc85 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java @@ -55,6 +55,15 @@ public class ApexParameters implements ParameterGroup { private static final String EVENT_OUTPUT_PARAMETERS_STRING = "eventOutputParameters"; private static final String FOR_PEERED_MODE_STRING = " for peered mode "; + // Parameters for the engine service and the engine threads in the engine service + private EngineServiceParameters engineServiceParameters; + + // Parameters for the event outputs that Apex will use to send events on its outputs + private Map<String, EventHandlerParameters> eventOutputParameters = new LinkedHashMap<>(); + + // Parameters for the event inputs that Apex will use to receive events on its inputs + private Map<String, EventHandlerParameters> eventInputParameters = new LinkedHashMap<>(); + /** * Constructor to create an apex parameters instance and register the instance with the parameter service. */ @@ -65,15 +74,6 @@ public class ApexParameters implements ParameterGroup { this.name = ApexParameterConstants.MAIN_GROUP_NAME; } - // Parameters for the engine service and the engine threads in the engine service - private EngineServiceParameters engineServiceParameters; - - // Parameters for the event outputs that Apex will use to send events on its outputs - private Map<String, EventHandlerParameters> eventOutputParameters = new LinkedHashMap<>(); - - // Parameters for the event inputs that Apex will use to receive events on its inputs - private Map<String, EventHandlerParameters> eventInputParameters = new LinkedHashMap<>(); - /** * Gets the parameters for the Apex engine service. * diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventConverter.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventConverter.java index 471f90425..4dbdc8cce 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventConverter.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventConverter.java @@ -33,7 +33,6 @@ import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParame * */ public class TestJsonEventConverter { - @Test public void testJsonEventConverter() { Apex2JsonEventConverter converter = new Apex2JsonEventConverter(); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandler.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandler.java index a9165d792..6e462a3e1 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandler.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandler.java @@ -93,6 +93,7 @@ public class TestJsonEventHandler { @AfterClass public static void teardownDefaultSchemaParameters() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); + ModelService.clear(); } /** diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandlerForPojo.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandlerForPojo.java index 1dae4c0f4..38f6da1b0 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandlerForPojo.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/TestJsonEventHandlerForPojo.java @@ -36,6 +36,7 @@ import org.onap.policy.apex.context.parameters.SchemaParameters; import org.onap.policy.apex.model.basicmodel.concepts.ApexException; import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; +import org.onap.policy.apex.model.basicmodel.service.ModelService; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; import org.onap.policy.apex.model.utilities.TextFileUtils; import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.Apex2JsonEventConverter; @@ -89,6 +90,7 @@ public class TestJsonEventHandlerForPojo { @AfterClass public static void teardownDefaultSchemaParameters() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); + ModelService.clear(); } /** diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/EvalDomainModelFactory.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/EvalDomainModelFactory.java index 25c7fa16e..70d723567 100644 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/EvalDomainModelFactory.java +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/EvalDomainModelFactory.java @@ -65,6 +65,8 @@ public class EvalDomainModelFactory { private static final String EVENT = "Event"; private static final String TASK_SELECTION_LOGIC = "TaskSelectionLogic"; private static final String JYTHON = "JYTHON"; + private static final String JRUBY = "JRUBY"; + private static final String MVEL = "MVEL"; private static final String ORIENT = "Orient"; private static final String STATE_NAME = "<STATE_NAME>"; private static final String OBSERVE = "Observe"; @@ -219,12 +221,12 @@ public class EvalDomainModelFactory { obTask.duplicateInputFields(event0000.getParameterMap()); obTask.duplicateOutputFields(event0001.getParameterMap()); final AxTaskLogic obAxLogic = new AxTaskLogic(obTask.getKey(), TASK_LOGIC, - (justOneLang == null ? "JRUBY" : justOneLang), logicReader); + (justOneLang == null ? JRUBY : justOneLang), logicReader); obAxLogic.setLogic(obAxLogic.getLogic().replaceAll(STATE_NAME, OBSERVE) .replaceAll(TASK_NAME, obTask.getKey().getName()).replaceAll(STATE_NUMBER, "1")); obTask.setTaskLogic(obAxLogic); - final AxTask orTask = new AxTask(new AxArtifactKey("Task_Orient_0", "0.0.1")); + final AxTask orTask = new AxTask(new AxArtifactKey("Task_Orient_0", DEFAULT_VERSION)); orTask.duplicateInputFields(event0001.getParameterMap()); orTask.duplicateOutputFields(event0002.getParameterMap()); final AxTaskLogic orAxLogic = new AxTaskLogic(orTask.getKey(), TASK_LOGIC, @@ -233,16 +235,16 @@ public class EvalDomainModelFactory { .replaceAll(TASK_NAME, orTask.getKey().getName()).replaceAll(STATE_NUMBER, "2")); orTask.setTaskLogic(orAxLogic); - final AxTask dTask = new AxTask(new AxArtifactKey("Task_Decide_0", "0.0.1")); + final AxTask dTask = new AxTask(new AxArtifactKey("Task_Decide_0", DEFAULT_VERSION)); dTask.duplicateInputFields(event0002.getParameterMap()); dTask.duplicateOutputFields(event0003.getParameterMap()); final AxTaskLogic dAxLogic = new AxTaskLogic(dTask.getKey(), TASK_LOGIC, - (justOneLang == null ? "MVEL" : justOneLang), logicReader); + (justOneLang == null ? MVEL : justOneLang), logicReader); dAxLogic.setLogic(dAxLogic.getLogic().replaceAll(STATE_NAME, ORIENT) .replaceAll(TASK_NAME, dTask.getKey().getName()).replaceAll(STATE_NUMBER, "3")); dTask.setTaskLogic(dAxLogic); - final AxTask aTask = new AxTask(new AxArtifactKey("Task_Act_0", "0.0.1")); + final AxTask aTask = new AxTask(new AxArtifactKey("Task_Act_0", DEFAULT_VERSION)); aTask.duplicateInputFields(event0003.getParameterMap()); aTask.duplicateOutputFields(event0004.getParameterMap()); final AxTaskLogic aAxLogic = new AxTaskLogic(aTask.getKey(), TASK_LOGIC, @@ -261,20 +263,8 @@ public class EvalDomainModelFactory { final Set<AxArtifactKey> decTasks = new TreeSet<>(); final Set<AxArtifactKey> actTasks = new TreeSet<>(); - for (final AxTask task : tasks.getTaskMap().values()) { - if (task.getKey().getName().contains(OBSERVE)) { - obTasks.add(task.getKey()); - } - if (task.getKey().getName().contains(ORIENT)) { - orTasks.add(task.getKey()); - } - if (task.getKey().getName().contains("Decide")) { - decTasks.add(task.getKey()); - } - if (task.getKey().getName().contains("Act")) { - actTasks.add(task.getKey()); - } - } + addOodaTasks(tasks, obTasks, orTasks, decTasks, actTasks); + final List<Set<AxArtifactKey>> taskReferenceList = new ArrayList<>(); taskReferenceList.add(obTasks); taskReferenceList.add(orTasks); @@ -299,23 +289,24 @@ public class EvalDomainModelFactory { p0defaultTaskList.add(tasks.get("Task_Decide_0").getKey()); p0defaultTaskList.add(tasks.get("Task_Act_0").getKey()); - final AxPolicy policy0 = new AxPolicy(new AxArtifactKey("OODAPolicy_0", "0.0.1")); - final List<String> axLogicExecutorTypeList = Arrays.asList((justOneLang == null ? JAVASCRIPT : justOneLang), - (justOneLang == null ? "MVEL" : justOneLang), (justOneLang == null ? JYTHON : justOneLang), - (justOneLang == null ? "JRUBY" : justOneLang)); + final AxPolicy policy0 = new AxPolicy(new AxArtifactKey("OODAPolicy_0", DEFAULT_VERSION)); + final List<String> axLogicExecutorTypeList = initAxLogicExecutorTypeList(justOneLang); + policy0.setStateMap(getOodaStateMap(policy0.getKey(), p0InEventList, p0OutEventList, axLogicExecutorTypeList, p0defaultTaskList, taskReferenceList)); policy0.setFirstState(policy0.getStateMap().get(OBSERVE).getKey().getLocalName()); - final AxPolicies policies = new AxPolicies(new AxArtifactKey("OODAPolicies", "0.0.1")); + final AxPolicies policies = new AxPolicies(new AxArtifactKey("OODAPolicies", DEFAULT_VERSION)); policies.getPolicyMap().put(policy0.getKey(), policy0); - final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInformation", "0.0.1")); - final AxPolicyModel policyModel = new AxPolicyModel(new AxArtifactKey("EvaluationPolicyModel_OODA", "0.0.1")); + final AxKeyInformation keyInformation = new AxKeyInformation( + new AxArtifactKey("KeyInformation", DEFAULT_VERSION)); + final AxPolicyModel policyModel = new AxPolicyModel( + new AxArtifactKey("EvaluationPolicyModel_OODA", DEFAULT_VERSION)); policyModel.setPolicies(policies); policyModel.setEvents(events); policyModel.setTasks(tasks); - policyModel.setAlbums(new AxContextAlbums(new AxArtifactKey("Albums", "0.0.1"))); + policyModel.setAlbums(new AxContextAlbums(new AxArtifactKey("Albums", DEFAULT_VERSION))); policyModel.setSchemas(schemas); policyModel.setKeyInformation(keyInformation); policyModel.getKeyInformation().generateKeyInfo(policyModel); @@ -328,6 +319,54 @@ public class EvalDomainModelFactory { } /** + * Add OODA tasks to the policy. + * + * @param tasks the policy tasks + * @param obTasks observe tasks + * @param orTasks orient tasks + * @param decTasks decide tasks + * @param actTasks act tasks + */ + private void addOodaTasks(final AxTasks tasks, final Set<AxArtifactKey> obTasks, final Set<AxArtifactKey> orTasks, + final Set<AxArtifactKey> decTasks, final Set<AxArtifactKey> actTasks) { + for (final AxTask task : tasks.getTaskMap().values()) { + if (task.getKey().getName().contains(OBSERVE)) { + obTasks.add(task.getKey()); + } + if (task.getKey().getName().contains(ORIENT)) { + orTasks.add(task.getKey()); + } + if (task.getKey().getName().contains("Decide")) { + decTasks.add(task.getKey()); + } + if (task.getKey().getName().contains("Act")) { + actTasks.add(task.getKey()); + } + } + } + + /** + * Initialize the logic executor list. + * + * @param justOneLang the language to use + * @return the list of languages + */ + private List<String> initAxLogicExecutorTypeList(final String justOneLang) { + List<String> axLogicExecutorTypeList = new ArrayList<>(); + + if (justOneLang != null) { + axLogicExecutorTypeList.add(justOneLang); + } else { + axLogicExecutorTypeList.add(JAVASCRIPT); + axLogicExecutorTypeList.add(JYTHON); + axLogicExecutorTypeList.add(JYTHON); + axLogicExecutorTypeList.add(MVEL); + axLogicExecutorTypeList.add(JRUBY); + } + return axLogicExecutorTypeList; + } + + /** * Gets the OODA state map. * * @param policyKey the policy key @@ -417,12 +456,12 @@ public class EvalDomainModelFactory { */ public AxPolicyModel getEcaPolicyModel() { - final AxTasks tasks = new AxTasks(new AxArtifactKey("Tasks", "0.0.1")); + final AxTasks tasks = new AxTasks(new AxArtifactKey("Tasks", DEFAULT_VERSION)); final AxLogicReader logicReader = new PolicyLogicReader().setLogicPackage(PACKAGE) .setDefaultLogic("EvalTask_Logic"); - final AxTask eTask = new AxTask(new AxArtifactKey("Task_Event_0", "0.0.1")); + final AxTask eTask = new AxTask(new AxArtifactKey("Task_Event_0", DEFAULT_VERSION)); eTask.duplicateInputFields(event0000.getParameterMap()); eTask.duplicateOutputFields(event0001.getParameterMap()); final AxTaskLogic eAxLogic = new AxTaskLogic(eTask.getKey(), TASK_LOGIC, @@ -431,7 +470,7 @@ public class EvalDomainModelFactory { .replaceAll(TASK_NAME, eTask.getKey().getName()).replaceAll(STATE_NUMBER, "1")); eTask.setTaskLogic(eAxLogic); - final AxTask cTask = new AxTask(new AxArtifactKey("Task_Condition_0", "0.0.1")); + final AxTask cTask = new AxTask(new AxArtifactKey("Task_Condition_0", DEFAULT_VERSION)); cTask.duplicateInputFields(event0001.getParameterMap()); cTask.duplicateOutputFields(event0002.getParameterMap()); final AxTaskLogic cAxLogic = new AxTaskLogic(cTask.getKey(), TASK_LOGIC, @@ -440,7 +479,7 @@ public class EvalDomainModelFactory { .replaceAll(TASK_NAME, cTask.getKey().getName()).replaceAll(STATE_NUMBER, "2")); cTask.setTaskLogic(cAxLogic); - final AxTask aTask = new AxTask(new AxArtifactKey("Task_Action_0", "0.0.1")); + final AxTask aTask = new AxTask(new AxArtifactKey("Task_Action_0", DEFAULT_VERSION)); aTask.duplicateInputFields(event0002.getParameterMap()); aTask.duplicateOutputFields(event0003.getParameterMap()); final AxTaskLogic aAxLogic = new AxTaskLogic(aTask.getKey(), TASK_LOGIC, @@ -457,17 +496,7 @@ public class EvalDomainModelFactory { final Set<AxArtifactKey> conditionTasks = new TreeSet<>(); final Set<AxArtifactKey> actionTasks = new TreeSet<>(); - for (final AxTask task : tasks.getTaskMap().values()) { - if (task.getKey().getName().contains(EVENT)) { - eventTasks.add(task.getKey()); - } - if (task.getKey().getName().contains(CONDITION)) { - conditionTasks.add(task.getKey()); - } - if (task.getKey().getName().contains(ACTION)) { - actionTasks.add(task.getKey()); - } - } + addEcaTasks(tasks, eventTasks, conditionTasks, actionTasks); final List<Set<AxArtifactKey>> taskReferenceList = new ArrayList<>(); taskReferenceList.add(eventTasks); taskReferenceList.add(conditionTasks); @@ -488,22 +517,24 @@ public class EvalDomainModelFactory { p0defaultTaskList.add(tasks.get("Task_Condition_0").getKey()); p0defaultTaskList.add(tasks.get("Task_Action_0").getKey()); - final AxPolicy policy0 = new AxPolicy(new AxArtifactKey("ECAPolicy_0", "0.0.1")); + final AxPolicy policy0 = new AxPolicy(new AxArtifactKey("ECAPolicy_0", DEFAULT_VERSION)); final List<String> axLogicExecutorTypeList = Arrays.asList((justOneLang == null ? JAVASCRIPT : justOneLang), - (justOneLang == null ? "MVEL" : justOneLang), (justOneLang == null ? JYTHON : justOneLang)); + (justOneLang == null ? MVEL : justOneLang), (justOneLang == null ? JYTHON : justOneLang)); policy0.setStateMap(getEcaStateMap(policy0.getKey(), p0InEventList, p0OutEventList, axLogicExecutorTypeList, p0defaultTaskList, taskReferenceList)); policy0.setFirstState(policy0.getStateMap().get(EVENT).getKey().getLocalName()); - final AxPolicies policies = new AxPolicies(new AxArtifactKey("ECAPolicies", "0.0.1")); + final AxPolicies policies = new AxPolicies(new AxArtifactKey("ECAPolicies", DEFAULT_VERSION)); policies.getPolicyMap().put(policy0.getKey(), policy0); - final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInformation", "0.0.1")); - final AxPolicyModel policyModel = new AxPolicyModel(new AxArtifactKey("EvaluationPolicyModel_ECA", "0.0.1")); + final AxKeyInformation keyInformation = new AxKeyInformation( + new AxArtifactKey("KeyInformation", DEFAULT_VERSION)); + final AxPolicyModel policyModel = new AxPolicyModel( + new AxArtifactKey("EvaluationPolicyModel_ECA", DEFAULT_VERSION)); policyModel.setPolicies(policies); policyModel.setEvents(events); policyModel.setTasks(tasks); - policyModel.setAlbums(new AxContextAlbums(new AxArtifactKey("Albums", "0.0.1"))); + policyModel.setAlbums(new AxContextAlbums(new AxArtifactKey("Albums", DEFAULT_VERSION))); policyModel.setSchemas(schemas); policyModel.setKeyInformation(keyInformation); policyModel.getKeyInformation().generateKeyInfo(policyModel); @@ -516,6 +547,29 @@ public class EvalDomainModelFactory { } /** + * Add ECA tasks. + * + * @param tasks the tasks + * @param eventTasks event tasks + * @param conditionTasks condition tasks + * @param actionTasks action tasks + */ + private void addEcaTasks(final AxTasks tasks, final Set<AxArtifactKey> eventTasks, + final Set<AxArtifactKey> conditionTasks, final Set<AxArtifactKey> actionTasks) { + for (final AxTask task : tasks.getTaskMap().values()) { + if (task.getKey().getName().contains(EVENT)) { + eventTasks.add(task.getKey()); + } + if (task.getKey().getName().contains(CONDITION)) { + conditionTasks.add(task.getKey()); + } + if (task.getKey().getName().contains(ACTION)) { + actionTasks.add(task.getKey()); + } + } + } + + /** * Gets the ECA state map. * * @param policyKey the policy key diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java index 86dac6638..854a9bb3c 100644 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java @@ -39,7 +39,7 @@ public class DefaultTaskLogic { * @return the event * @throws ApexException the apex exception */ - public boolean getEvent(final TaskExecutionContext executor) throws ApexException { + public boolean getEvent(final TaskExecutionContext executor) { String idString = executor.subject.getId(); executor.logger.debug(idString); diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalTaskLogic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalTaskLogic.java index 4c37e4d89..2d60926f6 100644 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalTaskLogic.java +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/EvalTaskLogic.java @@ -37,7 +37,7 @@ public class EvalTaskLogic { * @return the event * @throws ApexException the apex exception */ - public boolean getEvent(final TaskExecutionContext executor) throws ApexException { + public boolean getEvent(final TaskExecutionContext executor) { String idString = executor.subject.getId(); executor.logger.debug(idString); diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Application.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Application.java index 70436150c..34ab414d7 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Application.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Application.java @@ -24,12 +24,9 @@ import java.io.PrintStream; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; import org.onap.policy.apex.tools.common.CliOptions; import org.onap.policy.apex.tools.common.CliParser; import org.onap.policy.apex.tools.common.OutputFile; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Process an Apex Policy Model file to generate the CLI commands to generate an equivalent Apex Policy Model. @@ -37,9 +34,6 @@ import org.slf4j.LoggerFactory; * @author Sven van der Meer <sven.van.der.meer@ericsson.com> */ public final class Application { - // Get a reference to the logger - private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); - /** The name of the application. */ public static final String APP_NAME = "gen-model2cli"; @@ -125,13 +119,7 @@ public final class Application { OUT_STREAM.println(); } - try { - final Model2Cli app = new Model2Cli(modelFile, outfile, !cmd.hasOption("sv"), APP_NAME); - app.runApp(); - } catch (final ApexException aex) { - String message = APP_NAME + ": caught APEX exception with message: " + aex.getMessage(); - ERR_STREAM.println(message); - LOGGER.warn(message, aex); - } + final Model2Cli app = new Model2Cli(modelFile, outfile, !cmd.hasOption("sv"), APP_NAME); + app.runApp(); } } diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java index f58faf0eb..01434190b 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java @@ -108,7 +108,7 @@ public class Model2Cli { * version), negative integer for errors * @throws ApexException if any problem occurred in the model */ - public int runApp() throws ApexException { + public int runApp() { final CodeGeneratorCliEditor codeGen = new CodeGeneratorCliEditor(); final ApexModelFactory factory = new ApexModelFactory(); diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Application.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Application.java index a5600ead1..c7fc5e115 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Application.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Application.java @@ -45,14 +45,14 @@ public final class Application { /** The description 1-liner of the application. */ public static final String APP_DESCRIPTION = "generates JSON templates for events generated from a policy model"; - /** Private constructor to prevent instantiation. */ - private Application() { - } - // Input and output streams private static final PrintStream OUT_STREAM = System.out; private static final PrintStream ERR_STREAM = System.err; + /** Private constructor to prevent instantiation. */ + private Application() { + } + /** * Main method to start the application. * diff --git a/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/CliOptions.java b/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/CliOptions.java index aea984fb1..122ec90a9 100644 --- a/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/CliOptions.java +++ b/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/CliOptions.java @@ -29,9 +29,6 @@ import org.apache.commons.cli.Option; */ public final class CliOptions { - /** Private constructor to prevent instantiation. */ - private CliOptions() {} - /** A console option with "-c" and "--console". */ public static final Option CONSOLE = Option.builder("c").longOpt("console").desc("application as console with input from standard in").build(); @@ -103,4 +100,7 @@ public final class CliOptions { /** A skip validation option with "-sv" and "--skip-validation". */ public static final Option SKIPVALIDATION = Option.builder("sv").longOpt("skip-validation") .desc("switch of validation of the input file").required(false).type(boolean.class).build(); + + /** Private constructor to prevent instantiation. */ + private CliOptions() {} } |