/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;
+
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.onap.policy.apex.model.modelapi.ApexApiResult;
import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.model.utilities.TreeMapUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
* @param rootKeywordNode The root keyword node tree
*/
public CommandLineEditorLoop(final Properties properties, final ApexModelHandler modelHandler,
- final KeywordNode rootKeywordNode) {
+ final KeywordNode rootKeywordNode) {
this.modelHandler = modelHandler;
keywordNodeDeque.push(rootKeywordNode);
* @throws IOException Thrown on exceptions on IO
*/
public int runLoop(final InputStream inputStream, final OutputStream outputStream,
- final CommandLineParameters parameters) throws IOException {
+ final CommandLineParameters parameters) throws IOException {
// Readers and writers for input and output
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
final PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));
* @param executionStatus the status of the logic block read
*/
private void processIncomingCommands(final CommandLineParameters parameters, final BufferedReader reader,
- final PrintWriter writer, final CommandLineParser parser,
- MutablePair<Result, Integer> executionStatus) {
+ final PrintWriter writer, final CommandLineParser parser, MutablePair<Result, Integer> executionStatus) {
try {
// Output prompt and get a line of input
final CommandLineCommand command = findCommand(commandWords);
if (command != null) {
// Check the arguments of the command
- final TreeMap<String, CommandLineArgumentValue> argumentValues = getArgumentValues(command,
- commandWords);
+ final TreeMap<String, CommandLineArgumentValue> argumentValues =
+ getArgumentValues(command, commandWords);
// Execute the command, a FINISHED result means a command causes the loop to
// leave execution
* @return the result of the logic block read
*/
private String readLogicBlock(final CommandLineParameters parameters, final BufferedReader reader,
- final PrintWriter writer, MutablePair<Result, Integer> executionStatus) {
+ final PrintWriter writer, MutablePair<Result, Integer> executionStatus) {
String logicBlock;
logicBlock = "";
// If the node entries found is not equal to one, then we have either no command or more
// than one command matching
- final List<Entry<String, KeywordNode>> foundNodeEntries = findMatchingEntries(
- searchKeywordNode.getChildren(), commandWords.get(i));
+ final List<Entry<String, KeywordNode>> foundNodeEntries =
+ findMatchingEntries(searchKeywordNode.getChildren(), commandWords.get(i));
if (foundNodeEntries.isEmpty()) {
unwindStack(startKeywordNode);
throw new CommandLineException("command not found: " + stringAL2String(commandWords));
} else if (foundNodeEntries.size() > 1) {
unwindStack(startKeywordNode);
throw new CommandLineException("multiple commands matched: " + stringAL2String(commandWords) + " ["
- + nodeAL2String(foundNodeEntries) + ']');
+ + nodeAL2String(foundNodeEntries) + ']');
}
// Record the fully expanded command word
* @return the argument values
*/
private TreeMap<String, CommandLineArgumentValue> getArgumentValues(final CommandLineCommand command,
- final List<String> commandWords) {
+ final List<String> commandWords) {
final TreeMap<String, CommandLineArgumentValue> argumentValues = new TreeMap<>();
for (final CommandLineArgument argument : command.getArgumentList()) {
if (argument != null) {
// Set the value of the arguments
for (final Entry<String, String> argument : getCommandArguments(commandWords)) {
- final List<Entry<String, CommandLineArgumentValue>> foundArguments = TreeMapUtils
- .findMatchingEntries(argumentValues, argument.getKey());
+ final List<Entry<String, CommandLineArgumentValue>> foundArguments =
+ TreeMapUtils.findMatchingEntries(argumentValues, argument.getKey());
if (foundArguments.isEmpty()) {
throw new CommandLineException(COMMAND + stringAL2String(commandWords) + ": " + " argument \""
- + argument.getKey() + "\" not allowed on command");
+ + argument.getKey() + "\" not allowed on command");
} else if (foundArguments.size() > 1) {
throw new CommandLineException(COMMAND + stringAL2String(commandWords) + ": " + " argument " + argument
- + " matches multiple arguments [" + argumentAL2String(foundArguments) + ']');
+ + " matches multiple arguments [" + argumentAL2String(foundArguments) + ']');
}
// Set the value of the argument, stripping off any quotes
// mandatory
if (!argumentValue.isSpecified() && !argumentValue.getCliArgument().isNullable()) {
throw new CommandLineException(COMMAND + stringAL2String(commandWords) + ": " + " mandatory argument \""
- + argumentValue.getCliArgument().getArgumentName() + "\" not specified");
+ + argumentValue.getCliArgument().getArgumentName() + "\" not specified");
}
}
for (final String word : commandWords) {
final int equalsPos = word.indexOf('=');
if (equalsPos > 0) {
- arguments.add(new SimpleEntry<>(word.substring(0, equalsPos),
- word.substring(equalsPos + 1, word.length())));
+ arguments.add(
+ new SimpleEntry<>(word.substring(0, equalsPos), word.substring(equalsPos + 1, word.length())));
}
}
* @return the result of execution of the command
*/
private Result executeCommand(final CommandLineCommand command,
- final TreeMap<String, CommandLineArgumentValue> argumentValues, final PrintWriter writer) {
+ final TreeMap<String, CommandLineArgumentValue> argumentValues, final PrintWriter writer) {
if (command.isSystemCommand()) {
return exceuteSystemCommand(command, writer);
} else {
if (macroFileName.length() > 2 && macroFileName.startsWith("\"") && macroFileName.endsWith("\"")) {
macroFileName = macroFileName.substring(1, macroFileName.length() - 1);
} else {
- throw new CommandLineException("macro file name \"" + macroFileName
- + "\" must exist and be quoted with double quotes \"\"");
+ throw new CommandLineException(
+ "macro file name \"" + macroFileName + "\" must exist and be quoted with double quotes \"\"");
}
// Append the working directory to the macro file name
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* The Class TestCLIEditorEventsContext.
final File tempLogFile = temporaryFolder.newFile(LOG_FILE);
final File tempModelFile = temporaryFolder.newFile(JSON_FILE);
- final String[] cliArgs = new String[]
- { "-c", APEX_JAVA_POLICY_FILE.toString(), "-l", tempLogFile.getAbsolutePath(), "-o",
- tempModelFile.getAbsolutePath() };
+ final String[] cliArgs = new String[] {"-c", APEX_JAVA_POLICY_FILE.toString(), "-l",
+ tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath()};
final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs);
assertEquals(0, cliEditor.getErrorCount());
final File tempLogFile = temporaryFolder.newFile(LOG_FILE);
final File tempModelFile = temporaryFolder.newFile(JSON_FILE);
- final String[] cliArgs = new String[]
- { "-c", APEX_AVRO_POLICY_FILE.toString(), "-l", tempLogFile.getAbsolutePath(), "-o",
- tempModelFile.getAbsolutePath() };
+ final String[] cliArgs = new String[] {"-c", APEX_AVRO_POLICY_FILE.toString(), "-l",
+ tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath()};
final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs);
assertEquals(0, cliEditor.getErrorCount());
final File tempModelFile = temporaryFolder.newFile(JSON_FILE);
final String modelFile = SRC_TEST_FOLDER.resolve("model").resolve("empty_commands.json").toString();
- final String apexPropertiesLocation = SRC_MAIN_FOLDER.resolve("etc/editor").resolve("ApexModelProperties.json")
- .toString();
+ final String apexPropertiesLocation =
+ SRC_MAIN_FOLDER.resolve("etc/editor").resolve("ApexModelProperties.json").toString();
- final String[] cliArgs = new String[]
- { "-c", APEX_AVRO_POLICY_FILE.toString(), "-l", tempLogFile.getAbsolutePath(), "-o",
- tempModelFile.getAbsolutePath(), "-m", modelFile, "-a", apexPropertiesLocation };
+ final String[] cliArgs =
+ new String[] {"-c", APEX_AVRO_POLICY_FILE.toString(), "-l", tempLogFile.getAbsolutePath(), "-o",
+ tempModelFile.getAbsolutePath(), "-m", modelFile, "-a", apexPropertiesLocation};
final ApexCommandLineEditorMain objUnderTest = new ApexCommandLineEditorMain(cliArgs);
assertEquals(1, objUnderTest.getErrorCount());
final File modelFile = temporaryFolder.newFile("empty_commands.json");
- final String apexPropertiesLocation = SRC_MAIN_FOLDER.resolve("etc/editor").resolve("ApexModelProperties.json")
- .toString();
-
- final String[] cliArgs = new String[] {
- "-c",
- APEX_AVRO_POLICY_FILE.toString(),
- "-l",
- tempLogFile.getAbsolutePath(),
- "-o",
- tempModelFile.getAbsolutePath(),
- "-m",
- modelFile.getAbsolutePath(),
- "-a",
- apexPropertiesLocation
- };
+ final String apexPropertiesLocation =
+ SRC_MAIN_FOLDER.resolve("etc/editor").resolve("ApexModelProperties.json").toString();
+
+ final String[] cliArgs =
+ new String[] {"-c", APEX_AVRO_POLICY_FILE.toString(), "-l", tempLogFile.getAbsolutePath(), "-o",
+ tempModelFile.getAbsolutePath(), "-m", modelFile.getAbsolutePath(), "-a", apexPropertiesLocation};
final ApexCommandLineEditorMain objUnderTest = new ApexCommandLineEditorMain(cliArgs);
assertEquals(1, objUnderTest.getErrorCount());
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
+
import org.junit.Test;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* The Class TestCLIEditorOptions.
final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json");
final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l",
- tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath()};
+ tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath()};
final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs);
assertEquals(0, cliEditor.getErrorCount());
final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json");
final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l",
- tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nl", "-nm"};
+ tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nl", "-nm"};
final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs);
assertEquals(0, cliEditor.getErrorCount());
final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json");
final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l",
- tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nm"};
+ tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nm"};
final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs);
assertEquals(0, cliEditor.getErrorCount());
final File tempModelFile = File.createTempFile("ShellPolicyModel", ".json");
final String[] cliArgs = new String[] {"-c", "src/main/resources/examples/scripts/ShellPolicyModel.apex", "-l",
- tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nl"};
+ tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath(), "-nl"};
final ApexCommandLineEditorMain cliEditor = new ApexCommandLineEditorMain(cliArgs);
assertEquals(0, cliEditor.getErrorCount());
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.utils.resources.ResourceUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* Test FileMacro in the CLI.
tempLogFile = File.createTempFile("TestPolicyModel", ".log");
fileMacroArgs = new String[] {"-c", "src/test/resources/scripts/FileMacro.apex", "-l",
- tempLogFile.getCanonicalPath(), "-o", tempModelFile.getCanonicalPath(), "-if", "true"};
+ tempLogFile.getCanonicalPath(), "-o", tempModelFile.getCanonicalPath(), "-if", "true"};
}
/**
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.policy.apex.model.modelapi.ApexApiResult;
import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
*
*/
@Path("editor/{session}")
-@Produces(
- { MediaType.APPLICATION_JSON })
-@Consumes(
- { MediaType.APPLICATION_JSON })
+@Produces({MediaType.APPLICATION_JSON})
+@Consumes({MediaType.APPLICATION_JSON})
public class ApexEditorRestResource implements RestCommandHandler {
// Get a reference to the logger
/**
* Retrieve the model for this session. If successful the model will be available in the first message in the
- * result. The returned value will be similar to a {@code AxPolicyModel}, with merged {@code AxKeyInfo} for the
- * root object.
+ * result. The returned value will be similar to a {@code AxPolicyModel}, with merged {@code AxKeyInfo} for the root
+ * object.
*
* @return an ApexAPIResult object. If successful then {@link ApexApiResult#isOk()} will return true. Any
* messages/errors can be retrieved using {@link ApexApiResult#getMessages()}
@GET
@Path("KeyInformation/Get")
public ApexApiResult listKeyInformation(@QueryParam(NAME) final String name,
- @QueryParam(VERSION) final String version) {
+ @QueryParam(VERSION) final String version) {
return processRestCommand(RestCommandType.KEY_INFO, RestCommand.LIST, name, version);
}
/**
* List context schemas with the given key names/versions. If successful the result(s) will be available in the
- * result messages. The returned value(s) will be similar to {@code AxContextSchema}, with merged
- * {@code AxKeyInfo} for the root object.
+ * result messages. The returned value(s) will be similar to {@code AxContextSchema}, with merged {@code AxKeyInfo}
+ * for the root object.
*
* @param name the name to search for. If null or empty, then all names will be queried
* @param version the version to search for. If null then all versions will be searched for.
@GET
@Path("ContextSchema/Get")
public ApexApiResult listContextSchemas(@QueryParam(NAME) final String name,
- @QueryParam(VERSION) final String version) {
+ @QueryParam(VERSION) final String version) {
return processRestCommand(RestCommandType.CONTEXT_SCHEMA, RestCommand.LIST, name, version);
}
@DELETE
@Path("ContextSchema/Delete")
public ApexApiResult deleteContextSchema(@QueryParam(NAME) final String name,
- @QueryParam(VERSION) final String version) {
+ @QueryParam(VERSION) final String version) {
return processRestCommand(RestCommandType.CONTEXT_SCHEMA, RestCommand.DELETE, name, version);
}
@GET
@Path("Validate/ContextSchema")
public ApexApiResult validateContextSchemas(@QueryParam(NAME) final String name,
- @QueryParam(VERSION) final String version) {
+ @QueryParam(VERSION) final String version) {
return processRestCommand(RestCommandType.CONTEXT_SCHEMA, RestCommand.VALIDATE, name, version);
}
/**
* List context albums with the given key names/versions. If successful the result(s) will be available in the
- * result messages. The returned value(s) will be similar to {@code AxContextAlbum}, with merged
- * {@code AxKeyInfo} for the root object.
+ * result messages. The returned value(s) will be similar to {@code AxContextAlbum}, with merged {@code AxKeyInfo}
+ * for the root object.
*
* @param name the name to search for. If null or empty, then all names will be queried
* @param version the version to search for. If null then all versions will be searched for.
@GET
@Path("ContextAlbum/Get")
public ApexApiResult listContextAlbums(@QueryParam(NAME) final String name,
- @QueryParam(VERSION) final String version) {
+ @QueryParam(VERSION) final String version) {
return processRestCommand(RestCommandType.CONTEXT_ALBUM, RestCommand.LIST, name, version);
}
@DELETE
@Path("ContextAlbum/Delete")
public ApexApiResult deleteContextAlbum(@QueryParam(NAME) final String name,
- @QueryParam(VERSION) final String version) {
+ @QueryParam(VERSION) final String version) {
return processRestCommand(RestCommandType.CONTEXT_ALBUM, RestCommand.DELETE, name, version);
}
@GET
@Path("Validate/ContextAlbum")
public ApexApiResult validateContextAlbums(@QueryParam(NAME) final String name,
- @QueryParam(VERSION) final String version) {
+ @QueryParam(VERSION) final String version) {
return processRestCommand(RestCommandType.CONTEXT_ALBUM, RestCommand.VALIDATE, name, version);
}
/**
* List events with the given key names/versions. If successful the result(s) will be available in the result
- * messages. The returned value(s) will be similar to {@code AxEvent}, with merged {@code AxKeyInfo} for the
- * root object.
+ * messages. The returned value(s) will be similar to {@code AxEvent}, with merged {@code AxKeyInfo} for the root
+ * object.
*
* @param name the name to search for. If null or empty, then all names will be queried
* @param version the version to search for. If null then all versions will be searched for.
/**
* List tasks with the given key names/versions. If successful the result(s) will be available in the result
- * messages. The returned value(s) will be similar to {@code AxTask}, with merged {@code AxKeyInfo} for the
- * root object.
+ * messages. The returned value(s) will be similar to {@code AxTask}, with merged {@code AxKeyInfo} for the root
+ * object.
*
* @param name the name to search for. If null or empty, then all names will be queried
* @param version the version to search for. If null then all versions will be searched for.
@PUT
@Path("Policy/Update")
public ApexApiResult updatePolicy(@QueryParam("firstStatePeriodic") final boolean firstStatePeriodic,
- final String jsonString) {
+ final String jsonString) {
ApexApiResult result = processRestCommand(RestCommandType.POLICY, RestCommand.UPDATE, jsonString);
if (result != null && result.isOk() && firstStatePeriodic) {
/**
* List policies with the given key names/versions. If successful the result(s) will be available in the result
- * messages. The returned value(s) will be similar to {@code AxPolicy}, with merged {@code AxKeyInfo} for the
- * root object.
+ * messages. The returned value(s) will be similar to {@code AxPolicy}, with merged {@code AxKeyInfo} for the root
+ * object.
*
* @param name the name to search for. If null or empty, then all names will be queried
* @param version the version to search for. If null then all versions will be searched for.
/**
* This method routes REST commands that take no parameters to their caller.
- *
+ *
* @param commandType the type of REST command to process
* @param command the REST command to process
* @return the result of the REST command
/**
* This method routes REST commands that take a JSON string to their caller.
- *
+ *
* @param commandType the type of REST command to process
* @param command the REST command to process
* @param jsonString the JSON string received in the REST request
* @return the result of the REST command
*/
private ApexApiResult processRestCommand(final RestCommandType commandType, final RestCommand command,
- final String jsonString) {
+ final String jsonString) {
LOGGER.entry(commandType, jsonString);
try {
ApexApiResult result = new ApexApiResult();
/**
* This method routes REST commands that take a name and version to their caller.
- *
+ *
* @param commandType the type of REST command to process
* @param command the REST command to process
* @param name the name received in the REST request
* @return the result of the REST command
*/
private ApexApiResult processRestCommand(final RestCommandType commandType, final RestCommand command,
- final String name, final String version) {
+ final String name, final String version) {
LOGGER.entry(commandType, name, version);
try {
ApexApiResult result = new ApexApiResult();
*/
@Override
public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
- final RestCommand command) {
+ final RestCommand command) {
switch (commandType) {
case MODEL:
return MODEL_HANDLER.executeRestCommand(session, commandType, command);
/**
* This method invokes callers to run REST commands that take a JSON string.
- *
+ *
* @param session the Apex editor session
* @param commandType the type of REST command to process
* @param command the REST command to process
*/
@Override
public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
- final RestCommand command, final String jsonString) {
+ final RestCommand command, final String jsonString) {
switch (commandType) {
case MODEL:
return MODEL_HANDLER.executeRestCommand(session, commandType, command, jsonString);
/**
* This method invokes callers to run REST commands that take a name and version.
- *
+ *
* @param session the Apex editor session
* @param commandType the type of REST command to process
* @param command the REST command to process
*/
@Override
public ApexApiResult executeRestCommand(final RestSession session, final RestCommandType commandType,
- final RestCommand command, final String name, final String version) {
+ final RestCommand command, final String name, final String version) {
switch (commandType) {
case MODEL:
return MODEL_HANDLER.executeRestCommand(session, commandType, command, name, version);
periodicEventJsonString = TextFileUtils.getTextFileAsString(PERIODIC_EVENT_TEMPLATE);
} catch (IOException ioException) {
String message = "read of periodic event tempalte from " + PERIODIC_EVENT_TEMPLATE + "failed: "
- + ioException.getMessage();
+ + ioException.getMessage();
LOGGER.debug(message, ioException);
return new ApexApiResult(Result.FAILED, message);
}
return processRestCommand(RestCommandType.EVENT, RestCommand.CREATE, periodicEventJsonString);
}
-
+
/*
* This method is used only for testing and is used to cause an exception on calls from unit test to test exception
* handling.
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.junit.Test;
import org.onap.policy.apex.model.modelapi.ApexApiResult;
import org.onap.policy.apex.model.modelapi.ApexApiResult.Result;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* Test Apex Editor Rest Resource.
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class ApexEditorRestResourceTest extends JerseyTest {
entityString = "{" + "\"name\" : \"GoodDay4\"," + "\"version\" : \"0.0.2\","
+ "\"parameters\" : {\"Par0\" : {\"parameterName\" : \"NotPar0\", \"defaultValue\" : "
- + "\"Parameter Defaultvalue\"}},"
- + "\"uuid\" : \"1fa2e430-f2b2-11e6-bc64-92361f002799\","
+ + "\"Parameter Defaultvalue\"}}," + "\"uuid\" : \"1fa2e430-f2b2-11e6-bc64-92361f002799\","
+ "\"description\" : \"A description of hello\"" + "}";
entity = Entity.entity(entityString, MediaType.APPLICATION_JSON);
result = target("editor/" + sessionId + "/Task/Create").request().post(entity, ApexApiResult.class);
+ " \"trigger\" : {\"name\" : \"inEvent\", \"version\" : \"0.0.1\"},"
+ " \"defaultTask\" : {\"name\" : \"task\", \"version\" : \"0.0.1\"},"
+ " \"taskSelectionLogic\" : {\"logicFlavour\" : \"LemonAndLime\", \"logic\" : \"lots of lemons, "
- + "lots of lime\"},"
- + " \"contexts\" : [null]," + " \"stateOutputs\" : {" + " \"so0\" : {"
+ + "lots of lime\"}," + " \"contexts\" : [null]," + " \"stateOutputs\" : {"
+ + " \"so0\" : {"
+ " \"event\" : {\"name\" : \"inEvent\", \"version\" : \"0.0.1\"},"
+ " \"nextState\" : null" + " }" + " }," + " \"tasks\" : {"
+ " \"tr0\" : {"
+ " \"outputType\" : \"DIRECT\"," + " \"outputName\" : \"so0\"" + " }" + " },"
+ " \"finalizers\" : {"
+ " \"sf0\" : {\"logicFlavour\" : \"LemonAndLime\", \"logic\" : \"lots of lemons, "
- + "lots of lime\"}"
- + " }" + " }" + "}," + "\"uuid\" : \"1fa2e430-f2b2-11e6-bc64-92361f002671\","
+ + "lots of lime\"}" + " }" + " }" + "},"
+ + "\"uuid\" : \"1fa2e430-f2b2-11e6-bc64-92361f002671\","
+ "\"description\" : \"A description of hello\"" + "}";
entity = Entity.entity(entityString, MediaType.APPLICATION_JSON);
result = target("editor/" + sessionId + "/Policy/Create").request().post(entity, ApexApiResult.class);
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.policy.apex.core.protocols.engdep.messages.StopPeriodicEvents;
import org.onap.policy.apex.core.protocols.engdep.messages.UpdateModel;
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* Dummy deployment client.
*
* @param message the message to send to the Apex server
*/
+ @Override
public void sendMessage(final Message message) {
if (message instanceof GetEngineServiceInfo) {
handleEngineServiceInfo(message);
/**
* Handle the EngineServiceInfo message.
- *
+ *
* @param message the EngineServiceInfo message
*/
private void handleEngineServiceInfo(final Message message) {
}
if ("ReturnBadResponse".equals(message.getTarget().getName())) {
- Response badResponse = new Response(ENGINE_KEY, successFlag,new StartEngine(message.getTarget()));
+ Response badResponse = new Response(ENGINE_KEY, successFlag, new StartEngine(message.getTarget()));
receiveQueue.add(badResponse);
return !successFlag;
}
-
+
Response response = new Response(ENGINE_KEY, successFlag, message);
if (successFlag) {
try {
- response.setMessageData(TextFileUtils
- .getTextFileAsString("src/test/resources/models/SmallModel.json"));
+ response.setMessageData(TextFileUtils.getTextFileAsString("src/test/resources/models/SmallModel.json"));
} catch (IOException e) {
e.printStackTrace();
}
/**
* Handle and return a message.
- *
+ *
* @param message the message
*/
private boolean handleAndReturnMessage(final Message message, final boolean successFlag) {
/**
* Stop the deployment client.
*/
+ @Override
public void stopClient() {
if (thisThread != null) {
thisThread.interrupt();
*
* @return true, if the client thread is started
*/
+ @Override
public boolean isStarted() {
return started;
}
*
* @return the receive queue
*/
+ @Override
public BlockingQueue<Message> getReceiveQueue() {
return receiveQueue;
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* Test MyFirstPolicyModel CLI.
final File tempLogFile2 = File.createTempFile("TestMyFirstPolicy2CLI", ".log");
final File tempModelFile2 = File.createTempFile("TestMyFirstPolicy2CLI", ".json");
final String[] testApexModel1CliArgs =
- { "-c", "src/main/resources/examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.apex", "-l",
- tempLogFile1.getAbsolutePath(), "-o", tempModelFile1.getAbsolutePath() };
+ {"-c", "src/main/resources/examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.apex", "-l",
+ tempLogFile1.getAbsolutePath(), "-o", tempModelFile1.getAbsolutePath()};
final String[] testApexModel2CliArgs =
- { "-c", "src/main/resources/examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.apex", "-l",
- tempLogFile2.getAbsolutePath(), "-o", tempModelFile2.getAbsolutePath() };
+ {"-c", "src/main/resources/examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.apex", "-l",
+ tempLogFile2.getAbsolutePath(), "-o", tempModelFile2.getAbsolutePath()};
new ApexCommandLineEditorMain(testApexModel1CliArgs);
new ApexCommandLineEditorMain(testApexModel2CliArgs);
import javax.ws.rs.core.Response;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.onap.policy.controlloop.util.Serialization;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.eclipse.persistence.oxm.MediaType;
import org.onap.policy.apex.model.basicmodel.concepts.AxConcept;
import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.utils.resources.ResourceUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.onap.policy.common.utils.validation.Assertions;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
// Set up the unmarshaller to carry out validation
unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
- }
- catch (final JAXBException e) {
+ } catch (final JAXBException e) {
LOGGER.error("Unable to set JAXB context", e);
throw new ApexModelException("Unable to set JAXB context", e);
}
try {
// Set the concept schema
final URL schemaUrl = ResourceUtils.getUrlResource(schemaFileName);
- final Schema apexConceptSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
- .newSchema(schemaUrl);
+ final Schema apexConceptSchema =
+ SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaUrl);
unmarshaller.setSchema(apexConceptSchema);
- }
- catch (final Exception e) {
+ } catch (final Exception e) {
LOGGER.error("Unable to load schema ", e);
throw new ApexModelException("Unable to load schema", e);
}
- }
- else {
+ } else {
// Clear the schema
unmarshaller.setSchema(null);
}
String apexConceptString = null;
try {
apexConceptString = TextFileUtils.getReaderAsString(apexConceptReader).trim();
- }
- catch (final IOException e) {
+ } catch (final IOException e) {
throw new ApexModelException("Unable to read Apex concept ", e);
}
final StreamSource source = new StreamSource(new StringReader(apexString));
final JAXBElement<C> rootElement = unmarshaller.unmarshal(source, rootConceptClass);
apexConcept = rootElement.getValue();
- }
- catch (final JAXBException e) {
+ } catch (final JAXBException e) {
throw new ApexModelException("Unable to unmarshal Apex concept ", e);
}
final AxValidationResult validationResult = apexConcept.validate(new AxValidationResult());
if (validationResult.isValid()) {
return apexConcept;
- }
- else {
+ } else {
String message = "Apex concept validation failed" + validationResult.toString();
LOGGER.error(message);
throw new ApexModelException(message);
}
- }
- else {
+ } else {
// No validation check
return apexConcept;
}
private void setInputType(final String apexConceptString) throws ApexModelException {
// Check the input type
if (Pattern.compile(JSON_INPUT_TYPE_REGEXP).matcher(apexConceptString).find()) {
- //is json
+ // is json
try {
unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
unmarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
- }
- catch (final Exception e) {
+ } catch (final Exception e) {
LOGGER.warn("JAXB error setting marshaller for JSON Input", e);
throw new ApexModelException("JAXB error setting unmarshaller for JSON input", e);
}
- }
- else if (Pattern.compile(XML_INPUT_TYPE_REGEXP).matcher(apexConceptString).find()) {
- //is xml
+ } else if (Pattern.compile(XML_INPUT_TYPE_REGEXP).matcher(apexConceptString).find()) {
+ // is xml
try {
unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
- }
- catch (final Exception e) {
+ } catch (final Exception e) {
LOGGER.warn("JAXB error setting marshaller for XML Input", e);
throw new ApexModelException("JAXB error setting unmarshaller for XML input", e);
}
- }
- else {
+ } else {
LOGGER.warn("format of input for Apex concept is neither JSON nor XML");
throw new ApexModelException("format of input for Apex concept is neither JSON nor XML");
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.List;
import java.util.Properties;
import java.util.Set;
+
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
import org.onap.policy.apex.model.policymodel.handling.PolicyModelComparer;
import org.onap.policy.apex.model.policymodel.handling.PolicyModelMerger;
import org.onap.policy.apex.model.policymodel.handling.PolicyModelSplitter;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.utils.resources.ResourceUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.onap.policy.common.utils.validation.Assertions;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
if (!apexModel.getPolicyModel().getKey().equals(AxArtifactKey.getNullKey())) {
return new ApexApiResult(ApexApiResult.Result.CONCEPT_EXISTS,
- MODEL + apexModel.getPolicyModel().getKey().getId() + ALREADY_LOADED);
+ MODEL + apexModel.getPolicyModel().getKey().getId() + ALREADY_LOADED);
}
ApexApiResult result = new ApexApiResult();
if (!apexModel.getPolicyModel().getKey().equals(AxArtifactKey.getNullKey())) {
return new ApexApiResult(ApexApiResult.Result.CONCEPT_EXISTS,
- MODEL + apexModel.getPolicyModel().getKey().getId() + ALREADY_LOADED);
+ MODEL + apexModel.getPolicyModel().getKey().getId() + ALREADY_LOADED);
}
ApexApiResult result = new ApexApiResult();
* @return the result of the operation
*/
public ApexApiResult loadFromDatabase(final String modelName, final String modelVersion,
- final DaoParameters daoParameters) {
+ final DaoParameters daoParameters) {
Assertions.argumentNotNull(modelName, "modelName may not be null");
Assertions.argumentNotNull(daoParameters, "DaoParameters may not be null");
if (!apexModel.getPolicyModel().getKey().equals(AxArtifactKey.getNullKey())) {
return new ApexApiResult(ApexApiResult.Result.CONCEPT_EXISTS,
- MODEL + apexModel.getPolicyModel().getKey().getId() + ALREADY_LOADED);
+ MODEL + apexModel.getPolicyModel().getKey().getId() + ALREADY_LOADED);
}
ApexDao apexDao = null;
// Single specific model requested
if (modelVersion != null) {
- AxPolicyModel daoPolicyModel = apexDao.get(AxPolicyModel.class,
- new AxArtifactKey(modelName, modelVersion));
+ AxPolicyModel daoPolicyModel =
+ apexDao.get(AxPolicyModel.class, new AxArtifactKey(modelName, modelVersion));
if (daoPolicyModel != null) {
apexModel.setPolicyModel(daoPolicyModel);
} else {
apexModel.setPolicyModel(new AxPolicyModel());
return new ApexApiResult(ApexApiResult.Result.FAILED, "no policy model with name " + modelName
- + " and version " + modelVersion + FOUND_IN_DATABASE);
+ + " and version " + modelVersion + FOUND_IN_DATABASE);
}
}
// Fishing expedition
foundPolicyModel = dbPolicyModel;
} else {
return new ApexApiResult(ApexApiResult.Result.FAILED,
- "more than one policy model with name " + modelName + FOUND_IN_DATABASE);
+ "more than one policy model with name " + modelName + FOUND_IN_DATABASE);
}
}
}
} else {
apexModel.setPolicyModel(new AxPolicyModel());
return new ApexApiResult(ApexApiResult.Result.FAILED,
- "no policy model with name " + modelName + FOUND_IN_DATABASE);
+ "no policy model with name " + modelName + FOUND_IN_DATABASE);
}
}
if (!apexModel.getPolicyModel().getKey().equals(AxArtifactKey.getNullKey())) {
return new ApexApiResult(ApexApiResult.Result.CONCEPT_EXISTS,
- MODEL + apexModel.getPolicyModel().getKey().getId() + ALREADY_LOADED);
+ MODEL + apexModel.getPolicyModel().getKey().getId() + ALREADY_LOADED);
}
URL apexModelUrl;
result.setResult(ApexApiResult.Result.FAILED);
}
result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false)
- .writeString(apexModel.getPolicyModel().getKey(), AxArtifactKey.class, jsonMode));
+ .writeString(apexModel.getPolicyModel().getKey(), AxArtifactKey.class, jsonMode));
result.addMessage(validationResult.toString());
return result;
} catch (Exception e) {
return result;
}
- PolicyModelComparer policyModelComparer = new PolicyModelComparer(apexModel.getPolicyModel(),
- otherPolicyModel);
+ PolicyModelComparer policyModelComparer =
+ new PolicyModelComparer(apexModel.getPolicyModel(), otherPolicyModel);
result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false)
- .writeString(apexModel.getPolicyModel().getKey(), AxArtifactKey.class, jsonMode));
+ .writeString(apexModel.getPolicyModel().getKey(), AxArtifactKey.class, jsonMode));
result.addMessage(policyModelComparer.toString());
return result;
* @return the result of the operation
*/
public ApexApiResult compareWithString(final String otherModelString, final boolean diffsOnly,
- final boolean keysOnly) {
+ final boolean keysOnly) {
ApexApiResult result = new ApexApiResult();
try {
AxPolicyModel otherPolicyModel = loadModelFromString(otherModelString, result);
return result;
}
- PolicyModelComparer policyModelComparer = new PolicyModelComparer(apexModel.getPolicyModel(),
- otherPolicyModel);
+ PolicyModelComparer policyModelComparer =
+ new PolicyModelComparer(apexModel.getPolicyModel(), otherPolicyModel);
result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false)
- .writeString(apexModel.getPolicyModel().getKey(), AxArtifactKey.class, jsonMode));
+ .writeString(apexModel.getPolicyModel().getKey(), AxArtifactKey.class, jsonMode));
result.addMessage(policyModelComparer.toString());
return result;
requiredPolicySet.add(requiredPolicy.getKey());
} else {
return new ApexApiResult(ApexApiResult.Result.FAILED,
- "policy for policy name " + policyName + " not found in model");
+ "policy for policy name " + policyName + " not found in model");
}
}
try {
- AxPolicyModel splitPolicyModel = PolicyModelSplitter.getSubPolicyModel(apexModel.getPolicyModel(),
- requiredPolicySet, false);
+ AxPolicyModel splitPolicyModel =
+ PolicyModelSplitter.getSubPolicyModel(apexModel.getPolicyModel(), requiredPolicySet, false);
ApexModelFileWriter<AxPolicyModel> apexModelFileWriter = new ApexModelFileWriter<>(false);
apexModelFileWriter.apexModelWriteJsonFile(splitPolicyModel, AxPolicyModel.class, targetModelName);
return splitResult;
} catch (Exception e) {
return new ApexApiResult(ApexApiResult.Result.FAILED,
- "split of policy model " + apexModel.getPolicyModel().getId() + " failed", e);
+ "split of policy model " + apexModel.getPolicyModel().getId() + " failed", e);
} finally {
if (tempSplitPolicyFile != null) {
try {
try {
AxPolicyModel mergedPolicyModel = PolicyModelMerger.getMergedPolicyModel(apexModel.getPolicyModel(),
- mergeInPolicyModel, keepOriginal, false, false);
+ mergeInPolicyModel, keepOriginal, false, false);
apexModel.setPolicyModel(mergedPolicyModel != null ? mergedPolicyModel : new AxPolicyModel());
return new ApexApiResult();
} catch (ApexModelException e) {
try {
AxPolicyModel mergedPolicyModel = PolicyModelMerger.getMergedPolicyModel(apexModel.getPolicyModel(),
- mergeInPolicyModel, keepOriginal, false, false);
+ mergeInPolicyModel, keepOriginal, false, false);
apexModel.setPolicyModel(mergedPolicyModel != null ? mergedPolicyModel : new AxPolicyModel());
return new ApexApiResult();
} catch (ApexModelException e) {
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.junit.Test;
import org.onap.policy.apex.model.basicmodel.dao.DaoParameters;
import org.onap.policy.apex.model.modelapi.impl.ApexModelImpl;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* Test the apex model API.
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class ApexModelApiTest {
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.junit.Test;
import org.onap.policy.apex.model.basicmodel.dao.DaoParameters;
import org.onap.policy.apex.model.modelapi.impl.ModelHandlerFacade;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* Test the model handler facade.
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class ModelHandlerFacadeTest {
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
-import org.onap.policy.apex.model.policymodel.handling.PolicyComparer;
-import org.onap.policy.apex.model.policymodel.handling.PolicyModelComparer;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
public class PolicyModelComparerTest {
<!--
============LICENSE_START=======================================================
Copyright (C) 2018 Ericsson. All rights reserved.
+ Modifications Copyright (C) 2020 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
SPDX-License-Identifier: Apache-2.0
============LICENSE_END=========================================================
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project
+ xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onap.policy.apex-pdp.model</groupId>
<dependencies>
+ <dependency>
+ <groupId>org.onap.policy.common</groupId>
+ <artifactId>utils</artifactId>
+ </dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.apex.model.utilities;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.nio.file.Files;
-
-/**
- * The Class TextFileUtils is class that provides useful functions for handling text files. Functions to read and wrtie
- * text files to strings and strings are provided.
- *
- * @author Liam Fallon (liam.fallon@ericsson.com)
- */
-public abstract class TextFileUtils {
- private static final int READER_CHAR_BUFFER_SIZE_4096 = 4096;
-
- private TextFileUtils() {
- // This class cannot be initialized
- }
-
- /**
- * Method to return the contents of a text file as a string.
- *
- * @param textFilePath The path to the file as a string
- * @return A string containing the contents of the file
- * @throws IOException on errors reading text from the file
- */
- public static String getTextFileAsString(final String textFilePath) throws IOException {
- final File textFile = new File(textFilePath);
- return new String(Files.readAllBytes(textFile.toPath()));
- }
-
- /**
- * Method to write contents of a string to a text file.
- *
- * @param outString The string to write
- * @param textFilePath The path to the file as a string
- * @throws IOException on errors reading text from the file
- */
- public static void putStringAsTextFile(final String outString, final String textFilePath) throws IOException {
- final File textFile = new File(textFilePath);
- if (!textFile.getParentFile().exists()) {
- textFile.getParentFile().mkdirs();
- }
-
- putStringAsFile(outString, textFile);
- }
-
- /**
- * Method to write contents of a string to a text file.
- *
- * @param outString The string to write
- * @param textFile The file to write the string to
- * @throws IOException on errors reading text from the file
- */
- public static void putStringAsFile(final String outString, final File textFile) throws IOException {
- Files.write(textFile.toPath(), outString.getBytes());
- }
-
- /**
- * Method to return the contents of a text steam as a string.
- *
- * @param textStream The stream
- * @return A string containing the output of the stream as text
- * @throws IOException on errors reading text from the file
- */
- public static String getStreamAsString(final InputStream textStream) throws IOException {
- return getReaderAsString(new BufferedReader(new InputStreamReader(textStream)));
- }
-
- /**
- * Method to return the contents of a reader steam as a string. This closes the reader after use
- *
- * @param textReader The reader
- * @return A string containing the output of the reader as text
- * @throws IOException on errors reading text from the file
- */
- public static String getReaderAsString(final BufferedReader textReader) throws IOException {
-
- final StringBuilder builder = new StringBuilder();
- int charsRead = -1;
- final char[] chars = new char[READER_CHAR_BUFFER_SIZE_4096];
- do {
- charsRead = textReader.read(chars, 0, chars.length);
- if (charsRead > 0) {
- builder.append(chars, 0, charsRead);
- }
- }
- while (charsRead > 0);
- return builder.toString();
- }
-}
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import java.util.Arrays;
import org.junit.Test;
-import org.onap.policy.apex.model.utilities.DirectoryUtils;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
public class DirectoryUtilsTest {
@Test
public void test() throws IOException {
DirectoryUtils.emptyDirectory(new File("/i/dont/exist"));
-
+
File tempDir = Files.createTempDirectory("test").toFile();
Files.createTempDirectory(tempDir.toPath(), "testsubprefix");
TextFileUtils.putStringAsTextFile("Temp File 0 contents", tempDir.getAbsolutePath() + "/tempFile0.tmp");
TextFileUtils.putStringAsTextFile("Temp File 1 contents", tempDir.getAbsolutePath() + "/tempFile1.tmp");
-
+
DirectoryUtils.emptyDirectory(tempDir);
-
+
DirectoryUtils.getLocalTempDirectory(null);
-
+
byte[] byteArray = new byte[] {0, 0, 0};
DirectoryUtils.getLocalTempDirectory(Arrays.toString(byteArray));
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import java.io.IOException;
import org.junit.Test;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* Test text file utilities.
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class TextFileUtilsTest {
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* The Class TestAvroSchemaAai.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
- * @version
+ * @version
*/
public class AvroSchemaAaiTest {
private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1");
public void initTest() throws IOException {
schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1"));
ModelService.registerModel(AxContextSchemas.class, schemas);
-
+
aaiInventoryResponseSchema =
TextFileUtils.getTextFileAsString("src/test/resources/avsc/AAIInventoryResponseItemType.avsc");
}
schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME);
schemaParameters.getSchemaHelperParameterMap().put("AVRO", new AvroSchemaHelperParameters());
ParameterService.register(schemaParameters);
-
+
}
/**
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
// TODO: Auto-generated Javadoc
/**
* The Class TestAvroSchemaArray.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
- * @version
+ * @version
*/
public class AvroSchemaArrayTest {
private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1");
schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME);
schemaParameters.getSchemaHelperParameterMap().put("AVRO", new AvroSchemaHelperParameters());
ParameterService.register(schemaParameters);
-
+
}
/**
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
// TODO: Auto-generated Javadoc
/**
* The Class TestAvroSchemaEnum.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
- * @version
+ * @version
*/
public class AvroSchemaEnumTest {
private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1");
schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME);
schemaParameters.getSchemaHelperParameterMap().put("AVRO", new AvroSchemaHelperParameters());
ParameterService.register(schemaParameters);
-
+
}
/**
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* The Class TestAvroSchemaFixed.
*/
@Test
public void testFixedInit() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO",
- fixedSchema);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", fixedSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
fail("Test should throw an exception here");
} catch (final Exception e) {
assertEquals("AvroTest:0.0.1: could not create an instance "
- + "of class \"org.apache.avro.generic.GenericData$Fixed\" "
- + "using the default constructor \"Fixed()\"", e.getMessage());
+ + "of class \"org.apache.avro.generic.GenericData$Fixed\" "
+ + "using the default constructor \"Fixed()\"", e.getMessage());
}
final String inString = TextFileUtils.getTextFileAsString("src/test/resources/data/FixedExampleGood.json");
*/
@Test
public void testFixedUnmarshalMarshal() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroArray", "0.0.1"), "AVRO",
- fixedSchema);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroArray", "0.0.1"), "AVRO", fixedSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
fail("This test should throw an exception here");
} catch (final Exception e) {
assertEquals("AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: Expected fixed. Got VALUE_NULL",
- e.getMessage());
+ e.getMessage());
}
try {
testUnmarshalMarshal(schemaHelper, "src/test/resources/data/FixedExampleNull.json");
fail("This test should throw an exception here");
} catch (final Exception e) {
assertEquals("AvroTest:0.0.1: object \"null\" Avro unmarshalling failed: Expected fixed. Got VALUE_NULL",
- e.getMessage());
+ e.getMessage());
}
try {
testUnmarshalMarshal(schemaHelper, "src/test/resources/data/FixedExampleBad0.json");
fail("This test should throw an exception here");
} catch (final Exception e) {
assertEquals("AvroTest:0.0.1: object \"\"BADBAD\"\" "
- + "Avro unmarshalling failed: Expected fixed length 64, but got6", e.getMessage());
+ + "Avro unmarshalling failed: Expected fixed length 64, but got6", e.getMessage());
}
try {
testUnmarshalMarshal(schemaHelper, "src/test/resources/data/FixedExampleBad1.json");
fail("This test should throw an exception here");
} catch (final Exception e) {
assertEquals("AvroTest:0.0.1: object "
- + "\"\"0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0\"\" "
- + "Avro unmarshalling failed: Expected fixed length 64, but got65", e.getMessage());
+ + "\"\"0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0\"\" "
+ + "Avro unmarshalling failed: Expected fixed length 64, but got65", e.getMessage());
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* The Class TestAvroSchemaMap.
ModelService.registerModel(AxContextSchemas.class, schemas);
longMapSchema = TextFileUtils.getTextFileAsString("src/test/resources/avsc/MapExampleLong.avsc");
addressMapSchema = TextFileUtils.getTextFileAsString("src/test/resources/avsc/MapExampleAddress.avsc");
- addressMapSchemaInvalidFields = TextFileUtils
- .getTextFileAsString("src/test/resources/avsc/MapExampleAddressInvalidFields.avsc");
+ addressMapSchemaInvalidFields =
+ TextFileUtils.getTextFileAsString("src/test/resources/avsc/MapExampleAddressInvalidFields.avsc");
}
/**
*/
@Test
public void testMapInit() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO",
- addressMapSchema);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", addressMapSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
final HashMap<?, ?> newMapFull = (HashMap<?, ?>) schemaHelper.createNewInstance(inString);
assertEquals("{\"streetaddress\": \"221 B Baker St.\", \"city\": \"London\"}",
- newMapFull.get(new Utf8("address2")).toString());
+ newMapFull.get(new Utf8("address2")).toString());
}
/**
*/
@Test
public void testLongMapUnmarshalMarshal() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroMap", "0.0.1"), "AVRO",
- longMapSchema);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroMap", "0.0.1"), "AVRO", longMapSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
*/
@Test
public void testAddressMapUnmarshalMarshal() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroMap", "0.0.1"), "AVRO",
- addressMapSchema);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroMap", "0.0.1"), "AVRO", addressMapSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
*/
@Test
public void testSubRecordCreateRecord() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroMap", "0.0.1"), "AVRO",
- addressMapSchema);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroMap", "0.0.1"), "AVRO", addressMapSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
*/
@Test
public void testAddressMapUnmarshalMarshalInvalidFields() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroMap", "0.0.1"), "AVRO",
- addressMapSchemaInvalidFields);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroMap", "0.0.1"), "AVRO", addressMapSchemaInvalidFields);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
-// TODO: Auto-generated Javadoc
/**
* The Class TestAvroSchemaRecord.
*
recordSchema = TextFileUtils.getTextFileAsString("src/test/resources/avsc/RecordExample.avsc");
recordSchemaVpn = TextFileUtils.getTextFileAsString("src/test/resources/avsc/RecordExampleVPN.avsc");
recordSchemaVpnReuse = TextFileUtils.getTextFileAsString("src/test/resources/avsc/RecordExampleVPNReuse.avsc");
- recordSchemaInvalidFields = TextFileUtils
- .getTextFileAsString("src/test/resources/avsc/RecordExampleInvalidFields.avsc");
+ recordSchemaInvalidFields =
+ TextFileUtils.getTextFileAsString("src/test/resources/avsc/RecordExampleInvalidFields.avsc");
}
/**
*/
@Test
public void testRecordInit() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO",
- recordSchema);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", recordSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
*/
@Test
public void testRecordUnmarshalMarshal() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO",
- recordSchema);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", recordSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
*/
@Test
public void testRecordCreateRecord() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO",
- recordSchema);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", recordSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
fail("test should throw an exception here");
} catch (ContextRuntimeException cre) {
assertEquals("AvroTest:0.0.1: the schema \"User\" does not have a subtype of type \"IDontExist\"",
- cre.getMessage());
+ cre.getMessage());
}
}
*/
@Test
public void testRecordUnmarshalMarshalInvalid() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO",
- recordSchemaInvalidFields);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", recordSchemaInvalidFields);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
*/
@Test
public void testVpnRecordUnmarshalMarshal() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO",
- recordSchemaVpn);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", recordSchemaVpn);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
*/
@Test
public void testVpnRecordReuse() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO",
- recordSchemaVpnReuse);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", recordSchemaVpnReuse);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* The Class TestAvroSchemaUnion.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
- * @version
+ * @version
*/
public class AvroSchemaUnionTest {
private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1");
@Test
public void testUnionAllFields() throws IOException {
final AxContextSchema avroSchema =
- new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema);
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
@Test
public void testUnionOptionalField() throws IOException {
final AxContextSchema avroSchema =
- new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema);
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
final String inString =
- TextFileUtils.getTextFileAsString("src/test/resources/data/UnionExampleOptionalField.json");
+ TextFileUtils.getTextFileAsString("src/test/resources/data/UnionExampleOptionalField.json");
final GenericRecord user = (GenericRecord) schemaHelper.createNewInstance(inString);
assertEquals("Ben", user.get("name").toString());
@Test
public void testUnionNullField() throws IOException {
final AxContextSchema avroSchema =
- new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema);
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* The Class TestHealthCheckSchema.
*/
@Test
public void testHealthCheck() throws IOException {
- final AxContextSchema avroSchema = new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO",
- healthCheckSchema);
+ final AxContextSchema avroSchema =
+ new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", healthCheckSchema);
schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
final GenericRecord inputRecord = new GenericData.Record(healthCheckRecordSchema.getField("input").schema());
final Schema inputRecordRecordSchema = inputRecord.getSchema();
- final GenericRecord actionIndentifiersRecord = new GenericData.Record(
- inputRecordRecordSchema.getField("action_DasH_identifiers").schema());
+ final GenericRecord actionIndentifiersRecord =
+ new GenericData.Record(inputRecordRecordSchema.getField("action_DasH_identifiers").schema());
- final GenericRecord commonHeaderRecord = new GenericData.Record(
- inputRecordRecordSchema.getField("common_DasH_header").schema());
+ final GenericRecord commonHeaderRecord =
+ new GenericData.Record(inputRecordRecordSchema.getField("common_DasH_header").schema());
final Schema commonHeaderRecordSchema = commonHeaderRecord.getSchema();
- final GenericRecord commonHeaderFlagsRecord = new GenericData.Record(
- commonHeaderRecordSchema.getField("flags").schema());
+ final GenericRecord commonHeaderFlagsRecord =
+ new GenericData.Record(commonHeaderRecordSchema.getField("flags").schema());
healthCheckRecord.put("input", inputRecord);
inputRecord.put("action_DasH_identifiers", actionIndentifiersRecord);
inputRecord.put("action", "HealthCheck");
inputRecord.put("payload", "{\"host-ip-address\":\"131.160.203.125\",\"input.url\":\"131.160.203.125/afr\","
- + "\"request-action-type\":\"GET\",\"request-action\":\"AFR\"}");
+ + "\"request-action-type\":\"GET\",\"request-action\":\"AFR\"}");
actionIndentifiersRecord.put("vnf_DasH_id", "49414df5-3482-4fd8-9952-c463dff2770b");
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
import org.onap.policy.apex.model.eventmodel.concepts.AxEvents;
import org.onap.policy.apex.model.eventmodel.concepts.AxField;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.service.engine.event.ApexEvent;
import org.onap.policy.apex.service.engine.event.ApexEventException;
import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.HeaderDelimitedTextBlockReader;
import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.TextBlock;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* The Class TestYamlEventProtocol.
AxContextSchemas schemas = new AxContextSchemas();
- AxContextSchema simpleIntSchema = new AxContextSchema(new AxArtifactKey("SimpleIntSchema", "0.0.1"), "JAVA",
- "java.lang.Integer");
+ AxContextSchema simpleIntSchema =
+ new AxContextSchema(new AxArtifactKey("SimpleIntSchema", "0.0.1"), "JAVA", "java.lang.Integer");
schemas.getSchemasMap().put(simpleIntSchema.getKey(), simpleIntSchema);
- AxContextSchema simpleDoubleSchema = new AxContextSchema(new AxArtifactKey("SimpleDoubleSchema", "0.0.1"),
- "JAVA", "java.lang.Double");
+ AxContextSchema simpleDoubleSchema =
+ new AxContextSchema(new AxArtifactKey("SimpleDoubleSchema", "0.0.1"), "JAVA", "java.lang.Double");
schemas.getSchemasMap().put(simpleDoubleSchema.getKey(), simpleDoubleSchema);
- AxContextSchema simpleStringSchema = new AxContextSchema(new AxArtifactKey("SimpleStringSchema", "0.0.1"),
- "JAVA", "java.lang.String");
+ AxContextSchema simpleStringSchema =
+ new AxContextSchema(new AxArtifactKey("SimpleStringSchema", "0.0.1"), "JAVA", "java.lang.String");
schemas.getSchemasMap().put(simpleStringSchema.getKey(), simpleStringSchema);
- AxContextSchema arrayListSchema = new AxContextSchema(new AxArtifactKey("ArrayListSchema", "0.0.1"), "JAVA",
- "java.util.ArrayList");
+ AxContextSchema arrayListSchema =
+ new AxContextSchema(new AxArtifactKey("ArrayListSchema", "0.0.1"), "JAVA", "java.util.ArrayList");
schemas.getSchemasMap().put(arrayListSchema.getKey(), arrayListSchema);
AxContextSchema linkedHashMapSchema = new AxContextSchema(new AxArtifactKey("LinkedHashMapSchema", "0.0.1"),
- "JAVA", "java.util.LinkedHashMap");
+ "JAVA", "java.util.LinkedHashMap");
schemas.getSchemasMap().put(linkedHashMapSchema.getKey(), linkedHashMapSchema);
ModelService.registerModel(AxContextSchemas.class, schemas);
AxEvent testEvent1 = new AxEvent(new AxArtifactKey("TestEvent1", "0.0.1"));
testEvent1.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml");
- AxField te1Field0 = new AxField(new AxReferenceKey(testEvent1.getKey(), "yaml_field"),
- arrayListSchema.getKey());
+ AxField te1Field0 =
+ new AxField(new AxReferenceKey(testEvent1.getKey(), "yaml_field"), arrayListSchema.getKey());
testEvent1.getParameterMap().put("yaml_field", te1Field0);
events.getEventMap().put(testEvent1.getKey(), testEvent1);
AxEvent testEvent4 = new AxEvent(new AxArtifactKey("TestEvent4", "0.0.1"));
testEvent4.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml");
- AxField te4Field0 = new AxField(new AxReferenceKey(testEvent4.getKey(), "yaml_field"),
- arrayListSchema.getKey());
+ AxField te4Field0 =
+ new AxField(new AxReferenceKey(testEvent4.getKey(), "yaml_field"), arrayListSchema.getKey());
testEvent4.getParameterMap().put("yaml_field", te4Field0);
events.getEventMap().put(testEvent4.getKey(), testEvent4);
AxEvent testEvent5 = new AxEvent(new AxArtifactKey("TestEvent5", "0.0.1"));
testEvent5.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml");
- AxField te5Field0 = new AxField(new AxReferenceKey(testEvent5.getKey(), "yaml_field"),
- arrayListSchema.getKey());
+ AxField te5Field0 =
+ new AxField(new AxReferenceKey(testEvent5.getKey(), "yaml_field"), arrayListSchema.getKey());
testEvent5.getParameterMap().put("yaml_field", te5Field0);
events.getEventMap().put(testEvent5.getKey(), testEvent5);
AxEvent testEvent6 = new AxEvent(new AxArtifactKey("TestEvent6", "0.0.1"));
testEvent6.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml");
- AxField te6Field0 = new AxField(new AxReferenceKey(testEvent6.getKey(), "MarkMcGwire"),
- linkedHashMapSchema.getKey());
+ AxField te6Field0 =
+ new AxField(new AxReferenceKey(testEvent6.getKey(), "MarkMcGwire"), linkedHashMapSchema.getKey());
testEvent6.getParameterMap().put("Mark McGwire", te6Field0);
- AxField te6Field1 = new AxField(new AxReferenceKey(testEvent6.getKey(), "SammySosa"),
- linkedHashMapSchema.getKey());
+ AxField te6Field1 =
+ new AxField(new AxReferenceKey(testEvent6.getKey(), "SammySosa"), linkedHashMapSchema.getKey());
testEvent6.getParameterMap().put("Sammy Sosa", te6Field1);
events.getEventMap().put(testEvent6.getKey(), testEvent6);
AxEvent testEvent9 = new AxEvent(new AxArtifactKey("TestEvent9", "0.0.1"));
testEvent9.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml");
- AxField te9Field0 = new AxField(new AxReferenceKey(testEvent9.getKey(), "ChicagoCubs"),
- arrayListSchema.getKey());
+ AxField te9Field0 =
+ new AxField(new AxReferenceKey(testEvent9.getKey(), "ChicagoCubs"), arrayListSchema.getKey());
testEvent9.getParameterMap().put("ChicagoCubs", te9Field0);
- AxField te9Field1 = new AxField(new AxReferenceKey(testEvent9.getKey(), "AtlantaBraves"),
- arrayListSchema.getKey());
+ AxField te9Field1 =
+ new AxField(new AxReferenceKey(testEvent9.getKey(), "AtlantaBraves"), arrayListSchema.getKey());
testEvent9.getParameterMap().put("AtlantaBraves", te9Field1);
events.getEventMap().put(testEvent9.getKey(), testEvent9);
AxEvent testEvent10 = new AxEvent(new AxArtifactKey("TestEvent10", "0.0.1"));
testEvent10.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml");
- AxField te10Field0 = new AxField(new AxReferenceKey(testEvent10.getKey(), "yaml_field"),
- arrayListSchema.getKey());
+ AxField te10Field0 =
+ new AxField(new AxReferenceKey(testEvent10.getKey(), "yaml_field"), arrayListSchema.getKey());
testEvent10.getParameterMap().put("yaml_field", te10Field0);
events.getEventMap().put(testEvent10.getKey(), testEvent10);
AxEvent testEvent11 = new AxEvent(new AxArtifactKey("TestEvent11", "0.0.1"));
testEvent11.setNameSpace("org.onap.policy.apex.plugins.event.protocol.yaml");
AxField te11Field0 = new AxField(new AxReferenceKey(testEvent11.getKey(), "tosca_definitions_version"),
- simpleStringSchema.getKey());
+ simpleStringSchema.getKey());
testEvent11.getParameterMap().put("tosca_definitions_version", te11Field0);
- AxField te11Field1 = new AxField(new AxReferenceKey(testEvent11.getKey(), "description"),
- simpleStringSchema.getKey(), true);
+ AxField te11Field1 =
+ new AxField(new AxReferenceKey(testEvent11.getKey(), "description"), simpleStringSchema.getKey(), true);
testEvent11.getParameterMap().put("description", te11Field1);
- AxField te11Field2 = new AxField(new AxReferenceKey(testEvent11.getKey(), "node_types"),
- linkedHashMapSchema.getKey(), true);
+ AxField te11Field2 =
+ new AxField(new AxReferenceKey(testEvent11.getKey(), "node_types"), linkedHashMapSchema.getKey(), true);
testEvent11.getParameterMap().put("node_types", te11Field2);
AxField te11Field3 = new AxField(new AxReferenceKey(testEvent11.getKey(), "topology_template"),
- linkedHashMapSchema.getKey());
+ linkedHashMapSchema.getKey());
testEvent11.getParameterMap().put("topology_template", te11Field3);
events.getEventMap().put(testEvent11.getKey(), testEvent11);
* @throws IOException Signals that an I/O exception has occurred.
*/
private void testYamlDecodeEncode(final String eventName, final int eventCount, final int parCount,
- final String fileName) throws ApexEventException, IOException {
+ final String fileName) throws ApexEventException, IOException {
YamlEventProtocolParameters parameters = new YamlEventProtocolParameters();
parameters.setDelimiterAtStart(false);
String eventYaml = (String) converter.fromApexEvent(eventList.get(eventNo));
String expectedYaml = TextFileUtils
- .getTextFileAsString("src/test/resources/yaml_out/" + fileName + '_' + eventNo + ".yaml");
+ .getTextFileAsString("src/test/resources/yaml_out/" + fileName + '_' + eventNo + ".yaml");
assertEquals(expectedYaml.replaceAll("\\s*", ""), eventYaml.replaceAll("\\s*", ""));
}
}
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;
+
import lombok.Getter;
import lombok.Setter;
+
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.service.ModelService;
import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
import org.onap.policy.apex.model.policymodel.handling.PolicyModelMerger;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.service.engine.engdep.EngDepMessagingService;
import org.onap.policy.apex.service.engine.event.ApexEventException;
import org.onap.policy.apex.service.engine.runtime.EngineService;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
/**
- * This class wraps an Apex engine so that it can be activated as a complete service together with
- * all its context, executor, and event plugins.
+ * This class wraps an Apex engine so that it can be activated as a complete service together with all its context,
+ * executor, and event plugins.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
ApexParameters apexParameters = apexParametersMap.values().iterator().next();
// totalInstanceCount is the sum of instance counts required as per each policy
int totalInstanceCount = apexParametersMap.values().stream()
- .mapToInt(p -> p.getEngineServiceParameters().getInstanceCount()).sum();
+ .mapToInt(p -> p.getEngineServiceParameters().getInstanceCount()).sum();
apexParameters.getEngineServiceParameters().setInstanceCount(totalInstanceCount);
instantiateEngine(apexParameters);
setUpModelMarhsallerAndUnmarshaller(apexParameters);
for (Entry<ToscaPolicyIdentifier, ApexParameters> apexParamsEntry : apexParametersMap.entrySet()) {
ApexParameters apexParams = apexParamsEntry.getValue();
boolean duplicateInputParameterExist =
- apexParams.getEventInputParameters().keySet().stream().anyMatch(inputParametersMap::containsKey);
+ apexParams.getEventInputParameters().keySet().stream().anyMatch(inputParametersMap::containsKey);
boolean duplicateOutputParameterExist =
- apexParams.getEventOutputParameters().keySet().stream().anyMatch(outputParametersMap::containsKey);
+ apexParams.getEventOutputParameters().keySet().stream().anyMatch(outputParametersMap::containsKey);
if (duplicateInputParameterExist || duplicateOutputParameterExist) {
LOGGER.error("I/O Parameters for {}:{} has duplicates. So this policy is not executed.",
- apexParamsEntry.getKey().getName(), apexParamsEntry.getKey().getVersion());
+ apexParamsEntry.getKey().getName(), apexParamsEntry.getKey().getVersion());
apexParametersMap.remove(apexParamsEntry.getKey());
continue;
}
// Check if a policy model file has been specified
if (apexParams.getEngineServiceParameters().getPolicyModelFileName() != null) {
LOGGER.debug("deploying policy model in \"{}\" to the apex engines . . .",
- apexParams.getEngineServiceParameters().getPolicyModelFileName());
+ apexParams.getEngineServiceParameters().getPolicyModelFileName());
- final String policyModelString =
- TextFileUtils.getTextFileAsString(apexParams.getEngineServiceParameters().getPolicyModelFileName());
+ final String policyModelString = TextFileUtils
+ .getTextFileAsString(apexParams.getEngineServiceParameters().getPolicyModelFileName());
AxPolicyModel policyModel = EngineServiceImpl
- .createModel(apexParams.getEngineServiceParameters().getEngineKey(), policyModelString);
+ .createModel(apexParams.getEngineServiceParameters().getEngineKey(), policyModelString);
policyModelsMap.put(apexParamsEntry.getKey(), policyModel);
}
}
AxPolicyModel finalPolicyModel = aggregatePolicyModels(policyModelsMap);
// Set the policy model in the engine
apexEngineService.updateModel(apexParameters.getEngineServiceParameters().getEngineKey(), finalPolicyModel,
- true);
+ true);
setUpMarshallerAndUnmarshaller(apexParameters.getEngineServiceParameters(), inputParametersMap,
- outputParametersMap);
+ outputParametersMap);
setUpMarshalerPairings(inputParametersMap);
}
ToscaPolicyIdentifier tempId = new ToscaPolicyIdentifier(firstEntry.getKey());
AxPolicyModel tempModel = new AxPolicyModel(firstEntry.getValue());
Stream<Entry<ToscaPolicyIdentifier, AxPolicyModel>> policyModelStream =
- policyModelsMap.entrySet().stream().skip(1);
+ policyModelsMap.entrySet().stream().skip(1);
Entry<ToscaPolicyIdentifier, AxPolicyModel> finalPolicyModelEntry =
- policyModelStream.reduce(firstEntry, ((entry1, entry2) -> {
- try {
- entry1.setValue(
- PolicyModelMerger.getMergedPolicyModel(entry1.getValue(), entry2.getValue(), true, true));
- } catch (ApexModelException exc) {
- LOGGER.error("Policy model for {} : {} is having duplicates. So this policy is not executed.",
- entry2.getKey().getName(), entry2.getKey().getVersion(), exc);
- apexParametersMap.remove(entry2.getKey());
- policyModelsMap.remove(entry2.getKey());
- }
- return entry1;
- }));
+ policyModelStream.reduce(firstEntry, ((entry1, entry2) -> {
+ try {
+ entry1.setValue(PolicyModelMerger.getMergedPolicyModel(entry1.getValue(), entry2.getValue(),
+ true, true));
+ } catch (ApexModelException exc) {
+ LOGGER.error("Policy model for {} : {} is having duplicates. So this policy is not executed.",
+ entry2.getKey().getName(), entry2.getKey().getVersion(), exc);
+ apexParametersMap.remove(entry2.getKey());
+ policyModelsMap.remove(entry2.getKey());
+ }
+ return entry1;
+ }));
AxPolicyModel finalPolicyModel = new AxPolicyModel(finalPolicyModelEntry.getValue());
policyModelsMap.put(tempId, tempModel); // put back the original first entry into the policyModelsMap
return finalPolicyModel;
}
private void setUpMarshallerAndUnmarshaller(EngineServiceParameters engineServiceParameters,
- Map<String, EventHandlerParameters> inputParametersMap, Map<String, EventHandlerParameters> outputParametersMap)
- throws ApexEventException {
+ Map<String, EventHandlerParameters> inputParametersMap,
+ Map<String, EventHandlerParameters> outputParametersMap) throws ApexEventException {
// Producer parameters specify what event marshalers to handle events leaving Apex are
// set up and how they are set up
for (Entry<String, EventHandlerParameters> outputParameters : outputParametersMap.entrySet()) {
final ApexEventMarshaller marshaller = new ApexEventMarshaller(outputParameters.getKey(),
- engineServiceParameters, outputParameters.getValue());
+ engineServiceParameters, outputParameters.getValue());
marshaller.init();
apexEngineService.registerActionListener(outputParameters.getKey(), marshaller);
marshallerMap.put(outputParameters.getKey(), marshaller);
// are set up and how they are set up
for (final Entry<String, EventHandlerParameters> inputParameters : inputParametersMap.entrySet()) {
final ApexEventUnmarshaller unmarshaller = new ApexEventUnmarshaller(inputParameters.getKey(),
- engineServiceParameters, inputParameters.getValue());
+ engineServiceParameters, inputParameters.getValue());
unmarshallerMap.put(inputParameters.getKey(), unmarshaller);
unmarshaller.init(engineServiceHandler);
}
private void instantiateEngine(ApexParameters apexParameters) throws ApexException {
if (null != apexEngineService
- && apexEngineService.getKey().equals(apexParameters.getEngineServiceParameters().getEngineKey())) {
+ && apexEngineService.getKey().equals(apexParameters.getEngineServiceParameters().getEngineKey())) {
throw new ApexException("Apex Engine already initialized.");
}
// Create engine with specified thread count
}
/**
- * Set up unmarshaler/marshaler pairing for synchronized event handling. We only need to
- * traverse the unmarshalers because the
- * unmarshalers and marshalers are paired one to one uniquely so if we find a
- * synchronized unmarshaler we'll also find its
- * paired marshaler
+ * Set up unmarshaler/marshaler pairing for synchronized event handling. We only need to traverse the unmarshalers
+ * because the unmarshalers and marshalers are paired one to one uniquely so if we find a synchronized unmarshaler
+ * we'll also find its paired marshaler
+ *
* @param inputParametersMap the apex parameters
*/
private void setUpMarshalerPairings(Map<String, EventHandlerParameters> inputParametersMap) {
/**
* Updates the APEX Engine with the model created from new Policies.
*
- * @param apexParamsMap the apex parameters map for the Apex service
+ * @param apexParamsMap the apex parameters map for the Apex service
* @throws ApexException on errors
*/
public void updateModel(Map<ToscaPolicyIdentifier, ApexParameters> apexParamsMap) throws ApexException {
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
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;
import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters;
import org.onap.policy.apex.service.engine.event.testpojos.DummyPojo;
import org.onap.policy.apex.service.engine.event.testpojos.DummyPojoList;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
/**
* Test JSON Event Handler.
- *
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class JsonEventHandlerForPojoTest {
*/
@BeforeClass
public static void setupEventModel() throws IOException, ApexModelException {
- final String policyModelString = TextFileUtils
- .getTextFileAsString("src/test/resources/policymodels/PojoEventModel.json");
+ final String policyModelString =
+ TextFileUtils.getTextFileAsString("src/test/resources/policymodels/PojoEventModel.json");
final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<AxPolicyModel>(AxPolicyModel.class);
modelReader.setValidateFlag(false);
final AxPolicyModel apexPolicyModel = modelReader.read(new ByteArrayInputStream(policyModelString.getBytes()));
pars.setPojoField("POJO_PAR");
jsonEventConverter.init(pars);
- final String apexEventJsonStringIn = TextFileUtils
- .getTextFileAsString("src/test/resources/events/TestPojoEvent.json");
+ final String apexEventJsonStringIn =
+ TextFileUtils.getTextFileAsString("src/test/resources/events/TestPojoEvent.json");
logger.debug("input event\n" + apexEventJsonStringIn);
pars.setPojoField("POJO_LIST_PAR");
jsonEventConverter.init(pars);
- final String apexEventJsonStringIn = TextFileUtils
- .getTextFileAsString("src/test/resources/events/TestPojoListEvent.json");
+ final String apexEventJsonStringIn =
+ TextFileUtils.getTextFileAsString("src/test/resources/events/TestPojoListEvent.json");
logger.debug("input event\n" + apexEventJsonStringIn);
pars.setPojoField("BAD_POJO_PAR");
jsonEventConverter.init(pars);
- final String apexEventJsonStringIn = TextFileUtils
- .getTextFileAsString("src/test/resources/events/TestPojoEvent.json");
+ final String apexEventJsonStringIn =
+ TextFileUtils.getTextFileAsString("src/test/resources/events/TestPojoEvent.json");
logger.debug("input event\n" + apexEventJsonStringIn);
jsonEventConverter.toApexEvent("PojoEvent", apexEventJsonStringIn);
fail("test should throw an exception");
} catch (Exception tae) {
- assertEquals("Failed to unmarshal JSON event: error parsing PojoEvent:0.0.1 event from Json. "
+ assertEquals(
+ "Failed to unmarshal JSON event: error parsing PojoEvent:0.0.1 event from Json. "
+ "Field BAD_POJO_PAR not found on POJO event definition.",
- tae.getMessage().substring(0, 133));
+ tae.getMessage().substring(0, 133));
}
pars.setPojoField("POJO_PAR");
jsonEventConverter.toApexEvent("PojoNoFieldEvent", apexEventJsonStringIn);
fail("test should throw an exception");
} catch (Exception tae) {
- assertEquals("Failed to unmarshal JSON event: error parsing PojoNoFieldEvent:0.0.1 event from Json, "
+ assertEquals(
+ "Failed to unmarshal JSON event: error parsing PojoNoFieldEvent:0.0.1 event from Json, "
+ "Field POJO_PAR not found, no fields defined on event.",
- tae.getMessage().substring(0, 139));
+ tae.getMessage().substring(0, 139));
}
try {
jsonEventConverter.toApexEvent("PojoTooManyFieldsEvent", apexEventJsonStringIn);
fail("test should throw an exception");
} catch (Exception tae) {
- assertEquals("Failed to unmarshal JSON event: error parsing PojoTooManyFieldsEvent:0.0.1 event from Json, "
+ assertEquals(
+ "Failed to unmarshal JSON event: error parsing PojoTooManyFieldsEvent:0.0.1 event from Json, "
+ "Field POJO_PAR, one and only one field may be defined on a POJO event definition.",
- tae.getMessage().substring(0, 173));
+ tae.getMessage().substring(0, 173));
}
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
import org.onap.policy.apex.model.eventmodel.concepts.AxEvents;
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;
import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
/**
* Test JSON Event Handler.
- *
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class JsonEventHandlerTest {
*/
@BeforeClass
public static void setupEventModel() throws IOException, ApexModelException {
- final String policyModelString = TextFileUtils
- .getTextFileAsString("src/test/resources/policymodels/SmallModel.json");
+ final String policyModelString =
+ TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModel.json");
final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<AxPolicyModel>(AxPolicyModel.class);
final AxPolicyModel apexPolicyModel = modelReader.read(new ByteArrayInputStream(policyModelString.getBytes()));
fail("Test should throw an exception here");
} catch (final ApexEventException e) {
assertEquals("Failed to unmarshal JSON event: event received without mandatory parameter \"name\" ",
- e.getMessage().substring(0, 82));
+ e.getMessage().substring(0, 82));
}
try {
fail("Test should throw an exception here");
} catch (final ApexEventException e) {
assertEquals("Failed to unmarshal JSON event: field \"name\" with value \"%%%%\" is invalid",
- e.getMessage().substring(0, 73));
+ e.getMessage().substring(0, 73));
}
try {
fail("Test should throw an exception here");
} catch (final ApexEventException e) {
assertEquals("Failed to unmarshal JSON event: an event definition for an event named \"I_DONT_EXI",
- e.getMessage().substring(0, 82));
+ e.getMessage().substring(0, 82));
}
apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoVersion();
fail("Test should throw an exception here");
} catch (final ApexEventException e) {
assertEquals("Failed to unmarshal JSON event: field \"version\" with value \"#####\" is invalid",
- e.getMessage().substring(0, 77));
+ e.getMessage().substring(0, 77));
}
try {
jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
fail("Test should throw an exception here");
} catch (final ApexEventException e) {
- assertEquals("Failed to unmarshal JSON event: an event definition for an event named "
+ assertEquals(
+ "Failed to unmarshal JSON event: an event definition for an event named "
+ "\"BasicEvent\" with version \"1.2.3\" not found in Apex model",
- e.getMessage().substring(0, 128));
+ e.getMessage().substring(0, 128));
}
apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoNamespace();
jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
fail("Test should throw an exception here");
} catch (final ApexEventException e) {
- assertEquals("Failed to unmarshal JSON event: "
- + "field \"nameSpace\" with value \"hello.&&&&\" is invalid",
- e.getMessage().substring(0, 84));
+ assertEquals(
+ "Failed to unmarshal JSON event: " + "field \"nameSpace\" with value \"hello.&&&&\" is invalid",
+ e.getMessage().substring(0, 84));
}
try {
fail("Test should throw an exception here");
} catch (final ApexEventException e) {
assertEquals("Failed to unmarshal JSON event: namespace \"pie.in.the.sky\" "
- + "on event \"BasicEvent\" does not"
- + " match namespace \"org.onap.policy.apex.events\" "
- + "for that event in the Apex model", e.getMessage().substring(0, 168));
+ + "on event \"BasicEvent\" does not" + " match namespace \"org.onap.policy.apex.events\" "
+ + "for that event in the Apex model", e.getMessage().substring(0, 168));
}
apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoSource();
fail("Test should throw an exception here");
} catch (final ApexEventException e) {
assertEquals("Failed to unmarshal JSON event: field \"source\" with value \"%!@**@!\" is invalid",
- e.getMessage().substring(0, 78));
+ e.getMessage().substring(0, 78));
}
apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoTarget();
fail("Test should throw an exception here");
} catch (final ApexEventException e) {
assertEquals("Failed to unmarshal JSON event: field \"target\" with value \"KNIO(*S)A(S)D\" is invalid",
- e.getMessage().substring(0, 84));
+ e.getMessage().substring(0, 84));
}
try {
jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
fail("Test should throw an exception here");
} catch (final ApexEventException e) {
- assertEquals("Failed to unmarshal JSON event: error parsing BasicEvent:0.0.1 "
+ assertEquals(
+ "Failed to unmarshal JSON event: error parsing BasicEvent:0.0.1 "
+ "event from Json. Field \"intPar\" is missing, but is mandatory.",
- e.getMessage().substring(0, 124));
+ e.getMessage().substring(0, 124));
}
apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNullFields();
final Map<String, Object> basicEventMap = new HashMap<String, Object>();
basicEventMap.put("intPar", 12345);
- final ApexEvent basicEvent = new ApexEvent("BasicEvent", "0.0.1", "org.onap.policy.apex.events", "test",
- "apex");
+ final ApexEvent basicEvent =
+ new ApexEvent("BasicEvent", "0.0.1", "org.onap.policy.apex.events", "test", "apex");
basicEvent.putAll(basicEventMap);
final String apexEvent0000JsonString = (String) jsonEventConverter.fromApexEvent(basicEvent);
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
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.ApexEvent;
import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* Test the engine service implementation.
/**
* Read the models into strings.
- *
+ *
* @throws IOException on model reading errors
* @throws ApexModelException on model reading exceptions
*/
@BeforeClass
public static void readSimpleModel() throws IOException, ApexModelException {
- simpleModelString = TextFileUtils
- .getTextFileAsString("src/test/resources/policymodels/SmallModel.json");
+ simpleModelString = TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModel.json");
- differentModelString = TextFileUtils
- .getTextFileAsString("src/test/resources/policymodels/SmallModelDifferent.json");
+ differentModelString =
+ TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModelDifferent.json");
final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class);
simpleModel = modelReader.read(new ByteArrayInputStream(simpleModelString.getBytes()));
engineParameters.setName(EngineParameterConstants.MAIN_GROUP_NAME);
ExecutorParameters jsExecutorParameters = new ExecutorParameters();
jsExecutorParameters.setName("JAVASCRIPT");
- jsExecutorParameters.setTaskSelectionExecutorPluginClass(
- "org.onap.policy.apex.service.engine.runtime.impl.DummyTse");
+ jsExecutorParameters
+ .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse");
jsExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe");
- jsExecutorParameters.setStateFinalizerExecutorPluginClass(
- "org.onap.policy.apex.service.engine.runtime.impl.DummySfe");
+ jsExecutorParameters
+ .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe");
engineParameters.getExecutorParameterMap().put("JAVASCRIPT", jsExecutorParameters);
ExecutorParameters mvvelExecutorParameters = new ExecutorParameters();
mvvelExecutorParameters.setName("MVEL");
- mvvelExecutorParameters.setTaskSelectionExecutorPluginClass(
- "org.onap.policy.apex.service.engine.runtime.impl.DummyTse");
+ mvvelExecutorParameters
+ .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse");
mvvelExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe");
- mvvelExecutorParameters.setStateFinalizerExecutorPluginClass(
- "org.onap.policy.apex.service.engine.runtime.impl.DummySfe");
+ mvvelExecutorParameters
+ .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe");
engineParameters.getExecutorParameterMap().put("MVEL", jsExecutorParameters);
ParameterService.register(engineParameters);
}
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("start()<-Engine-0:0.0.1,STOPPED, cannot start engine, "
- + "engine has not been initialized, its model is not loaded", apEx.getMessage());
+ + "engine has not been initialized, its model is not loaded", apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("start()<-Engine-0:0.0.1,STOPPED, cannot start engine, "
- + "engine has not been initialized, its model is not loaded", apEx.getMessage());
+ + "engine has not been initialized, its model is not loaded", apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("Peiodic event geneation already running on engine Engine:0.0.1, ApexPeriodicEventGenerator "
- + "[period=100000, firstEventTime=0, lastEventTime=0, eventCount=0]", apEx.getMessage());
+ + "[period=100000, firstEventTime=0, lastEventTime=0, eventCount=0]", apEx.getMessage());
}
esImpl.stopPeriodicEvents();
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("engine service key DummyKey:0.0.1 does not match the keyEngine:0.0.1 of this engine service",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("engine service key DummyKey:0.0.1 does not match the keyEngine:0.0.1 of this engine service",
- apEx.getMessage());
+ apEx.getMessage());
}
}
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("apex model update failed, supplied model with key \"SmallModelDifferent:0.0.1\" is not a "
- + "compatible model update "
- + "from the existing engine model with key \"SmallModel:0.0.1\"",
- apEx.getMessage());
+ + "compatible model update " + "from the existing engine model with key \"SmallModel:0.0.1\"",
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("apex engine for engine key Engine-0:0.0.1 is already running with state READY",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("apex engine for engine key Engine-0:0.0.1 is already running with state READY",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("Peiodic event geneation already running on engine Engine:0.0.1, ApexPeriodicEventGenerator "
- + "[period=100000, firstEventTime=0, lastEventTime=0, eventCount=0]", apEx.getMessage());
+ + "[period=100000, firstEventTime=0, lastEventTime=0, eventCount=0]", apEx.getMessage());
}
esImpl.stopPeriodicEvents();
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
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.ApexEvent;
import org.onap.policy.apex.service.engine.main.ApexPolicyStatisticsManager;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.onap.policy.common.utils.services.Registry;
/**
public static void readSimpleModel() throws IOException, ApexModelException {
simpleModelString = TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModel.json");
- differentModelString = TextFileUtils
- .getTextFileAsString("src/test/resources/policymodels/SmallModelDifferent.json");
+ differentModelString =
+ TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModelDifferent.json");
final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class);
simpleModel = modelReader.read(new ByteArrayInputStream(simpleModelString.getBytes()));
engineParameters.setName(EngineParameterConstants.MAIN_GROUP_NAME);
ExecutorParameters jsExecutorParameters = new ExecutorParameters();
jsExecutorParameters.setName("JAVASCRIPT");
- jsExecutorParameters.setTaskSelectionExecutorPluginClass(
- "org.onap.policy.apex.service.engine.runtime.impl.DummyTse");
+ jsExecutorParameters
+ .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse");
jsExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe");
- jsExecutorParameters.setStateFinalizerExecutorPluginClass(
- "org.onap.policy.apex.service.engine.runtime.impl.DummySfe");
+ jsExecutorParameters
+ .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe");
engineParameters.getExecutorParameterMap().put("JAVASCRIPT", jsExecutorParameters);
ExecutorParameters mvvelExecutorParameters = new ExecutorParameters();
mvvelExecutorParameters.setName("MVEL");
- mvvelExecutorParameters.setTaskSelectionExecutorPluginClass(
- "org.onap.policy.apex.service.engine.runtime.impl.DummyTse");
+ mvvelExecutorParameters
+ .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse");
mvvelExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe");
- mvvelExecutorParameters.setStateFinalizerExecutorPluginClass(
- "org.onap.policy.apex.service.engine.runtime.impl.DummySfe");
+ mvvelExecutorParameters
+ .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe");
engineParameters.getExecutorParameterMap().put("MVEL", jsExecutorParameters);
ParameterService.register(engineParameters);
fail("test should throw an exception");
} catch (Exception apEx) {
assertEquals("getEngineServiceEventInterface() call is not allowed on an Apex Engine Worker",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("start()<-Worker:0.0.1,STOPPED, cannot start engine, engine has not been initialized, "
- + "its model is not loaded", apEx.getMessage());
+ + "its model is not loaded", apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("start()<-Worker:0.0.1,STOPPED, cannot start engine, "
- + "engine has not been initialized, its model is not loaded", apEx.getMessage());
+ + "engine has not been initialized, its model is not loaded", apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
- apEx.getMessage());
+ apEx.getMessage());
}
}
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("apex model update failed, supplied model with key \"SmallModelDifferent:0.0.1\" is not a "
- + "compatible model update "
- + "from the existing engine model with key \"SmallModel:0.0.1\"", apEx.getMessage());
+ + "compatible model update " + "from the existing engine model with key \"SmallModel:0.0.1\"",
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("apex engine for engine key Worker:0.0.1 is already running with state READY",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
fail("test should throw an exception");
} catch (ApexException apEx) {
assertEquals("apex engine for engine key Worker:0.0.1 is already running with state READY",
- apEx.getMessage());
+ apEx.getMessage());
}
try {
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.service.engine.main.ApexMain;
+import org.onap.policy.common.utils.resources.TextFileUtils;
public class BaseEventTest {
private static final long TIME_OUT_IN_MS = 10000;
long startWaitTime = System.currentTimeMillis();
long lastTotalSize = 0;
-
+
do {
long totalSize = 0;
if (totalSize >= totalExpectedSize) {
return;
}
-
+
// We're making progress, extend the timeout
if (totalSize > lastTotalSize) {
lastTotalSize = totalSize;
startWaitTime = System.currentTimeMillis();
}
-
+
ThreadUtilities.sleep(100);
}
while (TIME_OUT_IN_MS >= System.currentTimeMillis() - startWaitTime);
private int getEventCount(final String expectedFileName) throws IOException {
File expectedFile = new File(expectedFileName);
-
+
if (!expectedFile.exists()) {
return 0;
}
String expectedFileContents = TextFileUtils.getTextFileAsString(expectedFileName);
-
+
return StringUtils.countMatches(expectedFileContents, "{");
}
protected void testFileEvents(final String[] args, final String[] expectedFileNames, final long expectedFileSize)
- throws Exception {
+ throws Exception {
final ApexMain apexMain = new ApexMain(args);
waitForOutFiles(expectedFileNames, expectedFileSize);
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.service.engine.main.ApexMain;
+import org.onap.policy.common.utils.resources.TextFileUtils;
public class TestFile2File {
/**
/**
* Strip variable length text from file string.
- *
+ *
* @param textFileAsString the file to read and strip
* @return the stripped string
* @throws IOException on out file read exceptions
*/
private String stripVariableLengthText(final String outFile) throws IOException {
- return TextFileUtils.getTextFileAsString(outFile)
- .replaceAll("\\s+", "")
- .replaceAll(":\\d*\\.?\\d*,", ":0,")
- .replaceAll(":\\d*}", ":0}")
- .replaceAll("<value>\\d*\\.?\\d*</value>", "<value>0</value>");
+ return TextFileUtils.getTextFileAsString(outFile).replaceAll("\\s+", "").replaceAll(":\\d*\\.?\\d*,", ":0,")
+ .replaceAll(":\\d*}", ":0}").replaceAll("<value>\\d*\\.?\\d*</value>", "<value>0</value>");
}
}
-
-
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.service.engine.main.ApexMain;
+import org.onap.policy.common.utils.resources.TextFileUtils;
public class TestFile2FileFiltered {
/**
@Test
public void testJsonFilteredFileInOutEvents() throws MessagingException, ApexException, IOException {
+ // @formatter:off
final String[] args =
{ "-rfr", "target", "-c", "target/examples/config/SampleDomain/File2FileFilteredInOutJsonEvent.json" };
{ 22366, 19834 };
testFilteredFileEvents(args, outFilePaths, expectedFileSizes);
+ // @formatter:on
}
@Test
public void testJsonFilteredFileOutEvents() throws MessagingException, ApexException, IOException {
+ // @formatter:off
final String[] args =
{ "-rfr", "target", "-c", "target/examples/config/SampleDomain/File2FileFilteredOutJsonEvent.json" };
{ 22366, 19834 };
testFilteredFileEvents(args, outFilePaths, expectedFileSizes);
+ // @formatter:on
}
@Test
public void testJsonFilteredFileInEvents() throws MessagingException, ApexException, IOException {
+ // @formatter:off
final String[] args =
{ "-rfr", "target", "-c", "target/examples/config/SampleDomain/File2FileFilteredInJsonEvent.json" };
{ 22366 };
testFilteredFileEvents(args, outFilePaths, expectedFileSizes);
+ // @formatter:on
}
private void testFilteredFileEvents(final String[] args, final String[] outFilePaths,
- final long[] expectedFileSizes) throws MessagingException, ApexException, IOException {
+ final long[] expectedFileSizes) throws MessagingException, ApexException, IOException {
final ApexMain apexMain = new ApexMain(args);
final File outFile0 = new File(outFilePaths[0]);
/**
* Strip variable length text from file string.
- *
+ *
* @param textFileAsString the file to read and strip
* @return the stripped string
* @throws IOException on out file read exceptions
*/
private String stripVariableLengthText(final String outFile) throws IOException {
- return TextFileUtils.getTextFileAsString(outFile)
- .replaceAll("\\s+", "")
- .replaceAll(":\\d*\\.?\\d*,", ":0,")
- .replaceAll(":\\d*}", ":0}")
- .replaceAll("<value>\\d*\\.?\\d*</value>", "<value>0</value>");
+ return TextFileUtils.getTextFileAsString(outFile).replaceAll("\\s+", "").replaceAll(":\\d*\\.?\\d*,", ":0,")
+ .replaceAll(":\\d*}", ":0}").replaceAll("<value>\\d*\\.?\\d*</value>", "<value>0</value>");
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.service.engine.main.ApexMain;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* The Class TestFile2FileIgnore.
outFile.delete();
assertEquals(outFileSize, expectedFileSize);
}
-
/**
* Strip variable length text from file string.
- *
+ *
* @param textFileAsString the file to read and strip
* @return the stripped string
* @throws IOException on out file read exceptions
*/
private static String stripVariableLengthText(final String outFile) throws IOException {
- return TextFileUtils.getTextFileAsString(outFile)
- .replaceAll("\\s+", "")
- .replaceAll(":\\d*\\.?\\d*,", ":0,")
- .replaceAll(":\\d*}", ":0}")
- .replaceAll("<value>\\d*\\.?\\d*</value>", "<value>0</value>");
+ return TextFileUtils.getTextFileAsString(outFile).replaceAll("\\s+", "").replaceAll(":\\d*\\.?\\d*,", ":0,")
+ .replaceAll(":\\d*}", ":0}").replaceAll("<value>\\d*\\.?\\d*</value>", "<value>0</value>");
}
}
-
-
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.service.engine.main.ApexMain;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* The Class TestKafka2Kafka tests Kafka event sending and reception.
@ClassRule
public static final SharedKafkaTestResource sharedKafkaTestResource = new SharedKafkaTestResource()
- // Start a cluster with 1 brokers.
- .withBrokers(1)
- // Disable topic auto-creation.
- .withBrokerProperty("auto.create.topics.enable", "false");
+ // Start a cluster with 1 brokers.
+ .withBrokers(1)
+ // Disable topic auto-creation.
+ .withBrokerProperty("auto.create.topics.enable", "false");
/**
* Test json kafka events.
@Test
public void testJsonKafkaEvents() throws MessagingException, ApexException {
final String conditionedConfigFile = getConditionedConfigFile(
- "target" + File.separator + "examples/config/SampleDomain/Kafka2KafkaJsonEvent.json");
- final String[] args =
- { "-rfr", "target", "-c", conditionedConfigFile };
+ "target" + File.separator + "examples/config/SampleDomain/Kafka2KafkaJsonEvent.json");
+ final String[] args = {"-rfr", "target", "-c", conditionedConfigFile};
testKafkaEvents(args, false, "json");
}
@Test
public void testXmlKafkaEvents() throws MessagingException, ApexException {
final String conditionedConfigFile = getConditionedConfigFile(
- "target" + File.separator + "examples/config/SampleDomain/Kafka2KafkaXmlEvent.json");
- final String[] args =
- { "-rfr", "target", "-c", conditionedConfigFile };
+ "target" + File.separator + "examples/config/SampleDomain/Kafka2KafkaXmlEvent.json");
+ final String[] args = {"-rfr", "target", "-c", conditionedConfigFile};
testKafkaEvents(args, true, "xml");
}
* @throws ApexException the apex exception
*/
private void testKafkaEvents(String[] args, final Boolean xmlEvents, final String topicSuffix)
- throws MessagingException, ApexException {
+ throws MessagingException, ApexException {
sharedKafkaTestResource.getKafkaTestUtils().createTopic("apex-out-" + topicSuffix, 1, (short) 1);
sharedKafkaTestResource.getKafkaTestUtils().createTopic("apex-in-" + topicSuffix, 1, (short) 1);
- final KafkaEventSubscriber subscriber = new KafkaEventSubscriber("apex-out-" + topicSuffix,
- sharedKafkaTestResource);
+ final KafkaEventSubscriber subscriber =
+ new KafkaEventSubscriber("apex-out-" + topicSuffix, sharedKafkaTestResource);
final ApexMain apexMain = new ApexMain(args);
ThreadUtilities.sleep(3000);
final KafkaEventProducer producer = new KafkaEventProducer("apex-in-" + topicSuffix, sharedKafkaTestResource,
- EVENT_COUNT, xmlEvents, EVENT_INTERVAL);
+ EVENT_COUNT, xmlEvents, EVENT_INTERVAL);
producer.sendEvents();
// Wait for the producer to send all tis events
while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH
- && producer.getEventsSentCount() < EVENT_COUNT) {
+ && producer.getEventsSentCount() < EVENT_COUNT) {
ThreadUtilities.sleep(EVENT_INTERVAL);
}
while (System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH
- && subscriber.getEventsReceivedCount() < EVENT_COUNT) {
+ && subscriber.getEventsReceivedCount() < EVENT_COUNT) {
ThreadUtilities.sleep(EVENT_INTERVAL);
}
File tempConfigFile = File.createTempFile("Kafka_", ".json");
tempConfigFile.deleteOnExit();
String configAsString = TextFileUtils.getTextFileAsString(configurationFileName)
- .replaceAll("localhost:39902", sharedKafkaTestResource.getKafkaConnectString());
+ .replaceAll("localhost:39902", sharedKafkaTestResource.getKafkaConnectString());
TextFileUtils.putStringAsFile(configAsString, tempConfigFile.getCanonicalFile());
return tempConfigFile.getCanonicalPath();
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.service.engine.main.ApexMain;
import org.onap.policy.common.endpoints.http.server.HttpServletServer;
import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
import org.onap.policy.common.gson.GsonMessageBodyHandler;
import org.onap.policy.common.utils.network.NetworkUtil;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
*/
@Before
public void setUp() throws Exception {
- server = HttpServletServerFactoryInstance.getServerFactory().build(
- "TestRest2File", false, null, PORT, "/TestRest2File", false, false);
+ server = HttpServletServerFactoryInstance.getServerFactory().build("TestRest2File", false, null, PORT,
+ "/TestRest2File", false, false);
server.addServletClass(null, TestRestClientEndpoint.class.getName());
server.setSerializationProvider(GsonMessageBodyHandler.class.getName());
*/
@Test
public void testRestEventsIn() throws MessagingException, ApexException, IOException {
- final String[] args = { "-rfr", "target", "-c", "target/examples/config/SampleDomain/REST2FileJsonEvent.json" };
+ final String[] args = {"-rfr", "target", "-c", "target/examples/config/SampleDomain/REST2FileJsonEvent.json"};
final ApexMain apexMain = new ApexMain(args);
ThreadUtilities.sleep(5000);
apexMain.shutdown();
- final String outputEventText = TextFileUtils
- .getTextFileAsString("target/examples/events/SampleDomain/EventsOut.json");
+ final String outputEventText =
+ TextFileUtils.getTextFileAsString("target/examples/events/SampleDomain/EventsOut.json");
checkRequiredString(outputEventText,
- "04\",\n" + " \"version\": \"0.0.1\",\n" + " \"nameSpace\": \"org.onap.policy.apex.sample.events\"");
+ "04\",\n" + " \"version\": \"0.0.1\",\n" + " \"nameSpace\": \"org.onap.policy.apex.sample.events\"");
}
/**
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
- final String[] args = { "src/test/resources/prodcons/REST2FileJsonEmptyEvents.json" };
+ final String[] args = {"src/test/resources/prodcons/REST2FileJsonEmptyEvents.json"};
final ApexMain apexMain = new ApexMain(args);
ThreadUtilities.sleep(5000);
System.setOut(stdout);
System.setErr(stderr);
- checkRequiredString(outString,
- "received an empty event from URL " + "\"http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent\"");
+ checkRequiredString(outString, "received an empty event from URL "
+ + "\"http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent\"");
}
/**
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
- final String[] args = { "src/test/resources/prodcons/REST2FileJsonEventNoURL.json" };
+ final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventNoURL.json"};
final ApexMain apexMain = new ApexMain(args);
ThreadUtilities.sleep(5000);
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
- final String[] args = { "src/test/resources/prodcons/REST2FileJsonEventBadURL.json" };
+ final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadURL.json"};
final ApexMain apexMain = new ApexMain(args);
ThreadUtilities.sleep(5000);
System.setErr(stderr);
checkRequiredString(outString, "reception of event from URL "
- + "\"http://localhost:32801/TestRest2File/apex/event/Bad\" failed with status code 404");
+ + "\"http://localhost:32801/TestRest2File/apex/event/Bad\" failed with status code 404");
}
/**
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
- final String[] args = { "src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json" };
+ final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json"};
final ApexMain apexMain = new ApexMain(args);
ThreadUtilities.sleep(5000);
System.setErr(stderr);
checkRequiredString(outString, "specified HTTP method of \"POST\" is invalid, "
- + "only HTTP method \"GET\" is supported for event reception on REST client consumer");
+ + "only HTTP method \"GET\" is supported for event reception on REST client consumer");
}
/**
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
- final String[] args = { "src/test/resources/prodcons/REST2FileJsonEventBadResponse.json" };
+ final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadResponse.json"};
final ApexMain apexMain = new ApexMain(args);
ThreadUtilities.sleep(5000);
System.setErr(stderr);
checkRequiredString(outString,
- "reception of event from URL " + "\"http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse\" "
- + "failed with status code 400 and message \"");
+ "reception of event from URL "
+ + "\"http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse\" "
+ + "failed with status code 400 and message \"");
}
/**
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.service.engine.main.ApexMain;
import org.onap.policy.common.utils.resources.ResourceUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
public class EventAlbumContextTest {
private File tempCommandFile;
@Rule
public TemporaryFolder tempTestDir = new TemporaryFolder();
-
+
/**
* Clear relative file root environment variable.
*/
configFile = "src/test/resources/prodcons/Context_JavaEventAlbum_file2file.json";
outputFile = "target/Context_JavaEventAlbum_EventOut.json";
compareFile = "src/test/resources/events/Context_JavaEventAlbum_EventOutCompare.json";
-
+
testEventAlbumContextTest();
}
configFile = "src/test/resources/prodcons/Context_AvroEventAlbum_file2file.json";
outputFile = "target/Context_AvroEventAlbum_EventOut.json";
compareFile = "src/test/resources/events/Context_AvroEventAlbum_EventOutCompare.json";
-
+
testEventAlbumContextTest();
}
private void testEventAlbumContextTest() throws IOException, ApexException {
TextFileUtils.putStringAsFile(eventContextString, tempCommandFile);
- final String[] cliArgs = new String[] { "-c", tempCommandFile.getCanonicalPath(), "-l",
- tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath() };
+ final String[] cliArgs = new String[] {"-c", tempCommandFile.getCanonicalPath(), "-l",
+ tempLogFile.getAbsolutePath(), "-o", tempModelFile.getAbsolutePath()};
new ApexCommandLineEditorMain(cliArgs);
- final String[] args = new String[] { "-m", tempModelFile.getAbsolutePath(), "-c", configFile };
+ final String[] args = new String[] {"-m", tempModelFile.getAbsolutePath(), "-c", configFile};
final ApexMain apexMain = new ApexMain(args);
// The output event will be in this file
for (int tenthsOfSecondsToWait = 100; tenthsOfSecondsToWait > 0; tenthsOfSecondsToWait--) {
if (outputEventFile.exists() && outputEventFile.length() > 0) {
// The output event is in this file
- receivedApexOutputString = TextFileUtils.getTextFileAsString(outputEventFile.getCanonicalPath())
- .replaceAll("\\s+", "");
+ receivedApexOutputString =
+ TextFileUtils.getTextFileAsString(outputEventFile.getCanonicalPath()).replaceAll("\\s+", "");
break;
}
assertTrue("Test failed, the output event file was empty", receivedApexOutputString.length() > 0);
// We compare the output to what we expect to get
- final String expectedFileContent = TextFileUtils
- .getTextFileAsString(compareFile);
+ final String expectedFileContent = TextFileUtils.getTextFileAsString(compareFile);
final String outputEventCompareString = expectedFileContent.replaceAll("\\s+", "");
assertEquals(outputEventCompareString, receivedApexOutputString);
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
if (parameters.getOutFile() != null) {
try {
TextFileUtils.putStringAsTextFile(getEventGenerationStats(), parameters.getOutFile());
- }
- catch (IOException ioe) {
+ } catch (IOException ioe) {
LOGGER.warn("could not output statistics to file \"" + parameters.getOutFile() + "\"", ioe);
}
}
try {
parameters = parameterHandler.parse(args);
- }
- catch (ParseException pe) {
+ } catch (ParseException pe) {
LOGGER.trace("Event generator start exception", pe);
LOGGER.info("Start of event generator failed: {}", pe.getMessage());
return;
ThreadUtilities.sleep(200);
}
-
// Shut down the server
eventGenerator.tearDown();
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
+import org.onap.policy.common.utils.resources.TextFileUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
public EventGeneratorParameterHandler() {
options = new Options();
options.addOption(Option.builder("h").longOpt(HELP).desc("outputs the usage of this command").required(false)
- .type(Boolean.class).build());
+ .type(Boolean.class).build());
options.addOption(Option.builder("H").longOpt(HOST)
- .desc("the host name on which to start the event generation server, defaults to \"localhost\"")
- .hasArg().argName(HOST).required(false).type(String.class).build());
+ .desc("the host name on which to start the event generation server, defaults to \"localhost\"").hasArg()
+ .argName(HOST).required(false).type(String.class).build());
options.addOption(Option.builder("p").longOpt(PORT)
- .desc("the port on which to start the event generation server, defaults to 42339").hasArg()
- .argName(PORT).required(false).type(Number.class).build());
+ .desc("the port on which to start the event generation server, defaults to 42339").hasArg()
+ .argName(PORT).required(false).type(Number.class).build());
options.addOption(Option.builder("c").longOpt(CONFIGURATION_FILE)
- .desc("name of a file containing the parameters for the event generations server, "
- + "this option must appear on its own")
- .hasArg().argName(CONFIGURATION_FILE).required(false).type(String.class).build());
+ .desc("name of a file containing the parameters for the event generations server, "
+ + "this option must appear on its own")
+ .hasArg().argName(CONFIGURATION_FILE).required(false).type(String.class).build());
options.addOption(Option.builder("o").longOpt(OUTPUT_FILE)
- .desc("path and name of a file to which output will be written,"
- + " if not specified no output is written")
- .hasArg().argName(OUTPUT_FILE).required(false).type(String.class).build());
+ .desc("path and name of a file to which output will be written,"
+ + " if not specified no output is written")
+ .hasArg().argName(OUTPUT_FILE).required(false).type(String.class).build());
options.addOption(Option.builder("bc").longOpt(BATCH_COUNT)
- .desc("the number of batches of events to send, must be 0 or more, "
- + "0 means send event batches forever, defaults to 1")
- .hasArg().argName(BATCH_COUNT).required(false).type(Number.class).build());
+ .desc("the number of batches of events to send, must be 0 or more, "
+ + "0 means send event batches forever, defaults to 1")
+ .hasArg().argName(BATCH_COUNT).required(false).type(Number.class).build());
options.addOption(Option.builder("bs").longOpt(BATCH_SIZE)
- .desc("the number of events to send in an event batch, must be 1 or more, defaults to 1")
- .hasArg().argName(BATCH_SIZE).required(false).type(Number.class).build());
+ .desc("the number of events to send in an event batch, must be 1 or more, defaults to 1").hasArg()
+ .argName(BATCH_SIZE).required(false).type(Number.class).build());
options.addOption(Option.builder("bd").longOpt(BATCH_DELAY)
- .desc("the delay in milliseconds between event batches, must be zero or more, "
- + "defaults to 10,000 (10 seconds)")
- .hasArg().argName(BATCH_DELAY).required(false).type(Number.class).build());
+ .desc("the delay in milliseconds between event batches, must be zero or more, "
+ + "defaults to 10,000 (10 seconds)")
+ .hasArg().argName(BATCH_DELAY).required(false).type(Number.class).build());
}
/**
parameterJsonString = TextFileUtils.getTextFileAsString(configurationFile);
} catch (IOException ioe) {
String errorMessage = "Could not read parameters from configuration file \"" + configurationFile + "\": "
- + ioe.getMessage();
+ + ioe.getMessage();
LOGGER.warn(errorMessage, ioe);
throw new ParseException(errorMessage);
}
return new Gson().fromJson(parameterJsonString, EventGeneratorParameters.class);
} catch (Exception ge) {
String errorMessage = "Error parsing JSON parameters from configuration file \"" + configurationFile
- + "\": " + ge.getMessage();
+ + "\": " + ge.getMessage();
LOGGER.warn(errorMessage, ge);
throw new ParseException(errorMessage);
}
final HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(stringPrintWriter, MAX_HELP_LINE_LENGTH, mainClassName + " [options...] ", "", options,
- 0, 0, "");
+ 0, 0, "");
return stringWriter.toString();
}
import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
import org.onap.policy.apex.model.eventmodel.concepts.AxInputField;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelper;
import org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters;
import org.onap.policy.apex.service.engine.event.ApexEventException;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.common.utils.resources.TextFileUtils;
/**
* Test the Key Info Getter.