Fixed some easy to resolve Sonar issues.
Issue-ID: POLICY-1034
Change-Id: Ia8e4606bd4307daca499b4a74c96135211e572fd
Signed-off-by: liamfallon <liam.fallon@ericsson.com>
}
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;
+ }
}
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;
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;
}
}
// 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;
catch (final CommandLineException e) {
writer.println(e.getMessage());
errorCount++;
- LOGGER.debug("command line error", e);
+ LOGGER.debug(COMMAND_LINE_ERROR, e);
continue;
}
catch (final CommandLineException e) {
writer.println(e.getMessage());
errorCount++;
- LOGGER.debug("command line error", e);
+ LOGGER.debug(COMMAND_LINE_ERROR, e);
continue;
}
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);
}
}
"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);
}
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;
}
/**
}
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;
+ }
}
// The Apex services client this class is running
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.
*
}
}
+ /**
+ * 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);
+ }
+ }
}
* @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 \"";
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.
*
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.
*
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.
*
* @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 {
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);
+ }
+ }
}
// Output and error streams for messages
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.
*
}
}
}
+ /**
+ * 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);
+ }
+ }
}
* @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";
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.
*
// The Apex services client this class is running
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.
*
}
}
+ /**
+ * 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);
+ }
+ }
}
* @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";
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.
*
* @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);
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,
* @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();
* @throws ApexException the Apex exception occurs in handling Apex
*/
public Map<String, TestContextLongItem> testConcurrentContext()
- throws IOException, ApexException {
+ throws ApexException {
try {
setupAndVerifyContext();
import java.net.InetAddress;
import java.net.NetworkInterface;
+import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
*
* @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
// 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)) {
}
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());
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() {
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.
*
public static final AxArtifactKey[] getAxArtifactKeyArray() {
return USED_ARTIFACT_STACK_ARRAY;
}
-
- /**
- * Instantiates a new constants.
- */
- private Constants() {}
-
}
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;
* @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);
+ }
+
}
/**
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
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
--- /dev/null
+/*-
+ * ============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
+ }
+}
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);
}
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
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;
/**
* @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.
* @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
* @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.
// 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
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)
*
private boolean firstRound = true;
private int frequency = 0;
+ private List<Double> anomalyScores = new LinkedList<>();
+ private List<Double> frequencyForecasted;
+
/**
* The Constructor creates an AnomalyDetection instance.
*/
frequency = 0;
}
- private List<Double> anomalyScores = new LinkedList<>();
- private List<Double> frequencyForecasted;
-
/**
* Checks if the AnomalyDetection instance is initialized.
*
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
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.
*
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;
}
}
}
+ /**
+ * 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);
}
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");
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;
+ }
}
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) {
}
}
+ /**
+ * 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)
*
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";
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
/**
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");
"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");
"[" + 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");
"[" + 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);
result.setResult("valueDeserializer", ValidationStatus.INVALID,
SPECIFY_AS_STRING_MESSAGE);
}
-
- return result;
}
private void validateConsumerTopicList(final GroupValidationResult result) {
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);
} 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;
}
/**
// 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) {
}
}
+ /**
+ * 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.
*
// 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) {
}
}
+ /**
+ * 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.
*
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
// A string holding a message that indicates why processing of this event threw an exception
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.
*
// @formatter:on
}
+ /**
+ * 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.
*
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.
* @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);
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;
}
}
}
+ /**
+ * 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.
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);
}
}
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);
+ }
+ }
}
}
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.
*/
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.
*
*
*/
public class TestJsonEventConverter {
-
@Test
public void testJsonEventConverter() {
Apex2JsonEventConverter converter = new Apex2JsonEventConverter();
@AfterClass
public static void teardownDefaultSchemaParameters() {
ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
+ ModelService.clear();
}
/**
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;
@AfterClass
public static void teardownDefaultSchemaParameters() {
ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
+ ModelService.clear();
}
/**
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";
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,
.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,
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);
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);
return policyModel;
}
+ /**
+ * 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.
*
*/
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,
.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,
.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,
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);
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);
return policyModel;
}
+ /**
+ * 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.
*
* @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);
* @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);
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.
* @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";
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();
}
}
* 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();
/** 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.
*
*/
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();
/** 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() {}
}