/**
* Test Apex Editor Rest Resource.
- *
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class ApexEditorRestResourceTest extends JerseyTest {
result = target("editor/-1/Session/Create").request().get(ApexApiResult.class);
assertEquals(Result.SUCCESS, result.getResult());
- final int sessionId = new Integer(result.getMessages().get(0));
+ final int sessionId = Integer.valueOf(result.getMessages().get(0));
result = target("editor/-1/Session/Create").request().get(ApexApiResult.class);
assertEquals(Result.SUCCESS, result.getResult());
public void testContextSchema() throws IOException {
ApexApiResult result = target("editor/-1/Session/Create").request().get(ApexApiResult.class);
assertEquals(Result.SUCCESS, result.getResult());
- final int sessionId = new Integer(result.getMessages().get(0));
+ final int sessionId = Integer.valueOf(result.getMessages().get(0));
final int corruptSessionId = ApexEditorRestResource.createCorruptSession();
public void testContextAlbum() throws IOException {
ApexApiResult result = target("editor/-1/Session/Create").request().get(ApexApiResult.class);
assertEquals(Result.SUCCESS, result.getResult());
- final int sessionId = new Integer(result.getMessages().get(0));
+ final int sessionId = Integer.valueOf(result.getMessages().get(0));
final int corruptSessionId = ApexEditorRestResource.createCorruptSession();
result = target("editor/-12345/Validate/ContextAlbum").request().get(ApexApiResult.class);
ApexApiResult result = target("editor/-1/Session/Create").request().get(ApexApiResult.class);
assertEquals(Result.SUCCESS, result.getResult());
- final int sessionId = new Integer(result.getMessages().get(0));
+ final int sessionId = Integer.valueOf(result.getMessages().get(0));
result = target("editor/-12345/Validate/Event").request().get(ApexApiResult.class);
assertEquals(ApexApiResult.Result.FAILED, result.getResult());
ApexApiResult result = target("editor/-1/Session/Create").request().get(ApexApiResult.class);
assertEquals(Result.SUCCESS, result.getResult());
- final int sessionId = new Integer(result.getMessages().get(0));
+ final int sessionId = Integer.valueOf(result.getMessages().get(0));
result = target("editor/-12345/Validate/Task").request().get(ApexApiResult.class);
assertEquals(ApexApiResult.Result.FAILED, result.getResult());
ApexApiResult result = target("editor/-1/Session/Create").request().get(ApexApiResult.class);
assertEquals(Result.SUCCESS, result.getResult());
- final int sessionId = new Integer(result.getMessages().get(0));
+ final int sessionId = Integer.valueOf(result.getMessages().get(0));
result = target("editor/-12345/Model/Validate").request().get(ApexApiResult.class);
assertEquals(ApexApiResult.Result.FAILED, result.getResult());
/*-
* ============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.
* @throws ContextException on context distributor creation errors
*/
public Distributor getDistributor(final AxArtifactKey key) throws ContextException {
- LOGGER.entry("Distributor factory, key=" + key);
+ LOGGER.debug("Distributor factory, key={}", key);
Assertions.argumentOfClassNotNull(key, ContextException.class, "Parameter \"key\" may not be null");
// Get the class for the distributor using reflection
- final DistributorParameters distributorParameters = ParameterService
- .get(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME);
+ final DistributorParameters distributorParameters =
+ ParameterService.get(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME);
final String pluginClass = distributorParameters.getPluginClass();
Object contextDistributorObject = null;
try {
- contextDistributorObject = Class.forName(pluginClass).newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
- LOGGER.error("Apex context distributor class not found for context distributor plugin \"" + pluginClass
- + "\"", e);
- throw new ContextException("Apex context distributor class not found for context distributor plugin \""
- + pluginClass + "\"", e);
+ contextDistributorObject = Class.forName(pluginClass).getDeclaredConstructor().newInstance();
+ } catch (Exception e) {
+ throw new ContextException(
+ "Apex context distributor class not found for context distributor plugin \"" + pluginClass + "\"",
+ e);
}
// Check the class is a distributor
if (!(contextDistributorObject instanceof Distributor)) {
final String returnString = "Specified Apex context distributor plugin class \"" + pluginClass
- + "\" does not implement the ContextDistributor interface";
- LOGGER.error(returnString);
+ + "\" does not implement the ContextDistributor interface";
throw new ContextException(returnString);
}
// Lock and load the context distributor
contextDistributor.init(key);
- LOGGER.exit("Distributor factory, key=" + key + ", selected distributor of class "
- + contextDistributor.getClass());
+ LOGGER.debug("Distributor factory, key={}, selected distributor of class {}", key,
+ contextDistributor.getClass());
return contextDistributor;
}
}
/*-
* ============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.
public LockManager createLockManager(final AxArtifactKey key) throws ContextException {
LOGGER.entry("Lock Manager factory, key=" + key);
- final LockManagerParameters lockManagerParameters = ParameterService
- .get(ContextParameterConstants.LOCKING_GROUP_NAME);
+ final LockManagerParameters lockManagerParameters =
+ ParameterService.get(ContextParameterConstants.LOCKING_GROUP_NAME);
// Get the class for the lock manager using reflection
Object lockManagerObject = null;
final String pluginClass = lockManagerParameters.getPluginClass();
try {
- lockManagerObject = Class.forName(pluginClass).newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
- LOGGER.error("Apex context lock manager class not found for context lock manager plugin \"" + pluginClass
- + "\"", e);
- throw new ContextException("Apex context lock manager class not found for context lock manager plugin \""
- + pluginClass + "\"", e);
+ lockManagerObject = Class.forName(pluginClass).getDeclaredConstructor().newInstance();
+ } catch (Exception e) {
+ LOGGER.error(
+ "Apex context lock manager class not found for context lock manager plugin \"" + pluginClass + "\"",
+ e);
+ throw new ContextException(
+ "Apex context lock manager class not found for context lock manager plugin \"" + pluginClass + "\"",
+ e);
}
// Check the class is a lock manager
if (!(lockManagerObject instanceof LockManager)) {
LOGGER.error("Specified Apex context lock manager plugin class \"{}\" "
- + "does not implement the LockManager interface", pluginClass);
+ + "does not implement the LockManager interface", pluginClass);
throw new ContextException("Specified Apex context lock manager plugin class \"" + pluginClass
- + "\" does not implement the LockManager interface");
+ + "\" does not implement the LockManager interface");
}
// The context lock manager to return
/*-
* ============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.
LOGGER.entry("persistor factory, key=" + key);
Assertions.argumentOfClassNotNull(key, ContextException.class, "Parameter \"key\" may not be null");
- final PersistorParameters persistorParameters = ParameterService
- .get(ContextParameterConstants.PERSISTENCE_GROUP_NAME);
+ final PersistorParameters persistorParameters =
+ ParameterService.get(ContextParameterConstants.PERSISTENCE_GROUP_NAME);
// Get the class for the persistor using reflection
Object persistorObject = null;
final String pluginClass = persistorParameters.getPluginClass();
try {
- persistorObject = Class.forName(pluginClass).newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
+ persistorObject = Class.forName(pluginClass).getDeclaredConstructor().newInstance();
+ } catch (Exception e) {
LOGGER.error("Apex context persistor class not found for context persistor plugin \"" + pluginClass + "\"",
- e);
- throw new ContextException("Apex context persistor class not found for context persistor plugin \""
- + pluginClass + "\"", e);
+ e);
+ throw new ContextException(
+ "Apex context persistor class not found for context persistor plugin \"" + pluginClass + "\"", e);
}
// Check the class is a persistor
if (!(persistorObject instanceof Persistor)) {
LOGGER.error("Specified Apex context persistor plugin class \"{}\" "
- + "does not implement the ContextDistributor interface", pluginClass);
+ + "does not implement the ContextDistributor interface", pluginClass);
throw new ContextException("Specified Apex context persistor plugin class \"" + pluginClass
- + "\" does not implement the ContextDistributor interface");
+ + "\" does not implement the ContextDistributor interface");
}
// The persistor to return
/*-
* ============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.
@Override
public void init(final AxKey incomingUserKey, final AxContextSchema incomingSchema) {
Assertions.argumentOfClassNotNull(incomingUserKey, ContextRuntimeException.class,
- "incomingUserKey may not be null");
+ "incomingUserKey may not be null");
Assertions.argumentOfClassNotNull(incomingSchema, ContextRuntimeException.class,
- "incomingSchema may not be null");
+ "incomingSchema may not be null");
this.userKey = incomingUserKey;
this.schema = incomingSchema;
@Override
public Object createNewInstance() {
if (schemaClass == null) {
- final String returnString = userKey.getId()
- + ": could not create an instance, schema class for the schema is null";
+ final String returnString =
+ userKey.getId() + ": could not create an instance, schema class for the schema is null";
LOGGER.warn(returnString);
throw new ContextRuntimeException(returnString);
}
try {
- return schemaClass.newInstance();
+ return schemaClass.getDeclaredConstructor().newInstance();
} catch (final Exception e) {
- final String returnString = userKey.getId() + ": could not create an instance of class \""
- + schemaClass.getName() + "\" using the default constructor \""
- + schemaClass.getSimpleName() + "()\"";
+ final String returnString =
+ userKey.getId() + ": could not create an instance of class \"" + schemaClass.getName()
+ + "\" using the default constructor \"" + schemaClass.getSimpleName() + "()\"";
LOGGER.warn(returnString, e);
throw new ContextRuntimeException(returnString, e);
}
@Override
public Object createNewInstance(final String stringValue) {
if (schemaClass == null) {
- final String returnString = userKey.getId()
- + ": could not create an instance, schema class for the schema is null";
+ final String returnString =
+ userKey.getId() + ": could not create an instance, schema class for the schema is null";
LOGGER.warn(returnString);
throw new ContextRuntimeException(returnString);
}
// Invoke the constructor
return stringConstructor.newInstance(stringValue);
} catch (final Exception e) {
- final String returnString = userKey.getId() + ": could not create an instance of class \""
- + schemaClass.getName() + "\" using the string constructor \""
- + schemaClass.getSimpleName() + "(String)\"";
+ final String returnString =
+ userKey.getId() + ": could not create an instance of class \"" + schemaClass.getName()
+ + "\" using the string constructor \"" + schemaClass.getSimpleName() + "(String)\"";
LOGGER.warn(returnString, e);
throw new ContextRuntimeException(returnString);
}
/*-
* ============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.
public SchemaHelper createSchemaHelper(final AxKey owningEntityKey, final AxArtifactKey schemaKey) {
LOGGER.entry("schema helper factory, owningEntityKey=" + owningEntityKey);
Assertions.argumentOfClassNotNull(owningEntityKey, ContextRuntimeException.class,
- "Parameter \"owningEntityKey\" may not be null");
+ "Parameter \"owningEntityKey\" may not be null");
Assertions.argumentOfClassNotNull(schemaKey, ContextRuntimeException.class,
- "Parameter \"schemaKey\" may not be null");
+ "Parameter \"schemaKey\" may not be null");
// Get the schema for items in the album
final AxContextSchema schema = ModelService.getModel(AxContextSchemas.class).get(schemaKey);
if (schema == null) {
- final String resultString = "schema \"" + schemaKey.getId() + "\" for entity " + owningEntityKey.getId()
- + " does not exist";
+ final String resultString =
+ "schema \"" + schemaKey.getId() + "\" for entity " + owningEntityKey.getId() + " does not exist";
LOGGER.warn(resultString);
throw new ContextRuntimeException(resultString);
}
final SchemaParameters schemaParameters = ParameterService.get(ContextParameterConstants.SCHEMA_GROUP_NAME);
// Get the class for the schema helper from the schema parameters
- final SchemaHelperParameters schemaHelperParameters = schemaParameters
- .getSchemaHelperParameters(schema.getSchemaFlavour());
+ final SchemaHelperParameters schemaHelperParameters =
+ schemaParameters.getSchemaHelperParameters(schema.getSchemaFlavour());
if (schemaHelperParameters == null) {
final String resultString = "context schema helper parameters not found for context schema \""
- + schema.getSchemaFlavour() + "\"";
+ + schema.getSchemaFlavour() + "\"";
LOGGER.warn(resultString);
throw new ContextRuntimeException(resultString);
}
Object schemaHelperObject = null;
final String pluginClass = schemaHelperParameters.getSchemaHelperPluginClass();
try {
- schemaHelperObject = Class.forName(pluginClass).newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
+ schemaHelperObject = Class.forName(pluginClass).getDeclaredConstructor().newInstance();
+ } catch (final Exception e) {
final String resultString = "Apex context schema helper class not found for context schema helper plugin \""
- + pluginClass + "\"";
+ + pluginClass + "\"";
LOGGER.warn(resultString, e);
throw new ContextRuntimeException(resultString, e);
}
// Check the class is a schema helper
if (!(schemaHelperObject instanceof SchemaHelper)) {
final String resultString = "Specified Apex context schema helper plugin class \"" + pluginClass
- + "\" does not implement the SchemaHelper interface";
+ + "\" does not implement the SchemaHelper interface";
LOGGER.warn(resultString);
throw new ContextRuntimeException(resultString);
}
schemaHelper.init(owningEntityKey.getKey(), schema);
LOGGER.exit("Schema Helper factory, owningEntityKey=" + owningEntityKey + ", selected schema helper of class "
- + schemaHelper.getClass());
+ + schemaHelper.getClass());
return schemaHelper;
}
}
/*-
* ============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.
} catch (final IllegalArgumentException e) {
String resultSting = userKey.getId() + ": class/type " + schema.getSchema() + " for context schema \""
- + schema.getId() + "\" not found.";
+ + schema.getId() + "\" not found.";
if (JavaSchemaHelper.BUILT_IN_MAP.get(javatype) != null) {
resultSting += " Primitive types are not supported. Use the appropriate Java boxing type instead.";
} else {
}
if (getSchemaClass() == null) {
- final String returnString = getUserKey().getId()
- + ": could not create an instance, schema class for the schema is null";
+ final String returnString =
+ getUserKey().getId() + ": could not create an instance, schema class for the schema is null";
LOGGER.warn(returnString);
throw new ContextRuntimeException(returnString);
}
}
final String returnString = getUserKey().getId() + ": the object \"" + incomingObject + "\" of type \""
- + incomingObject.getClass().getName()
- + "\" is not an instance of JsonObject and is not assignable to \"" + getSchemaClass().getName()
- + "\"";
+ + incomingObject.getClass().getName()
+ + "\" is not an instance of JsonObject and is not assignable to \"" + getSchemaClass().getName() + "\"";
LOGGER.warn(returnString);
throw new ContextRuntimeException(returnString);
}
return getGson().toJson(schemaObject);
} else {
final String returnString = getUserKey().getId() + ": object \"" + schemaObject.toString()
- + "\" of class \"" + schemaObject.getClass().getName() + "\" not compatible with class \""
- + getSchemaClass().getName() + "\"";
+ + "\" of class \"" + schemaObject.getClass().getName() + "\" not compatible with class \""
+ + getSchemaClass().getName() + "\"";
LOGGER.warn(returnString);
throw new ContextRuntimeException(returnString);
}
return stringConstructor.newInstance(object.toString());
} catch (final Exception e) {
final String returnString = getUserKey().getId() + ": object \"" + object.toString() + "\" of class \""
- + object.getClass().getName() + "\" not compatible with class \""
- + getSchemaClass().getName() + "\"";
+ + object.getClass().getName() + "\" not compatible with class \"" + getSchemaClass().getName()
+ + "\"";
LOGGER.warn(returnString, e);
throw new ContextRuntimeException(returnString);
}
// Get the Java schema helper parameters from the parameter service
SchemaParameters schemaParameters = ParameterService.get(ContextParameterConstants.SCHEMA_GROUP_NAME);
- JavaSchemaHelperParameters javaSchemaHelperParmeters = (JavaSchemaHelperParameters) schemaParameters
- .getSchemaHelperParameterMap().get("Java");
+ JavaSchemaHelperParameters javaSchemaHelperParmeters =
+ (JavaSchemaHelperParameters) schemaParameters.getSchemaHelperParameterMap().get("Java");
if (javaSchemaHelperParmeters == null) {
javaSchemaHelperParmeters = new JavaSchemaHelperParameters();
}
for (JavaSchemaHelperJsonAdapterParameters jsonAdapterEntry : javaSchemaHelperParmeters.getJsonAdapters()
- .values()) {
+ .values()) {
Object adapterObject;
try {
- adapterObject = jsonAdapterEntry.getAdaptorClazz().newInstance();
- } catch (InstantiationException | IllegalAccessException e) {
+ adapterObject = jsonAdapterEntry.getAdaptorClazz().getDeclaredConstructor().newInstance();
+ } catch (Exception e) {
final String returnString = getUserKey().getId() + ": instantiation of adapter class \""
- + jsonAdapterEntry.getAdaptorClass() + "\" to decode and encode class \""
- + jsonAdapterEntry.getAdaptedClass() + "\" failed: " + e.getMessage();
+ + jsonAdapterEntry.getAdaptorClass() + "\" to decode and encode class \""
+ + jsonAdapterEntry.getAdaptedClass() + "\" failed: " + e.getMessage();
LOGGER.warn(returnString, e);
throw new ContextRuntimeException(returnString);
}
/*-
* ============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.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
-
import org.onap.policy.apex.context.ContextRuntimeException;
import org.onap.policy.apex.context.SchemaHelper;
import org.onap.policy.apex.context.parameters.ContextParameterConstants;
stringAdapterPars.setAdaptorClass("org.onap.policy.apex.context.impl.schema.java.SupportJsonAdapter");
javaSchemaHelperPars.getJsonAdapters().put("String", stringAdapterPars);
-
+
SchemaParameters schemaPars = new SchemaParameters();
schemaPars.getSchemaHelperParameterMap().put("Java", javaSchemaHelperPars);
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: class/type java.lang.Rubbish for context schema"
- + " \"SchemaKey:0.0.1\" not found. Check the class path of the JVM", e.getMessage());
+ + " \"SchemaKey:0.0.1\" not found. Check the class path of the JVM", e.getMessage());
}
AxContextSchema builtInJavaTypeSchema = new AxContextSchema(schemaKey, "Java", "short");
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: class/type short for context schema "
- + "\"SchemaKey:0.0.1\" not found. Primitive types are not supported."
- + " Use the appropriate Java boxing type instead.", e.getMessage());
+ + "\"SchemaKey:0.0.1\" not found. Primitive types are not supported."
+ + " Use the appropriate Java boxing type instead.", e.getMessage());
}
}
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("NULL:0.0.0: could not create an instance, schema class for the schema is null",
- e.getMessage());
+ e.getMessage());
}
try {
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("NULL:0.0.0: could not create an instance, schema class for the schema is null",
- e.getMessage());
+ e.getMessage());
}
try {
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("NULL:0.0.0: could not create an instance, schema class for the schema is null",
- e.getMessage());
+ e.getMessage());
}
AxArtifactKey schemaKey = new AxArtifactKey("SchemaKey", "0.0.1");
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: could not create an instance of class "
- + "\"java.lang.Integer\" using the default constructor \"Integer()\"", e.getMessage());
+ + "\"java.lang.Integer\" using the default constructor \"Integer()\"", e.getMessage());
}
try {
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: the object \"1.23\" of type "
- + "\"java.lang.Float\" is not an instance of JsonObject and is not "
- + "assignable to \"java.lang.Integer\"", e.getMessage());
+ + "\"java.lang.Float\" is not an instance of JsonObject and is not "
+ + "assignable to \"java.lang.Integer\"", e.getMessage());
}
try {
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: could not create an instance of class \"java.lang.Integer\" "
- + "using the string constructor \"Integer(String)\"", e.getMessage());
+ + "using the string constructor \"Integer(String)\"", e.getMessage());
}
JsonElement jsonIntElement = null;
assertEquals(null, intSchemaHelper.createNewInstance(jsonIntElement));
- jsonIntElement = new JsonParser().parse("123");
+ jsonIntElement = JsonParser.parseString("123");
assertEquals(123, intSchemaHelper.createNewInstance(jsonIntElement));
assertEquals(123, intSchemaHelper.createNewInstance(Integer.parseInt("123")));
stringSchemaHelper.init(userKey, stringSchema);
AxContextSchema myBaseClassSchema = new AxContextSchema(schemaKey, "Java",
- "org.onap.policy.apex.context.impl.schema.java.SupportBaseClass");
+ "org.onap.policy.apex.context.impl.schema.java.SupportBaseClass");
SchemaHelper myBaseClassSchemaHelper = new JavaSchemaHelper();
myBaseClassSchemaHelper.init(userKey, myBaseClassSchema);
assertEquals(null, byteSchemaHelper.unmarshal(null));
- assertEquals(new Byte("123"), byteSchemaHelper.unmarshal("123"));
- assertEquals(new Byte("123"), byteSchemaHelper.unmarshal(Integer.parseInt("123")));
- assertEquals(new Byte("123"), byteSchemaHelper.unmarshal(Byte.parseByte("123")));
- assertEquals(new Byte("123"), byteSchemaHelper.unmarshal(Short.parseShort("123")));
- assertEquals(new Byte("123"), byteSchemaHelper.unmarshal(Long.parseLong("123")));
- assertEquals(new Byte("123"), byteSchemaHelper.unmarshal(Float.parseFloat("123")));
- assertEquals(new Byte("123"), byteSchemaHelper.unmarshal(Double.parseDouble("123")));
+ assertEquals(Byte.valueOf("123"), byteSchemaHelper.unmarshal("123"));
+ assertEquals(Byte.valueOf("123"), byteSchemaHelper.unmarshal(Integer.parseInt("123")));
+ assertEquals(Byte.valueOf("123"), byteSchemaHelper.unmarshal(Byte.parseByte("123")));
+ assertEquals(Byte.valueOf("123"), byteSchemaHelper.unmarshal(Short.parseShort("123")));
+ assertEquals(Byte.valueOf("123"), byteSchemaHelper.unmarshal(Long.parseLong("123")));
+ assertEquals(Byte.valueOf("123"), byteSchemaHelper.unmarshal(Float.parseFloat("123")));
+ assertEquals(Byte.valueOf("123"), byteSchemaHelper.unmarshal(Double.parseDouble("123")));
try {
byteSchemaHelper.unmarshal("one two three");
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: object \"one two three\" of class \"java.lang.String\" not "
- + "compatible with class \"java.lang.Byte\"", e.getMessage());
+ + "compatible with class \"java.lang.Byte\"", e.getMessage());
}
assertEquals(null, shortSchemaHelper.unmarshal(null));
- assertEquals(new Short("123"), shortSchemaHelper.unmarshal("123"));
- assertEquals(new Short("123"), shortSchemaHelper.unmarshal(Integer.parseInt("123")));
- assertEquals(new Short("123"), shortSchemaHelper.unmarshal(Byte.parseByte("123")));
- assertEquals(new Short("123"), shortSchemaHelper.unmarshal(Short.parseShort("123")));
- assertEquals(new Short("123"), shortSchemaHelper.unmarshal(Long.parseLong("123")));
- assertEquals(new Short("123"), shortSchemaHelper.unmarshal(Float.parseFloat("123")));
- assertEquals(new Short("123"), shortSchemaHelper.unmarshal(Double.parseDouble("123")));
+ assertEquals(Short.valueOf("123"), shortSchemaHelper.unmarshal("123"));
+ assertEquals(Short.valueOf("123"), shortSchemaHelper.unmarshal(Integer.parseInt("123")));
+ assertEquals(Short.valueOf("123"), shortSchemaHelper.unmarshal(Byte.parseByte("123")));
+ assertEquals(Short.valueOf("123"), shortSchemaHelper.unmarshal(Short.parseShort("123")));
+ assertEquals(Short.valueOf("123"), shortSchemaHelper.unmarshal(Long.parseLong("123")));
+ assertEquals(Short.valueOf("123"), shortSchemaHelper.unmarshal(Float.parseFloat("123")));
+ assertEquals(Short.valueOf("123"), shortSchemaHelper.unmarshal(Double.parseDouble("123")));
try {
shortSchemaHelper.unmarshal("one two three");
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: object \"one two three\" of class \"java.lang.String\" not "
- + "compatible with class \"java.lang.Short\"", e.getMessage());
+ + "compatible with class \"java.lang.Short\"", e.getMessage());
}
assertEquals(null, intSchemaHelper.unmarshal(null));
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: object \"one two three\" of class \"java.lang.String\" not "
- + "compatible with class \"java.lang.Integer\"", e.getMessage());
+ + "compatible with class \"java.lang.Integer\"", e.getMessage());
}
assertEquals(null, longSchemaHelper.unmarshal(null));
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: object \"one two three\" of class \"java.lang.String\" not "
- + "compatible with class \"java.lang.Long\"", e.getMessage());
+ + "compatible with class \"java.lang.Long\"", e.getMessage());
}
assertEquals(null, floatSchemaHelper.unmarshal(null));
- assertEquals(new Float("123"), floatSchemaHelper.unmarshal("123"));
- assertEquals(new Float("123"), floatSchemaHelper.unmarshal(Integer.parseInt("123")));
- assertEquals(new Float("123"), floatSchemaHelper.unmarshal(Byte.parseByte("123")));
- assertEquals(new Float("123"), floatSchemaHelper.unmarshal(Short.parseShort("123")));
- assertEquals(new Float("123"), floatSchemaHelper.unmarshal(Long.parseLong("123")));
- assertEquals(new Float("123"), floatSchemaHelper.unmarshal(Float.parseFloat("123")));
- assertEquals(new Float("123"), floatSchemaHelper.unmarshal(Double.parseDouble("123")));
+ assertEquals(Float.valueOf("123"), floatSchemaHelper.unmarshal("123"));
+ assertEquals(Float.valueOf("123"), floatSchemaHelper.unmarshal(Integer.parseInt("123")));
+ assertEquals(Float.valueOf("123"), floatSchemaHelper.unmarshal(Byte.parseByte("123")));
+ assertEquals(Float.valueOf("123"), floatSchemaHelper.unmarshal(Short.parseShort("123")));
+ assertEquals(Float.valueOf("123"), floatSchemaHelper.unmarshal(Long.parseLong("123")));
+ assertEquals(Float.valueOf("123"), floatSchemaHelper.unmarshal(Float.parseFloat("123")));
+ assertEquals(Float.valueOf("123"), floatSchemaHelper.unmarshal(Double.parseDouble("123")));
try {
floatSchemaHelper.unmarshal("one two three");
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: object \"one two three\" of class \"java.lang.String\" not "
- + "compatible with class \"java.lang.Float\"", e.getMessage());
+ + "compatible with class \"java.lang.Float\"", e.getMessage());
}
assertEquals(null, doubleSchemaHelper.unmarshal(null));
- assertEquals(new Double("123"), doubleSchemaHelper.unmarshal("123"));
- assertEquals(new Double("123"), doubleSchemaHelper.unmarshal(Integer.parseInt("123")));
- assertEquals(new Double("123"), doubleSchemaHelper.unmarshal(Byte.parseByte("123")));
- assertEquals(new Double("123"), doubleSchemaHelper.unmarshal(Short.parseShort("123")));
- assertEquals(new Double("123"), doubleSchemaHelper.unmarshal(Long.parseLong("123")));
- assertEquals(new Double("123"), doubleSchemaHelper.unmarshal(Float.parseFloat("123")));
- assertEquals(new Double("123"), doubleSchemaHelper.unmarshal(Double.parseDouble("123")));
- assertEquals(new Double("123"), doubleSchemaHelper.unmarshal(BigDecimal.valueOf(123)));
+ assertEquals(Double.valueOf("123"), doubleSchemaHelper.unmarshal("123"));
+ assertEquals(Double.valueOf("123"), doubleSchemaHelper.unmarshal(Integer.parseInt("123")));
+ assertEquals(Double.valueOf("123"), doubleSchemaHelper.unmarshal(Byte.parseByte("123")));
+ assertEquals(Double.valueOf("123"), doubleSchemaHelper.unmarshal(Short.parseShort("123")));
+ assertEquals(Double.valueOf("123"), doubleSchemaHelper.unmarshal(Long.parseLong("123")));
+ assertEquals(Double.valueOf("123"), doubleSchemaHelper.unmarshal(Float.parseFloat("123")));
+ assertEquals(Double.valueOf("123"), doubleSchemaHelper.unmarshal(Double.parseDouble("123")));
+ assertEquals(Double.valueOf("123"), doubleSchemaHelper.unmarshal(BigDecimal.valueOf(123)));
try {
doubleSchemaHelper.unmarshal("one two three");
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: object \"one two three\" of class \"java.lang.String\" not "
- + "compatible with class \"java.lang.Double\"", e.getMessage());
+ + "compatible with class \"java.lang.Double\"", e.getMessage());
}
assertEquals("123", stringSchemaHelper.unmarshal(123));
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: object \"123.45\" of class \"java.lang.Double\" not "
- + "compatible with class \"java.lang.Integer\"", e.getMessage());
+ + "compatible with class \"java.lang.Integer\"", e.getMessage());
}
JsonPrimitive intJsonPrimitive = (JsonPrimitive) intSchemaHelper.marshal2Object(123);
fail("test should throw an exception here");
} catch (ContextRuntimeException e) {
assertEquals("UserKey:0.0.1: object \"1970-01-01T00:00:01Z\" of class \"java.time.Instant\" "
- + "not compatible with class \"java.lang.String\"", e.getMessage());
+ + "not compatible with class \"java.lang.String\"", e.getMessage());
}
JsonPrimitive stringJsonPrimitive = (JsonPrimitive) stringSchemaHelper.marshal2Object("Another String");
AxArtifactKey userKey = new AxArtifactKey("UserKey", "0.0.1");
SchemaParameters pars = ParameterService.get(ContextParameterConstants.SCHEMA_GROUP_NAME);
-
- JavaSchemaHelperParameters javaShPars = (JavaSchemaHelperParameters) pars.getSchemaHelperParameterMap()
- .get("Java");
+
+ JavaSchemaHelperParameters javaShPars =
+ (JavaSchemaHelperParameters) pars.getSchemaHelperParameterMap().get("Java");
javaShPars.getJsonAdapters().get("String")
- .setAdaptorClass("org.onap.policy.apex.context.impl.schema.java.SupportBadJsonAdapter");
+ .setAdaptorClass("org.onap.policy.apex.context.impl.schema.java.SupportBadJsonAdapter");
AxContextSchema stringSchema = new AxContextSchema(schemaKey, "Java", "java.lang.String");
SchemaHelper stringSchemaHelper = new JavaSchemaHelper();
fail("test should throw an exception");
} catch (ContextRuntimeException pre) {
assertEquals("UserKey:0.0.1: instantiation of adapter class "
- + "\"org.onap.policy.apex.context.impl.schema.java.SupportBadJsonAdapter\" "
- + "to decode and encode class \"java.lang.String\" failed: Test for Bad Adapter",
- pre.getMessage());
+ + "\"org.onap.policy.apex.context.impl.schema.java.SupportBadJsonAdapter\" to decode and encode "
+ + "class \"java.lang.String\" failed: null", pre.getMessage());
}
}
public void testJavaSchemaHelperDefaultAdapter() {
SchemaParameters pars = ParameterService.get(ContextParameterConstants.SCHEMA_GROUP_NAME);
- JavaSchemaHelperParameters javaShPars = (JavaSchemaHelperParameters) pars.getSchemaHelperParameterMap()
- .get("Java");
-
+ JavaSchemaHelperParameters javaShPars =
+ (JavaSchemaHelperParameters) pars.getSchemaHelperParameterMap().get("Java");
+
pars.getSchemaHelperParameterMap().clear();
-
+
testJavaSchemaHelperAdapters();
pars.getSchemaHelperParameterMap().put("Java", javaShPars);
import lombok.Getter;
import lombok.Setter;
+
import org.onap.policy.common.parameters.BeanValidator;
import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.common.parameters.annotations.NotBlank;
this.name = "taskParameters";
}
+ /**
+ * Full constructor.
+ *
+ * @param key the task parameter key
+ * @param value the task parameter value
+ * @param taskId the task ID of this task parameter
+ */
public TaskParameters(String key, String value, String taskId) {
this();
this.key = key;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
+
import org.onap.policy.apex.core.engine.EngineParameterConstants;
import org.onap.policy.apex.core.engine.EngineParameters;
import org.onap.policy.apex.core.engine.ExecutorParameters;
engineParameters = ParameterService.get(EngineParameterConstants.MAIN_GROUP_NAME);
Assertions.argumentOfClassNotNull(engineParameters, StateMachineException.class,
- "Parameter \"engineParameters\" may not be null");
+ "Parameter \"engineParameters\" may not be null");
// Instantiate each executor class map entry
for (final Entry<String, ExecutorParameters> executorParameterEntry : engineParameters.getExecutorParameterMap()
- .entrySet()) {
+ .entrySet()) {
// Get classes for all types of executors for this logic type
taskExecutorPluginClassMap.put(executorParameterEntry.getKey(),
- getExecutorPluginClass(executorParameterEntry.getValue().getTaskExecutorPluginClass()));
- taskSelectionExecutorPluginClassMap.put(executorParameterEntry.getKey(), getExecutorPluginClass(
- executorParameterEntry.getValue().getTaskSelectionExecutorPluginClass()));
- stateFinalizerExecutorPluginClassMap.put(executorParameterEntry.getKey(), getExecutorPluginClass(
- executorParameterEntry.getValue().getStateFinalizerExecutorPluginClass()));
+ getExecutorPluginClass(executorParameterEntry.getValue().getTaskExecutorPluginClass()));
+ taskSelectionExecutorPluginClassMap.put(executorParameterEntry.getKey(),
+ getExecutorPluginClass(executorParameterEntry.getValue().getTaskSelectionExecutorPluginClass()));
+ stateFinalizerExecutorPluginClassMap.put(executorParameterEntry.getKey(),
+ getExecutorPluginClass(executorParameterEntry.getValue().getStateFinalizerExecutorPluginClass()));
// Save the executor implementation parameters
implementationParameterMap.put(executorParameterEntry.getKey(), executorParameterEntry.getValue());
*/
@Override
public TaskSelectExecutor getTaskSelectionExecutor(final Executor<?, ?, ?, ?> parentExecutor, final AxState state,
- final ApexInternalContext context) {
+ final ApexInternalContext context) {
if (!state.checkSetTaskSelectionLogic()) {
return null;
}
// Create task selection executor
- final TaskSelectExecutor tsExecutor = (TaskSelectExecutor) createExecutor(
- state.getTaskSelectionLogic().getLogicFlavour(),
+ final TaskSelectExecutor tsExecutor =
+ (TaskSelectExecutor) createExecutor(state.getTaskSelectionLogic().getLogicFlavour(),
taskSelectionExecutorPluginClassMap.get(state.getTaskSelectionLogic().getLogicFlavour()),
TaskSelectExecutor.class);
tsExecutor.setParameters(implementationParameterMap.get(state.getTaskSelectionLogic().getLogicFlavour()));
*/
@Override
public TaskExecutor getTaskExecutor(final Executor<?, ?, ?, ?> parentExecutor, final AxTask task,
- final ApexInternalContext context) {
+ final ApexInternalContext context) {
// Create task executor
final TaskExecutor taskExecutor = (TaskExecutor) createExecutor(task.getTaskLogic().getLogicFlavour(),
- taskExecutorPluginClassMap.get(task.getTaskLogic().getLogicFlavour()), TaskExecutor.class);
+ taskExecutorPluginClassMap.get(task.getTaskLogic().getLogicFlavour()), TaskExecutor.class);
taskExecutor.setParameters(implementationParameterMap.get(task.getTaskLogic().getLogicFlavour()));
taskExecutor.setContext(parentExecutor, task, context);
taskExecutor.updateTaskParameters(engineParameters.getTaskParameters());
*/
@Override
public StateFinalizerExecutor getStateFinalizerExecutor(final Executor<?, ?, ?, ?> parentExecutor,
- final AxStateFinalizerLogic logic, final ApexInternalContext context) {
+ final AxStateFinalizerLogic logic, final ApexInternalContext context) {
// Create state finalizer executor
final StateFinalizerExecutor sfExecutor = (StateFinalizerExecutor) createExecutor(logic.getLogicFlavour(),
- stateFinalizerExecutorPluginClassMap.get(logic.getLogicFlavour()),
- StateFinalizerExecutor.class);
+ stateFinalizerExecutorPluginClassMap.get(logic.getLogicFlavour()), StateFinalizerExecutor.class);
sfExecutor.setParameters(implementationParameterMap.get(logic.getLogicFlavour()));
sfExecutor.setContext(parentExecutor, logic, context);
*/
@SuppressWarnings("unchecked")
private Class<Executor<?, ?, ?, ?>> getExecutorPluginClass(final String executorClassName)
- throws StateMachineException {
+ throws StateMachineException {
// It's OK for an executor class not to be defined as long as it's not called
if (executorClassName == null) {
return null;
} catch (final ClassNotFoundException e) {
LOGGER.error("Apex executor class not found for executor plugin \"" + executorClassName + "\"", e);
throw new StateMachineException(
- "Apex executor class not found for executor plugin \"" + executorClassName + "\"", e);
+ "Apex executor class not found for executor plugin \"" + executorClassName + "\"", e);
}
// Check the class is an executor
if (!Executor.class.isAssignableFrom(executorPluginClass)) {
LOGGER.error("Specified Apex executor plugin class \"{}\" does not implment the Executor interface",
- executorClassName);
+ executorClassName);
throw new StateMachineException("Specified Apex executor plugin class \"" + executorClassName
- + "\" does not implment the Executor interface");
+ + "\" does not implment the Executor interface");
}
return (Class<Executor<?, ?, ?, ?>>) executorPluginClass;
* @return The instantiated class
*/
private Executor<?, ?, ?, ?> createExecutor(final String logicFlavour,
- final Class<Executor<?, ?, ?, ?>> executorClass,
- final Class<? extends Executor<?, ?, ?, ?>> executorSuperClass) {
+ final Class<Executor<?, ?, ?, ?>> executorClass,
+ final Class<? extends Executor<?, ?, ?, ?>> executorSuperClass) {
// It's OK for an executor class not to be defined but it's not all right to try and create
// a non-defined
// executor class
if (executorClass == null) {
final String errorMessage = "Executor plugin class not defined for \"" + logicFlavour
- + "\" executor of type \"" + executorSuperClass.getName() + "\"";
+ + "\" executor of type \"" + executorSuperClass.getName() + "\"";
LOGGER.error(errorMessage);
throw new StateMachineRuntimeException(errorMessage);
}
// Create an executor for the specified logic flavour
Object executorObject = null;
try {
- executorObject = executorClass.newInstance();
- } catch (InstantiationException | IllegalAccessException e) {
+ executorObject = executorClass.getDeclaredConstructor().newInstance();
+ } catch (final Exception e) {
final String errorMessage = "Instantiation error on \"" + logicFlavour + "\" executor of type \""
- + executorClass.getName() + "\"";
+ + executorClass.getName() + "\"";
LOGGER.error(errorMessage, e);
throw new StateMachineRuntimeException(errorMessage, e);
}
// Check the class is the correct type of executor
if (!(executorSuperClass.isAssignableFrom(executorObject.getClass()))) {
final String errorMessage = "Executor on \"" + logicFlavour + "\" of type \"" + executorClass
- + "\" is not an instance of \"" + executorSuperClass.getName() + "\"";
+ + "\" is not an instance of \"" + executorSuperClass.getName() + "\"";
LOGGER.error(errorMessage);
throw new StateMachineRuntimeException(errorMessage);
/*-
* ============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.
*/
public void compile() throws JavaHandlingException {
// Get the list of compilation units, there is only one here
- final List<? extends JavaFileObject> compilationUnits = Arrays
- .asList(new SingleClassCompilationUnit(className, sourceCode));
+ final List<? extends JavaFileObject> compilationUnits =
+ Arrays.asList(new SingleClassCompilationUnit(className, sourceCode));
// Allows us to get diagnostics from the compilation
final DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<>();
// Set up the target file manager and call the compiler
singleFileManager = new SingleFileManager(compiler, new SingleClassByteCodeFileObject(className));
- final JavaCompiler.CompilationTask task = compiler.getTask(null, singleFileManager, diagnosticListener, null,
- null, compilationUnits);
+ final JavaCompiler.CompilationTask task =
+ compiler.getTask(null, singleFileManager, diagnosticListener, null, null, compilationUnits);
// Check if the compilation worked
- if (!task.call()) {
+ if (Boolean.FALSE.equals(task.call())) {
final StringBuilder builder = new StringBuilder();
for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnosticListener.getDiagnostics()) {
builder.append("code:");
* Create a new instance of the Java class using its byte code definition.
*
* @return A new instance of the object
- * @throws InstantiationException if an instance of the object cannot be created, for example if the class has no
- * default constructor
- * @throws IllegalAccessException the caller does not have permission to call the class
- * @throws ClassNotFoundException the byte code for the class is not found in the class loader
- * @throws JavaHandlingException the java handling exception if the Java class source code is not compiled
+ * @throws JavaHandlingException on errors creating the object
*/
- public Object createObject() throws InstantiationException, IllegalAccessException, ClassNotFoundException,
- JavaHandlingException {
+ public Object createObject()
+ throws InstantiationException, IllegalAccessException, ClassNotFoundException, JavaHandlingException {
if (singleFileManager == null) {
String message = "error instantiating instance for class \"" + className + "\": code may not be compiled";
LOGGER.warn(message);
throw new JavaHandlingException(message);
}
- return singleFileManager.getClassLoader(null).findClass(className).newInstance();
+ try {
+ return singleFileManager.getClassLoader(null).findClass(className).getDeclaredConstructor().newInstance();
+ } catch (Exception e) {
+ return new JavaHandlingException("could not create java class", e);
+ }
+
}
}
/*-
* ============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.
// TODO: Auto-generated Javadoc
/**
* This class tests AADM use case.
- *
+ *
* @author Sergey Sachkov (sergey.sachkov@ericsson.com)
*
*/
// getting number of connections send it to policy, expecting probe action
logger.info("Sending too many connections trigger ");
EnEvent event = apexEngine.createEvent(axEvent.getKey());
- event.put("IMSI", new Long(123456));
+ event.put("IMSI", Long.valueOf(123456));
event.put("IMSI_IP", "101.111.121.131");
- event.put("ENODEB_ID", new Long(123));
+ event.put("ENODEB_ID", Long.valueOf(123));
event.put("SERVICE_REQUEST_COUNT", 99);
event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0);
event.put("UE_IP_ADDRESS", "101.111.121.131");
logger.info("Sending too many connections trigger ");
event = apexEngine.createEvent(axEvent.getKey());
- event.put("IMSI", new Long(123456));
+ event.put("IMSI", Long.valueOf(123456));
event.put("IMSI_IP", "101.111.121.131");
- event.put("ENODEB_ID", new Long(123));
+ event.put("ENODEB_ID", Long.valueOf(123));
event.put("SERVICE_REQUEST_COUNT", 101);
event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 99.0);
event.put("UE_IP_ADDRESS", "101.111.121.131");
// getting number of connections send it to policy, expecting probe action
logger.info("Sending too many connections trigger ");
event = apexEngine.createEvent(axEvent.getKey());
- event.put("IMSI", new Long(123456));
+ event.put("IMSI", Long.valueOf(123456));
event.put("IMSI_IP", "101.111.121.131");
- event.put("ENODEB_ID", new Long(123));
+ event.put("ENODEB_ID", Long.valueOf(123));
event.put("SERVICE_REQUEST_COUNT", 99);
event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0);
event.put("UE_IP_ADDRESS", "101.111.121.131");
// tcp correlation return positive dos
logger.info("Receiving action event with {} action", result.get("ACTTASK"));
event = apexEngine.createEvent(axEvent.getKey());
- event.put("IMSI", new Long(123456));
+ event.put("IMSI", Long.valueOf(123456));
event.put("IMSI_IP", "101.111.121.131");
- event.put("ENODEB_ID", new Long(123));
+ event.put("ENODEB_ID", Long.valueOf(123));
event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 101.0);
event.put("ACTTASK", "");
event.put("APPLICATION", "");
// user moving enodeB
logger.info("Sending too many connections trigger ");
event = apexEngine.createEvent(axEvent.getKey());
- event.put("IMSI", new Long(123456));
+ event.put("IMSI", Long.valueOf(123456));
event.put("IMSI_IP", "101.111.121.131");
- event.put("ENODEB_ID", new Long(123));
+ event.put("ENODEB_ID", Long.valueOf(123));
event.put("SERVICE_REQUEST_COUNT", 99);
event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0);
event.put("UE_IP_ADDRESS", "101.111.121.131");
logger.info("Sending too many connections trigger ");
event = apexEngine.createEvent(axEvent.getKey());
- event.put("IMSI", new Long(123456));
- event.put("ENODEB_ID", new Long(124));
+ event.put("IMSI", Long.valueOf(123456));
+ event.put("ENODEB_ID", Long.valueOf(124));
event.put("SERVICE_REQUEST_COUNT", 99);
event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0);
event.put("UE_IP_ADDRESS", "101.111.121.131");
// user becomes non anomalous
logger.info("Sending too many connections trigger ");
event = apexEngine.createEvent(axEvent.getKey());
- event.put("IMSI", new Long(123456));
+ event.put("IMSI", Long.valueOf(123456));
event.put("IMSI_IP", "101.111.121.131");
- event.put("ENODEB_ID", new Long(123));
+ event.put("ENODEB_ID", Long.valueOf(123));
event.put("SERVICE_REQUEST_COUNT", 99);
event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0);
event.put("UE_IP_ADDRESS", "101.111.121.131");
logger.info("Sending too many connections trigger ");
event = apexEngine.createEvent(axEvent.getKey());
- event.put("IMSI", new Long(123456));
- event.put("ENODEB_ID", new Long(123));
+ event.put("IMSI", Long.valueOf(123456));
+ event.put("ENODEB_ID", Long.valueOf(123));
event.put("SERVICE_REQUEST_COUNT", 99);
event.put("UE_IP_ADDRESS", "101.111.121.131");
event.put("ACTTASK", "");
final File tempModelFile1 = File.createTempFile("TestMyFirstPolicy1CLI", ".json");
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()};
- final String[] testApexModel2CliArgs =
- {"-c", "src/main/resources/examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.apex", "-l",
- tempLogFile2.getAbsolutePath(), "-o", tempModelFile2.getAbsolutePath()};
+ // @formatter:off
+ final String[] testApexModel1CliArgs = {
+ "-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()
+ };
+ // @formatter:on
new ApexCommandLineEditorMain(testApexModel1CliArgs);
new ApexCommandLineEditorMain(testApexModel2CliArgs);
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 huawei. 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.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
+
import javax.net.ssl.HttpsURLConnection;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
}
@Test
- public void httpsRequest() {
+ public void testHttpsRequest() {
WebClient cl = new WebClient();
String result =
cl.httpRequest("https://some.random.url/data", "POST", null, "admin", "admin", "application/json");
}
@Test
- public void httpRequest() {
+ public void testHttpRequest() {
WebClient cl = new WebClient();
String result =
cl.httpRequest("http://some.random.url/data", "GET", null, "admin", "admin", "application/json");
}
@Test
- public void toPrettyString() {
+ public void testToPrettyString() {
String xmlSample = "<input xmlns=\"org:onap:sdnc:northbound:generic-resource\">"
+ "<sdnc-request-header> <svc-action>update</svc-action> </sdnc-request-header></input>";
WebClient cl = new WebClient();
}
private static final String prettifyJsonString(final String uglyJsonString) {
- JsonParser jp = new JsonParser();
- JsonElement je = jp.parse(uglyJsonString);
+ JsonElement je = JsonParser.parseString(uglyJsonString);
return gson.toJson(je);
}
}
/*-
* ============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.
final AxKeyUse copy = ((AxKeyUse) copyObject);
try {
- copy.usedKey = usedKey.getClass().newInstance();
+ copy.usedKey = usedKey.getClass().getDeclaredConstructor().newInstance();
} catch (final Exception e) {
throw new ApexRuntimeException("error copying concept key: " + e.getMessage(), e);
}
/*-
* ============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.
*/
public ApexDao createApexDao(final DaoParameters daoParameters) throws ApexException {
Assertions.argumentOfClassNotNull(daoParameters, ApexException.class,
- "Parameter \"daoParameters\" may not be null");
+ "Parameter \"daoParameters\" may not be null");
// Get the class for the DAO using reflection
Object apexDaoObject = null;
try {
- apexDaoObject = Class.forName(daoParameters.getPluginClass()).newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
+ apexDaoObject = Class.forName(daoParameters.getPluginClass()).getDeclaredConstructor().newInstance();
+ } catch (final Exception e) {
LOGGER.error("Apex DAO class not found for DAO plugin \"" + daoParameters.getPluginClass() + "\"", e);
throw new ApexException(
- "Apex DAO class not found for DAO plugin \"" + daoParameters.getPluginClass() + "\"", e);
+ "Apex DAO class not found for DAO plugin \"" + daoParameters.getPluginClass() + "\"", e);
}
// Check the class is an Apex DAO
if (!(apexDaoObject instanceof ApexDao)) {
LOGGER.error("Specified Apex DAO plugin class \"" + daoParameters.getPluginClass()
- + "\" does not implement the ApexDao interface");
+ + "\" does not implement the ApexDao interface");
throw new ApexException("Specified Apex DAO plugin class \"" + daoParameters.getPluginClass()
- + "\" does not implement the ApexDao interface");
+ + "\" does not implement the ApexDao interface");
}
return (ApexDao) apexDaoObject;
/*-
* ============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.
LOGGER.debug("Creating Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\" . . .");
try {
emf = Persistence.createEntityManagerFactory(daoParameters.getPersistenceUnit(),
- daoParameters.getJdbcProperties());
+ daoParameters.getJdbcProperties());
} catch (final Exception e) {
LOGGER.warn("Creation of Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\" failed", e);
throw new ApexException(
- "Creation of Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\" failed",
- e);
+ "Creation of Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\" failed", e);
}
LOGGER.debug("Created Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\"");
}
mg.getTransaction().begin();
mg.merge(obj);
mg.getTransaction().commit();
- }
- finally {
+ } finally {
mg.close();
}
}
mg.getTransaction().begin();
mg.remove(mg.contains(obj) ? obj : mg.merge(obj));
mg.getTransaction().commit();
- }
- finally {
+ } finally {
mg.close();
}
}
try {
mg.getTransaction().begin();
mg.createQuery(DELETE_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_NAME + key.getName()
- + AND_C_KEY_VERSION + key.getVersion() + "'", someClass).executeUpdate();
+ + AND_C_KEY_VERSION + key.getVersion() + "'", someClass).executeUpdate();
mg.getTransaction().commit();
- }
- finally {
+ } finally {
mg.close();
}
}
try {
mg.getTransaction().begin();
mg.createQuery(DELETE_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME
- + key.getParentKeyName() + AND_C_KEY_PARENT_KEY_VERSION + key.getParentKeyVersion()
- + AND_C_KEY_LOCAL_NAME + key.getLocalName() + "'", someClass).executeUpdate();
+ + key.getParentKeyName() + AND_C_KEY_PARENT_KEY_VERSION + key.getParentKeyVersion()
+ + AND_C_KEY_LOCAL_NAME + key.getLocalName() + "'", someClass).executeUpdate();
mg.getTransaction().commit();
- }
- finally {
+ } finally {
mg.close();
}
}
mg.merge(t);
}
mg.getTransaction().commit();
- }
- finally {
+ } finally {
mg.close();
}
}
mg.remove(mg.contains(t) ? t : mg.merge(t));
}
mg.getTransaction().commit();
- }
- finally {
+ } finally {
mg.close();
}
}
*/
@Override
public <T extends AxConcept> int deleteByArtifactKey(final Class<T> someClass,
- final Collection<AxArtifactKey> keys) {
+ final Collection<AxArtifactKey> keys) {
if (keys == null || keys.isEmpty()) {
return 0;
}
try {
mg.getTransaction().begin();
for (final AxArtifactKey key : keys) {
- deletedCount += mg
- .createQuery(DELETE_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_NAME
- + key.getName() + AND_C_KEY_VERSION + key.getVersion() + "'", someClass)
- .executeUpdate();
+ deletedCount += mg.createQuery(DELETE_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_NAME
+ + key.getName() + AND_C_KEY_VERSION + key.getVersion() + "'", someClass).executeUpdate();
}
mg.getTransaction().commit();
- }
- finally {
+ } finally {
mg.close();
}
return deletedCount;
*/
@Override
public <T extends AxConcept> int deleteByReferenceKey(final Class<T> someClass,
- final Collection<AxReferenceKey> keys) {
+ final Collection<AxReferenceKey> keys) {
if (keys == null || keys.isEmpty()) {
return 0;
}
try {
mg.getTransaction().begin();
for (final AxReferenceKey key : keys) {
- deletedCount += mg.createQuery(DELETE_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME
- + key.getParentKeyName() + AND_C_KEY_PARENT_KEY_VERSION + key.getParentKeyVersion()
- + AND_C_KEY_LOCAL_NAME + key.getLocalName() + "'", someClass).executeUpdate();
+ deletedCount +=
+ mg.createQuery(
+ DELETE_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME
+ + key.getParentKeyName() + AND_C_KEY_PARENT_KEY_VERSION
+ + key.getParentKeyVersion() + AND_C_KEY_LOCAL_NAME + key.getLocalName() + "'",
+ someClass).executeUpdate();
}
mg.getTransaction().commit();
- }
- finally {
+ } finally {
mg.close();
}
return deletedCount;
mg.getTransaction().begin();
mg.createQuery(DELETE_FROM + someClass.getSimpleName() + " c ", someClass).executeUpdate();
mg.getTransaction().commit();
- }
- finally {
+ } finally {
mg.close();
}
}
if (t != null) {
// This clone is created to force the JPA DAO to recurse down through the object
try {
- final T clonedT = someClass.newInstance();
+ final T clonedT = someClass.getDeclaredConstructor().newInstance();
t.copyTo(clonedT);
return clonedT;
} catch (final Exception e) {
} else {
return null;
}
- }
- finally {
+ } finally {
mg.close();
}
}
final T t = mg.find(someClass, key);
if (t != null) {
try {
- final T clonedT = someClass.newInstance();
+ final T clonedT = someClass.getDeclaredConstructor().newInstance();
t.copyTo(clonedT);
return clonedT;
} catch (final Exception e) {
} else {
return null;
}
- }
- finally {
+ } finally {
mg.close();
}
}
final EntityManager mg = getEntityManager();
try {
return mg.createQuery(SELECT_C_FROM + someClass.getSimpleName() + " c", someClass).getResultList();
- }
- finally {
+ } finally {
mg.close();
}
}
}
final EntityManager mg = getEntityManager();
try {
- return mg.createQuery(SELECT_C_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME
- + parentKey.getName() + AND_C_KEY_PARENT_KEY_VERSION + parentKey.getVersion() + "'",
- someClass).getResultList();
- }
- finally {
+ return mg
+ .createQuery(
+ SELECT_C_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME
+ + parentKey.getName() + AND_C_KEY_PARENT_KEY_VERSION + parentKey.getVersion() + "'",
+ someClass)
+ .getResultList();
+ } finally {
mg.close();
}
}
List<T> ret;
try {
ret = mg.createQuery(SELECT_C_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_NAME + key.getName()
- + AND_C_KEY_VERSION + key.getVersion() + "'", someClass).getResultList();
- }
- finally {
+ + AND_C_KEY_VERSION + key.getVersion() + "'", someClass).getResultList();
+ } finally {
mg.close();
}
if (ret == null || ret.isEmpty()) {
}
if (ret.size() > 1) {
throw new IllegalArgumentException("More than one result was returned for search for " + someClass
- + " with key " + key.getId() + ": " + ret);
+ + " with key " + key.getId() + ": " + ret);
}
return ret.get(0);
}
List<T> ret;
try {
ret = mg.createQuery(SELECT_C_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME
- + key.getParentKeyName() + AND_C_KEY_PARENT_KEY_VERSION + key.getParentKeyVersion()
- + AND_C_KEY_LOCAL_NAME + key.getLocalName() + "'", someClass).getResultList();
- }
- finally {
+ + key.getParentKeyName() + AND_C_KEY_PARENT_KEY_VERSION + key.getParentKeyVersion()
+ + AND_C_KEY_LOCAL_NAME + key.getLocalName() + "'", someClass).getResultList();
+ } finally {
mg.close();
}
if (ret == null || ret.isEmpty()) {
}
if (ret.size() > 1) {
throw new IllegalArgumentException("More than one result was returned for search for " + someClass
- + " with key " + key.getId() + ": " + ret);
+ + " with key " + key.getId() + ": " + ret);
}
return ret.get(0);
}
ret = mg.merge(obj);
mg.flush();
mg.getTransaction().commit();
- }
- finally {
+ } finally {
mg.close();
}
return ret;
long size = 0;
try {
size = mg.createQuery("SELECT COUNT(c) FROM " + someClass.getSimpleName() + " c", Long.class)
- .getSingleResult();
- }
- finally {
+ .getSingleResult();
+ } finally {
mg.close();
}
return size;
/*
* ============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 javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-import org.onap.policy.apex.model.basicmodel.concepts.AxConcept;
-import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
-import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
-import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
import org.onap.policy.apex.model.basicmodel.xml.AxReferenceKeyAdapter;
@Entity
this.doubleValue = doubleValue;
}
+ @Override
public AxReferenceKey getKey() {
return key;
}
+ @Override
public List<AxKey> getKeys() {
return Arrays.asList((AxKey) getKey());
}
return key.compareTo(other.key);
}
if (doubleValue != other.doubleValue) {
- return new Double(doubleValue).compareTo(other.doubleValue);
+ return Double.valueOf(doubleValue).compareTo(other.doubleValue);
}
return 0;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
+import lombok.Getter;
+
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
import org.onap.policy.apex.model.basicmodel.concepts.AxConcept;
import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult;
import org.onap.policy.common.utils.validation.Assertions;
-import lombok.Getter;
/**
- * This class is a java bean that is used to record statistics on Apex engines as they execute.
- * Statistics on the number of events, the amount of time taken to execute the last policy, the
- * average policy execution time, the up time of the engine, and the time stamp of the last engine
- * start are recorded.
+ * This class is a java bean that is used to record statistics on Apex engines as they execute. Statistics on the number
+ * of events, the amount of time taken to execute the last policy, the average policy execution time, the up time of the
+ * engine, and the time stamp of the last engine start are recorded.
*/
@Entity
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "apexEngineStats", namespace = "http://www.onap.org/policy/apex-pdp")
@XmlType(name = "AxEngineStats", namespace = "http://www.onap.org/policy/apex-pdp", propOrder = {"key", "timeStamp",
- "eventCount", "lastExecutionTime", "averageExecutionTime", "upTime", "lastStart"})
+ "eventCount", "lastExecutionTime", "averageExecutionTime", "upTime", "lastStart"})
public class AxEngineStats extends AxConcept {
private static final long serialVersionUID = -6981129081962785368L;
private static final int HASH_CODE_PRIME = 32;
private long lastStart;
/**
- * The Default Constructor creates an engine statistics instance with a null key and with all
- * values cleared.
+ * The Default Constructor creates an engine statistics instance with a null key and with all values cleared.
*/
public AxEngineStats() {
this(new AxReferenceKey());
}
/**
- * The Keyed Constructor creates an engine statistics instance with the given key and all values
- * cleared.
+ * The Keyed Constructor creates an engine statistics instance with the given key and all values cleared.
*
* @param key the key
*/
}
/**
- * Updates the statistics when called, used by the Apex engine when it starts executing a
- * policy.
+ * Updates the statistics when called, used by the Apex engine when it starts executing a policy.
*
* @param eventkey the key of the event that is being executed
*/
}
/**
- * Updates the statistics when called, used by the Apex engine when it completes executing a
- * policy.
+ * Updates the statistics when called, used by the Apex engine when it completes executing a policy.
*/
public synchronized void executionExit() {
final long now = System.currentTimeMillis();
/*-
* ============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.concepts.AxValidationResult.ValidationResult;
/**
- * Test engine statistics.
+ * Test the engine statistics.
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class EngineStatsTest {
assertEquals("EngineKey:0.0.1:NULL:EngineStats", stats.getKeys().get(0).getId());
stats.setAverageExecutionTime(123.45);
- assertEquals(new Double(123.45), new Double(stats.getAverageExecutionTime()));
+ assertEquals(Double.valueOf(123.45), Double.valueOf(stats.getAverageExecutionTime()));
stats.setEventCount(987);
assertEquals(987, stats.getEventCount());
stats.engineStart();
stats.setEventCount(4);
stats.executionEnter(new AxArtifactKey());
-
+
synchronized (WAIT_LOCK) {
try {
WAIT_LOCK.wait(10);
assertTrue(stats.equals(stats));
assertTrue(stats.equals(clonedStats));
assertFalse(stats.equals(null));
- assertFalse(stats.equals((Object)"Hello"));
+ assertFalse(stats.equals("Hello"));
assertFalse(stats.equals(new AxEngineStats(new AxReferenceKey())));
assertEquals(0, stats.compareTo(stats));
/*-
* ============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;
/**
- * Test policies for API tests.
+ * Test policies for API.
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class ApexEditorApiPolicyTest {
@Test
- public void myTestPolicyCrud() {
+ public void testMyTestPolicyCrud() {
final ApexModel apexModel = new ApexModelFactory().createApexModel(null, false);
ApexApiResult result = apexModel.validatePolicy(null, 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=========================================================
*/
final Schema nullschema = Schema.create(Schema.Type.NULL);
if (types.size() != 2 || !types.contains(nullschema)) {
final String resultSting = userKey.getId()
- + ": Apex currently only supports UNION schemas with 2 options, one must be NULL";
+ + ": Apex currently only supports UNION schemas with 2 options, one must be NULL";
LOGGER.warn(resultSting);
throw new ContextRuntimeException(resultSting);
}
schema = types.get(1);
}
if (Schema.Type.NULL.equals(schema.getType())) {
- final String resultSting = userKey.getId()
- + ": Apex currently only supports UNION schema2 with 2 options, "
+ final String resultSting =
+ userKey.getId() + ": Apex currently only supports UNION schema2 with 2 options, "
+ "only one can be NULL, and the other cannot be another UNION";
LOGGER.warn(resultSting);
throw new ContextRuntimeException(resultSting);
// Check that there is a definition for the mapper for this type
if (!AVRO_OBJECT_MAPPER_MAP.containsKey(avroType) || AVRO_OBJECT_MAPPER_MAP.get(avroType) == null) {
- final String resultSting = userKey.getId() + ": no Avro object mapper defined for Avro type \"" + avroType
- + "\"";
+ final String resultSting =
+ userKey.getId() + ": no Avro object mapper defined for Avro type \"" + avroType + "\"";
LOGGER.warn(resultSting);
throw new ContextRuntimeException(resultSting);
}
// Create a mapper
AvroObjectMapper avroObjectMapper;
try {
- avroObjectMapper = AVRO_OBJECT_MAPPER_MAP.get(avroType).newInstance();
+ avroObjectMapper = AVRO_OBJECT_MAPPER_MAP.get(avroType).getDeclaredConstructor().newInstance();
if (isnullable) {
avroObjectMapper = new AvroNullableMapper(avroObjectMapper);
}
} catch (final Exception e) {
final String resultSting = userKey.getId() + ": could not create an Avro object mapper of type \""
- + AVRO_OBJECT_MAPPER_MAP.get(avroType) + "\" for Avro type \"" + avroType + "\" : " + e;
+ + AVRO_OBJECT_MAPPER_MAP.get(avroType) + "\" for Avro type \"" + avroType + "\" : " + e;
LOGGER.warn(resultSting, e);
throw new ContextRuntimeException(resultSting, e);
}
<!--
============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.
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"
+<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>
<artifactId>mockito-all</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+
</dependencies>
<profiles>
/*-
* ============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.
package org.onap.policy.apex.plugins.event.carrier.restclient;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
-
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-
import lombok.Getter;
import lombok.Setter;
-import org.apache.commons.lang3.StringUtils;
+
import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters;
-import org.onap.policy.common.parameters.GroupValidationResult;
-import org.onap.policy.common.parameters.ValidationStatus;
-import org.onap.policy.common.utils.validation.ParameterValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
// @formatter:off
/**
@Setter
@Getter
public class RestClientCarrierTechnologyParameters extends RestPluginCarrierTechnologyParameters {
- // Get a reference to the logger
- private static final Logger LOGGER = LoggerFactory.getLogger(RestClientCarrierTechnologyParameters.class);
+
/**
* Constructor to create a REST carrier technology parameters instance and register the instance with the parameter
* service.
*/
public RestClientCarrierTechnologyParameters() {
super();
- CARRIER_TECHNOLOGY_LABEL = "RESTCLIENT";
- EVENT_PRODUCER_PLUGIN_CLASS = ApexRestClientProducer.class.getName();
- EVENT_CONSUMER_PLUGIN_CLASS = ApexRestClientConsumer.class.getName();
- // Set the carrier technology properties for the web socket carrier technology
- this.setLabel(CARRIER_TECHNOLOGY_LABEL);
- this.setEventProducerPluginClass(EVENT_PRODUCER_PLUGIN_CLASS);
- this.setEventConsumerPluginClass(EVENT_CONSUMER_PLUGIN_CLASS);
- }
-
+ this.setLabel("RESTCLIENT");
+ this.setEventProducerPluginClass(ApexRestClientProducer.class.getName());
+ this.setEventConsumerPluginClass(ApexRestClientConsumer.class.getName());
+ }
}
/*-
* ============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.
package org.onap.policy.apex.plugins.event.carrier.restclient;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.onap.policy.common.parameters.ParameterException;
/**
- * Test REST Requestor carrier technology parameters.
+ * Test REST client carrier technology parameters.
*/
public class RestClientCarrierTechnologyParametersTest {
arguments.setConfigurationFilePath("src/test/resources/prodcons/RESTClientWithHTTPFilterInvalid.json");
arguments.setRelativeFileRoot(".");
- try {
- new ApexParameterHandler().getParameters(arguments);
+ assertThatCode(() -> {
ApexParameters parameters = new ApexParameterHandler().getParameters(arguments);
-
parameters.getEventInputParameters().get("RestClientConsumer0").getCarrierTechnologyParameters();
- fail("test should throw an exception here");
- } catch (ParameterException pe) {
- assertTrue(pe.getMessage().contains(
- "Invalid HTTP code filter, the filter must be specified as a three digit regular expression: "));
- }
+ }).hasMessageContaining(
+ "Invalid HTTP code filter, the filter must be specified as a three digit regular expression: ");
}
@Test
/*-
* ============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.
package org.onap.policy.apex.plugins.event.carrier.restrequestor;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
-
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
import lombok.Getter;
import lombok.Setter;
-import org.apache.commons.lang3.StringUtils;
+
import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters;
import org.onap.policy.common.parameters.GroupValidationResult;
import org.onap.policy.common.parameters.ValidationStatus;
-import org.onap.policy.common.utils.validation.ParameterValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
// @formatter:off
/**
@Getter
@Setter
public class RestRequestorCarrierTechnologyParameters extends RestPluginCarrierTechnologyParameters {
- // Get a reference to the logger
- private static final Logger LOGGER = LoggerFactory.getLogger(RestRequestorCarrierTechnologyParameters.class);
-
-
/** The default HTTP method for request events. */
public static final HttpMethod DEFAULT_REQUESTOR_HTTP_METHOD = HttpMethod.GET;
public RestRequestorCarrierTechnologyParameters() {
super();
- // Set the carrier technology properties for the web socket carrier technology
- CARRIER_TECHNOLOGY_LABEL = "RESTREQUESTOR";
- EVENT_PRODUCER_PLUGIN_CLASS = ApexRestRequestorProducer.class.getName();
- EVENT_CONSUMER_PLUGIN_CLASS = ApexRestRequestorConsumer.class.getName();
- // Set the carrier technology properties for the web socket carrier technology
- this.setLabel(CARRIER_TECHNOLOGY_LABEL);
- this.setEventProducerPluginClass(EVENT_PRODUCER_PLUGIN_CLASS);
- this.setEventConsumerPluginClass(EVENT_CONSUMER_PLUGIN_CLASS);
+ // Set the carrier technology properties for the REST requestor carrier technology
+ this.setLabel("RESTREQUESTOR");
+ this.setEventProducerPluginClass(ApexRestRequestorProducer.class.getName());
+ this.setEventConsumerPluginClass(ApexRestRequestorConsumer.class.getName());
}
// @formatter:off
/*-
* ============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.
final Date event0004StartTime = new Date(1434363272000L);
final Map<String, Object> event0004DataMap = new HashMap<String, Object>();
event0004DataMap.put("TestSlogan", "Test slogan for External Event");
- event0004DataMap.put("TestMatchCase", new Integer(2));
- event0004DataMap.put("TestTimestamp", new Long(event0004StartTime.getTime()));
- event0004DataMap.put("TestTemperature", new Double(1064.43));
- event0004DataMap.put("TestMatchCaseSelected", new Integer(2));
- event0004DataMap.put("TestMatchStateTime", new Long(1434370506078L));
- event0004DataMap.put("TestEstablishCaseSelected", new Integer(0));
- event0004DataMap.put("TestEstablishStateTime", new Long(1434370506085L));
- event0004DataMap.put("TestDecideCaseSelected", new Integer(3));
- event0004DataMap.put("TestDecideStateTime", new Long(1434370506092L));
- event0004DataMap.put("TestActCaseSelected", new Integer(2));
- event0004DataMap.put("TestActStateTime", new Long(1434370506095L));
+ event0004DataMap.put("TestMatchCase", Integer.valueOf(2));
+ event0004DataMap.put("TestTimestamp", Long.valueOf(event0004StartTime.getTime()));
+ event0004DataMap.put("TestTemperature", Double.valueOf(1064.43));
+ event0004DataMap.put("TestMatchCaseSelected", Integer.valueOf(2));
+ event0004DataMap.put("TestMatchStateTime", Long.valueOf(1434370506078L));
+ event0004DataMap.put("TestEstablishCaseSelected", Integer.valueOf(0));
+ event0004DataMap.put("TestEstablishStateTime", Long.valueOf(1434370506085L));
+ event0004DataMap.put("TestDecideCaseSelected", Integer.valueOf(3));
+ event0004DataMap.put("TestDecideStateTime", Long.valueOf(1434370506092L));
+ event0004DataMap.put("TestActCaseSelected", Integer.valueOf(2));
+ event0004DataMap.put("TestActStateTime", Long.valueOf(1434370506095L));
final ApexEvent apexEvent0004 =
new ApexEvent("Event0004", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
/*-
* ============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.
// Get the class for state finalizer execution
try {
// Create the state finalizer logic object from the byte code of the class
- stateFinalizerLogicObject = Class.forName(getSubject().getLogic()).newInstance();
+ stateFinalizerLogicObject = Class.forName(getSubject().getLogic()).getDeclaredConstructor().newInstance();
} catch (final Exception e) {
LOGGER.error("instantiation error on Java class \"" + getSubject().getLogic() + "\"", e);
throw new StateMachineException("instantiation error on Java class \"" + getSubject().getLogic() + "\"", e);
// to invoke the
// task logic in the Java class
final Method method = stateFinalizerLogicObject.getClass().getDeclaredMethod("getStateOutput",
- new Class[] { StateFinalizerExecutionContext.class });
+ new Class[] {StateFinalizerExecutionContext.class});
returnValue = (boolean) method.invoke(stateFinalizerLogicObject, getExecutionContext());
} catch (final Exception e) {
LOGGER.error("execute: state finalizer logic failed to run for state finalizer \"" + getSubject().getId()
/*-
* ============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.
// Get the class for task execution
try {
// Create the task logic object from the byte code of the class
- taskLogicObject = Class.forName(getSubject().getTaskLogic().getLogic()).newInstance();
+ taskLogicObject =
+ Class.forName(getSubject().getTaskLogic().getLogic()).getDeclaredConstructor().newInstance();
} catch (final Exception e) {
LOGGER.error("instantiation error on Java class \"" + getSubject().getTaskLogic().getLogic() + "\"", e);
throw new StateMachineException(
// Find and call the method with the signature "public boolean getEvent(final TaskExecutionContext executor)
// throws ApexException" to invoke the
// task logic in the Java class
- final Method method = taskLogicObject.getClass().getDeclaredMethod("getEvent",
- new Class[] { TaskExecutionContext.class });
+ final Method method =
+ taskLogicObject.getClass().getDeclaredMethod("getEvent", new Class[] {TaskExecutionContext.class});
returnValue = (boolean) method.invoke(taskLogicObject, getExecutionContext());
} catch (final Exception e) {
LOGGER.error("execute: task logic failed to run for task \"" + getSubject().getKey().getId() + "\"");
/*-
* ============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.
// Get the class for task selection
try {
// Create the task logic object from the byte code of the class
- taskSelectionLogicObject = Class.forName(getSubject().getTaskSelectionLogic().getLogic()).newInstance();
+ taskSelectionLogicObject = Class.forName(getSubject().getTaskSelectionLogic().getLogic())
+ .getDeclaredConstructor().newInstance();
} catch (final Exception e) {
LOGGER.error(
"instantiation error on Java class \"" + getSubject().getTaskSelectionLogic().getLogic() + "\"", e);
// executor)" to invoke the task selection
// logic in the Java class
final Method method = taskSelectionLogicObject.getClass().getDeclaredMethod("getTask",
- new Class[] { TaskSelectionExecutionContext.class });
+ new Class[] {TaskSelectionExecutionContext.class});
returnValue = (boolean) method.invoke(taskSelectionLogicObject, getExecutionContext());
} catch (final Exception e) {
LOGGER.error(
/*-
* ============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.
* @throws ApexEventException on errors creating the Apex event consumer
*/
public ApexEventConsumer createConsumer(final String name, final EventHandlerParameters consumerParameters)
- throws ApexEventException {
+ throws ApexEventException {
// Get the carrier technology parameters
final CarrierTechnologyParameters technologyParameters = consumerParameters.getCarrierTechnologyParameters();
final String consumerPluginClass = technologyParameters.getEventConsumerPluginClass();
Object consumerPluginObject = null;
try {
- consumerPluginObject = Class.forName(consumerPluginClass).newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
+ consumerPluginObject = Class.forName(consumerPluginClass).getDeclaredConstructor().newInstance();
+ } catch (final Exception e) {
final String errorMessage = "could not create an Apex event consumer for \"" + name
- + "\" for the carrier technology \"" + technologyParameters.getLabel()
- + "\", specified event consumer plugin class \"" + consumerPluginClass + "\" not found";
+ + "\" for the carrier technology \"" + technologyParameters.getLabel()
+ + "\", specified event consumer plugin class \"" + consumerPluginClass + "\" not found";
LOGGER.error(errorMessage, e);
throw new ApexEventException(errorMessage, e);
}
// Check the class is an event consumer
if (!(consumerPluginObject instanceof ApexEventConsumer)) {
final String errorMessage = "could not create an Apex event consumer \"" + name
- + "\" for the carrier technology \"" + technologyParameters.getLabel()
- + "\", specified event consumer plugin class \"" + consumerPluginClass
- + "\" is not an instance of \"" + ApexEventConsumer.class.getName() + "\"";
+ + "\" for the carrier technology \"" + technologyParameters.getLabel()
+ + "\", specified event consumer plugin class \"" + consumerPluginClass
+ + "\" is not an instance of \"" + ApexEventConsumer.class.getName() + "\"";
LOGGER.error(errorMessage);
throw new ApexEventException(errorMessage);
}
/*-
* ============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.
* @throws ApexEventException on errors creating the Apex event producer
*/
public ApexEventProducer createProducer(final String name, final EventHandlerParameters producerParameters)
- throws ApexEventException {
+ throws ApexEventException {
// Get the carrier technology parameters
final CarrierTechnologyParameters technologyParameters = producerParameters.getCarrierTechnologyParameters();
final String producerPluginClass = technologyParameters.getEventProducerPluginClass();
Object producerPluginObject = null;
try {
- producerPluginObject = Class.forName(producerPluginClass).newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
+ producerPluginObject = Class.forName(producerPluginClass).getDeclaredConstructor().newInstance();
+ } catch (final Exception e) {
final String errorMessage = "could not create an Apex event producer for Producer \"" + name
- + "\" for the carrier technology \"" + technologyParameters.getLabel()
- + "\", specified event producer plugin class \"" + producerPluginClass + "\" not found";
+ + "\" for the carrier technology \"" + technologyParameters.getLabel()
+ + "\", specified event producer plugin class \"" + producerPluginClass + "\" not found";
LOGGER.error(errorMessage, e);
throw new ApexEventException(errorMessage, e);
}
// Check the class is an event producer
if (!(producerPluginObject instanceof ApexEventProducer)) {
final String errorMessage = "could not create an Apex event producer for Producer \"" + name
- + "\" for the carrier technology \"" + technologyParameters.getLabel()
- + "\", specified event producer plugin class \"" + producerPluginClass
- + "\" is not an instance of \"" + ApexEventProducer.class.getName() + "\"";
+ + "\" for the carrier technology \"" + technologyParameters.getLabel()
+ + "\", specified event producer plugin class \"" + producerPluginClass
+ + "\" is not an instance of \"" + ApexEventProducer.class.getName() + "\"";
LOGGER.error(errorMessage);
throw new ApexEventException(errorMessage);
}
/*-
* ============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.
* @return The event converter for converting events to and from Apex format
*/
public ApexEventProtocolConverter createConverter(final String name,
- final EventProtocolParameters eventProtocolParameters) {
+ final EventProtocolParameters eventProtocolParameters) {
// Get the class for the event protocol plugin using reflection
final String eventProtocolPluginClass = eventProtocolParameters.getEventProtocolPluginClass();
Object eventProtocolPluginObject = null;
try {
- eventProtocolPluginObject = Class.forName(eventProtocolPluginClass).newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
+ eventProtocolPluginObject = Class.forName(eventProtocolPluginClass).getDeclaredConstructor().newInstance();
+ } catch (final Exception e) {
final String errorMessage = "could not create an Apex event protocol converter for \"" + name
- + "\" for the protocol \"" + eventProtocolParameters.getLabel()
- + "\", specified event protocol converter plugin class \"" + eventProtocolPluginClass
- + "\" not found";
+ + "\" for the protocol \"" + eventProtocolParameters.getLabel()
+ + "\", specified event protocol converter plugin class \"" + eventProtocolPluginClass
+ + "\" not found";
LOGGER.error(errorMessage, e);
throw new ApexEventRuntimeException(errorMessage, e);
}
// Check the class is an event consumer
if (!(eventProtocolPluginObject instanceof ApexEventProtocolConverter)) {
final String errorMessage = "could not create an Apex event protocol converter for \"" + name
- + "\" for the protocol \"" + eventProtocolParameters.getLabel()
- + "\", specified event protocol converter plugin class \"" + eventProtocolPluginClass
- + "\" is not an instance of \"" + ApexEventProtocolConverter.class.getName() + "\"";
+ + "\" for the protocol \"" + eventProtocolParameters.getLabel()
+ + "\", specified event protocol converter plugin class \"" + eventProtocolPluginClass
+ + "\" is not an instance of \"" + ApexEventProtocolConverter.class.getName() + "\"";
LOGGER.error(errorMessage);
throw new ApexEventRuntimeException(errorMessage);
}
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
+
import lombok.Setter;
+
import org.onap.policy.apex.context.ContextException;
import org.onap.policy.apex.context.ContextRuntimeException;
import org.onap.policy.apex.context.SchemaHelper;
* @throws ApexException thrown on errors on worker instantiation
*/
protected EngineWorker(final AxArtifactKey engineWorkerKey, final BlockingQueue<ApexEvent> queue,
- final ApplicationThreadFactory threadFactory) {
+ final ApplicationThreadFactory threadFactory) {
LOGGER.entry(engineWorkerKey);
this.engineWorkerKey = engineWorkerKey;
@Override
public EngineServiceEventInterface getEngineServiceEventInterface() {
throw new UnsupportedOperationException(
- "getEngineServiceEventInterface() call is not allowed on an Apex Engine Worker");
+ "getEngineServiceEventInterface() call is not allowed on an Apex Engine Worker");
}
/**
*/
@Override
public void updateModel(final AxArtifactKey engineKey, final String engineModel, final boolean forceFlag)
- throws ApexException {
+ throws ApexException {
LOGGER.entry(engineKey);
// Read the Apex model into memory using the Apex Model Reader
final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class);
apexPolicyModel = modelReader.read(new ByteArrayInputStream(engineModel.getBytes()));
} catch (final ApexModelException e) {
- LOGGER.error("failed to unmarshal the apex model on engine " + engineKey.getId(), e);
throw new ApexException("failed to unmarshal the apex model on engine " + engineKey.getId(), e);
}
*/
@Override
public void updateModel(final AxArtifactKey engineKey, final AxPolicyModel apexModel, final boolean forceFlag)
- throws ApexException {
+ throws ApexException {
LOGGER.entry(engineKey);
// Check if the key on the update request is correct
if (!engineWorkerKey.equals(engineKey)) {
- String message = ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
- + ENGINE_SUFFIX;
- LOGGER.warn(message);
+ String message =
+ ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX;
throw new ApexException(message);
}
final AxPolicyModel currentModel = ModelService.getModel(AxPolicyModel.class);
if (!currentModel.getKey().isCompatible(apexModel.getKey())) {
if (forceFlag) {
- LOGGER.warn("apex model update forced, supplied model with key \"" + apexModel.getKey().getId()
- + "\" is not a compatible model update from the existing engine model with key \""
- + currentModel.getKey().getId() + "\"");
+ LOGGER.warn(
+ "apex model update forced, supplied model with key \"{}\" is not a compatible model update "
+ + "from the existing engine model with key \"{}\"",
+ apexModel.getKey().getId(), currentModel.getKey().getId());
} else {
throw new ContextException(
- "apex model update failed, supplied model with key \"" + apexModel.getKey().getId()
- + "\" is not a compatible model update from the existing engine model with key \""
- + currentModel.getKey().getId() + "\"");
+ "apex model update failed, supplied model with key \"" + apexModel.getKey().getId()
+ + "\" is not a compatible model update from the existing engine model with key \""
+ + currentModel.getKey().getId() + "\"");
}
}
}
// Check if the key on the start request is correct
if (!engineWorkerKey.equals(engineKey)) {
- LOGGER.warn(
- ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
- throw new ApexException(
- ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
+ throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
+ + ENGINE_SUFFIX);
}
// Starts the event processing thread that handles incoming events
if (processorThread != null && processorThread.isAlive()) {
- String message = ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already running with state "
- + getState();
+ String message =
+ ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already running with state " + getState();
LOGGER.error(message);
throw new ApexException(message);
}
public void stop(final AxArtifactKey engineKey) throws ApexException {
// Check if the key on the start request is correct
if (!engineWorkerKey.equals(engineKey)) {
- LOGGER.warn(
- ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
- throw new ApexException(
- ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
+ LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
+ + ENGINE_SUFFIX);
+ throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
+ + ENGINE_SUFFIX);
}
// Interrupt the worker to stop its thread
if (processorThread == null || !processorThread.isAlive()) {
processorThread = null;
- LOGGER
- .warn(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already stopped with state " + getState());
+ LOGGER.warn(
+ ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already stopped with state " + getState());
return;
}
public void clear(final AxArtifactKey engineKey) throws ApexException {
// Check if the key on the start request is correct
if (!engineWorkerKey.equals(engineKey)) {
- LOGGER.warn(
- ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
- throw new ApexException(
- ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + ENGINE_SUFFIX);
+ LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
+ + ENGINE_SUFFIX);
+ throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
+ + ENGINE_SUFFIX);
}
// Interrupt the worker to stop its thread
runtimeJsonStringBuilder.append(",\"AlbumContent\":[");
// Get the schema helper to use to marshal context album objects to JSON
- final AxContextAlbum axContextAlbum = ModelService.getModel(AxContextAlbums.class)
- .get(contextAlbumEntry.getKey());
+ final AxContextAlbum axContextAlbum =
+ ModelService.getModel(AxContextAlbums.class).get(contextAlbumEntry.getKey());
SchemaHelper schemaHelper = null;
try {
// Get a schema helper to manage the translations between objects on the album map
// for this album
schemaHelper = new SchemaHelperFactory().createSchemaHelper(axContextAlbum.getKey(),
- axContextAlbum.getItemSchema());
+ axContextAlbum.getItemSchema());
} catch (final ContextRuntimeException e) {
- final String resultString = "could not find schema helper to marshal context album \"" + axContextAlbum
- + "\" to JSON";
+ final String resultString =
+ "could not find schema helper to marshal context album \"" + axContextAlbum + "\" to JSON";
LOGGER.warn(resultString, e);
// End of context album entry
runtimeJsonStringBuilder.append("]}");
// Tidy up the JSON string
- final JsonParser jsonParser = new JsonParser();
- final JsonElement jsonElement = jsonParser.parse(runtimeJsonStringBuilder.toString());
+ final JsonElement jsonElement = JsonParser.parseString(runtimeJsonStringBuilder.toString());
final String tidiedRuntimeString = gson.toJson(jsonElement);
LOGGER.debug("runtime information={}", tidiedRuntimeString);
/*-
* ============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=========================================================
*/
private static final String VALUE_TAG = "\" value \"";
private static final String CARRIER_TECHNOLOGY_PREAMBLE = "carrier technology \"";
-
private static final String PARAMETER_CLASS_NAME = "parameterClassName";
private static final String CARRIER_TECHNOLOGY_TOKEN = "carrierTechnology";
private static final Map<String, String> BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP = new HashMap<>();
static {
- BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("FILE",
- FileCarrierTechnologyParameters.class.getName());
+ BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("FILE", FileCarrierTechnologyParameters.class.getName());
BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("EVENT_REQUESTOR",
EventRequestorCarrierTechnologyParameters.class.getName());
}
// OK no parameters for the carrier technology have been specified, just instantiate the
// default parameters
try {
- carrierTechnologyParameters =
- (CarrierTechnologyParameters) carrierTechnologyParameterClass.newInstance();
+ carrierTechnologyParameters = (CarrierTechnologyParameters) carrierTechnologyParameterClass
+ .getDeclaredConstructor().newInstance();
} catch (final Exception e) {
final String errorMessage = "could not create default parameters for carrier technology \""
+ carrierTechnologyLabel + "\"\n" + e.getMessage();
// Check that the carrier technology label matches the label in the carrier technology
// parameters object
if (!carrierTechnologyParameters.getLabel().equals(carrierTechnologyLabel)) {
- final String errorMessage = CARRIER_TECHNOLOGY_PREAMBLE + carrierTechnologyLabel
- + "\" does not match plugin \""
- + carrierTechnologyParameters.getLabel() + "\" in \"" + carrierTechnologyParameterClassName
- + "\", specify correct carrier technology parameter plugin in parameter \"" + PARAMETER_CLASS_NAME
- + "\"";
+ final String errorMessage =
+ CARRIER_TECHNOLOGY_PREAMBLE + carrierTechnologyLabel + "\" does not match plugin \""
+ + carrierTechnologyParameters.getLabel() + "\" in \"" + carrierTechnologyParameterClassName
+ + "\", specify correct carrier technology parameter plugin in parameter \""
+ + PARAMETER_CLASS_NAME + "\"";
LOGGER.warn(errorMessage);
throw new ParameterRuntimeException(errorMessage);
}
/*-
* ============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 lombok.Getter;
import lombok.Setter;
+
import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters;
import org.onap.policy.common.parameters.GroupValidationResult;
import org.onap.policy.common.parameters.ValidationStatus;
import org.onap.policy.common.utils.validation.ParameterValidationUtils;
/** The supported HTTP methods. */
public enum HttpMethod {
- GET, PUT, POST, DELETE
+ GET,
+ PUT,
+ POST,
+ DELETE
}
- /** The label of this carrier technology. */
- protected String CARRIER_TECHNOLOGY_LABEL;
-
- /** The producer plugin class for the REST carrier technology. */
- protected String EVENT_PRODUCER_PLUGIN_CLASS;
-
- /** The consumer plugin class for the REST carrier technology. */
- protected String EVENT_CONSUMER_PLUGIN_CLASS;
-
/** The default HTTP code filter, allows 2xx HTTP codes through. */
public static final String DEFAULT_HTTP_CODE_FILTER = "[2][0-9][0-9]";
protected static final Pattern patternErrorKey =
Pattern.compile("(\\{[^\\{}]*.?\\{)|(\\{[^\\{}]*$)|(\\}[^\\{}]*.?\\})|(^[^\\{}]*.?\\})|\\{\\s*\\}");
- //variable
+ // variable
protected String url = null;
protected HttpMethod httpMethod = null;
protected String[][] httpHeaders = null;
*/
public RestPluginCarrierTechnologyParameters() {
super();
-
- // Set the carrier technology properties for the web socket carrier technology
- CARRIER_TECHNOLOGY_LABEL = "RESTPLUGIN";
- EVENT_PRODUCER_PLUGIN_CLASS = "PRODUCER";
- EVENT_CONSUMER_PLUGIN_CLASS = "CONSUMER";
- this.setLabel(CARRIER_TECHNOLOGY_LABEL);
- this.setEventProducerPluginClass(EVENT_PRODUCER_PLUGIN_CLASS);
- this.setEventConsumerPluginClass(EVENT_CONSUMER_PLUGIN_CLASS);
}
/**
public GroupValidationResult validate() {
GroupValidationResult result = super.validate();
- result = validateUrl(result);
-
- result = validateHttpHeaders(result);
+ validateUrl(result);
+ validateHttpHeaders(result);
return validateHttpCodeFilter(result);
}
// @formatter:on
public GroupValidationResult validateUrl(final GroupValidationResult result) {
// Check if the URL has been set for event output
- String URL_ERROR_MSG = "no URL has been set for event sending on " + CARRIER_TECHNOLOGY_LABEL;
+ String urlErrorMessage = "no URL has been set for event sending on " + getLabel();
if (getUrl() == null) {
- result.setResult("url", ValidationStatus.INVALID, URL_ERROR_MSG);
+ result.setResult("url", ValidationStatus.INVALID, urlErrorMessage);
return result;
}
Matcher matcher = patternErrorKey.matcher(getUrl());
if (matcher.find()) {
- result.setResult("url", ValidationStatus.INVALID,
- URL_ERROR_MSG);
+ result.setResult("url", ValidationStatus.INVALID, urlErrorMessage);
}
return result;
*/
@Override
public String toString() {
- return CARRIER_TECHNOLOGY_LABEL +"CarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + ", httpHeaders="
+ return getLabel() + "CarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + ", httpHeaders="
+ Arrays.deepToString(httpHeaders) + ", httpCodeFilter=" + httpCodeFilter + "]";
}
}
/*-
* ============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.slf4j.ext.XLoggerFactory;
/**
- * This class serialises and deserialises various type of event protocol parameters to and from
- * JSON.
+ * This class serialises and deserialises various type of event protocol parameters to and from JSON.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
try {
eventProtocolParameterClass = Class.forName(eventProtocolParameterClassName);
} catch (final ClassNotFoundException e) {
- final String errorMessage =
- EVENT_PROTOCOL_PREFIX + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + VALUE_TAG
- + eventProtocolParameterClassName + "\", could not find class";
+ final String errorMessage = EVENT_PROTOCOL_PREFIX + eventProtocolLabel + "\" parameter \""
+ + PARAMETER_CLASS_NAME + VALUE_TAG + eventProtocolParameterClassName + "\", could not find class";
LOGGER.warn(errorMessage, e);
throw new ParameterRuntimeException(errorMessage, e);
}
// OK no parameters for the event protocol have been specified, just instantiate the
// default parameters
try {
- eventProtocolParameters = (EventProtocolParameters) eventProtocolParameterClass.newInstance();
+ eventProtocolParameters =
+ (EventProtocolParameters) eventProtocolParameterClass.getDeclaredConstructor().newInstance();
} catch (final Exception e) {
final String errorMessage = "could not create default parameters for event protocol \""
+ eventProtocolLabel + "\"\n" + e.getMessage();
/*-
* ============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=========================================================
*/
public class ApexParametersTest {
@Test
- public void javaPropertiesOk() throws ParameterException {
- final String[] args =
- { "-c", "src/test/resources/parameters/javaPropertiesOK.json" };
+ public void testJavaPropertiesOk() throws ParameterException {
+ final String[] args = {"-c", "src/test/resources/parameters/javaPropertiesOK.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
try {
}
@Test
- public void javaPropertiesEmpty() throws ParameterException {
- final String[] args =
- { "-c", "src/test/resources/parameters/javaPropertiesEmpty.json" };
+ public void testJavaPropertiesEmpty() throws ParameterException {
+ final String[] args = {"-c", "src/test/resources/parameters/javaPropertiesEmpty.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
try {
fail("This test should not throw an exception");
}
}
-
@Test
- public void javaPropertiesBad() throws ParameterException {
- final String[] args =
- { "-c", "src/test/resources/parameters/javaPropertiesBad.json" };
+ public void testJavaPropertiesBad() throws ParameterException {
+ final String[] args = {"-c", "src/test/resources/parameters/javaPropertiesBad.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
try {
assertTrue(pe.getMessage().contains("java properties array entry is null"));
}
}
-
+
@Test
public void testGettersSetters() {
ApexParameters pars = new ApexParameters();
assertNotNull(pars);
-
+
pars.setEngineServiceParameters(null);
assertNull(pars.getEngineServiceParameters());
-
+
pars.setEventInputParameters(null);
assertNull(pars.getEventInputParameters());
-
+
pars.setEventOutputParameters(null);
assertNull(pars.getEventOutputParameters());
-
+
assertFalse(pars.checkJavaPropertiesSet());
-
+
pars.setName("parName");
assertEquals("parName", pars.getName());
}
+ "\"src/test/resources/parameters/serviceContextBadPluginClassParams.json\""
+ "\n(ClassCastException):class org.onap.policy.apex.service.engine.parameters."
+ "dummyclasses.SuperDooperExecutorParameters"
- + " cannot be cast to class org.onap.policy.apex.context.parameters.ContextParameters (org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperDooperExecutorParameters and org.onap.policy.apex.context.parameters.ContextParameters are in unnamed module of loader 'app')",
- e.getMessage());
+ + " cannot be cast to class org.onap.policy.apex.context.parameters.ContextParameters "
+ + "(org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperDooperExecutorParameters and "
+ + "org.onap.policy.apex.context.parameters.ContextParameters are "
+ + "in unnamed module of loader 'app')", 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.
}
@Test
- public void noParamsTest() {
+ public void testNoParamsTest() {
final String[] args = {"-c", "src/test/resources/parameters/serviceExecutorNoParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void badParamsTest() {
+ public void testBadParamsTest() {
final String[] args = {"-c", "src/test/resources/parameters/serviceExecutorBadParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void noExecutorParamsTest() {
+ public void testNoExecutorParamsTest() {
final String[] args = {"-c", "src/test/resources/parameters/serviceExecutorNoExecutorParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void emptyParamsTest() {
+ public void testEmptyParamsTest() {
final String[] args = {"-c", "src/test/resources/parameters/serviceExecutorEmptyParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void badPluginParamNameTest() {
+ public void testBadPluginParamNameTest() {
final String[] args = {"-c", "src/test/resources/parameters/serviceExecutorBadPluginNameParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void badPluginParamObjectTest() {
+ public void testBadPluginParamObjectTest() {
final String[] args = {"-c", "src/test/resources/parameters/serviceExecutorBadPluginValueObjectParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void badPluginParamBlankTest() {
+ public void testBadPluginParamBlankTest() {
final String[] args = {"-c", "src/test/resources/parameters/serviceExecutorBadPluginValueBlankParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void badPluginParamValueTest() {
+ public void testBadPluginParamValueTest() {
final String[] args = {"-c", "src/test/resources/parameters/serviceExecutorBadPluginValueParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void goodParametersTest() {
+ public void testGoodParametersTest() {
final String[] args = {"-c", "src/test/resources/parameters/goodParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void relativeParametersTest() {
+ public void testRelativeParametersTest() {
// @formatter:off
final String[] args = {
"-rfr",
/*-
* ============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.
*/
public class ParameterTests {
@Test
- public void invalidParametersNoFileTest() throws ParameterException {
+ public void testInvalidParametersNoFileTest() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/invalidNoFile.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void invalidParametersEmptyTest() {
+ public void testInvalidParametersEmptyTest() {
final String[] args = {"-c", "src/test/resources/parameters/empty.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void invalidParametersNoParamsTest() {
+ public void testInvalidParametersNoParamsTest() {
final String[] args = {"-c", "src/test/resources/parameters/noParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void invalidParametersBlankParamsTest() {
+ public void testInvalidParametersBlankParamsTest() {
final String[] args = {"-c", "src/test/resources/parameters/blankParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void invalidParametersTest() {
+ public void testInvalidParametersTest() {
final String[] args = {"-c", "src/test/resources/parameters/badParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void modelNotFileTest() {
+ public void testModelNotFileTest() {
final String[] args = {"-c", "src/test/resources/parameters/badParamsModelNotFile.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void goodParametersTest() {
+ public void testGoodParametersTest() {
final String[] args = {"-c", "src/test/resources/parameters/goodParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void superDooperParametersTest() {
+ public void testSuperDooperParametersTest() {
final String[] args = {"-c", "src/test/resources/parameters/superDooperParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
/*-
* ============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.
*/
public class SyncParameterTests {
@Test
- public void syncBadNoSyncWithPeer() throws ParameterException {
+ public void testSyncBadNoSyncWithPeer() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncBadParamsNoSyncWithPeer.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncBadNotSyncWithPeer() throws ParameterException {
+ public void testSyncBadNotSyncWithPeer() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncBadParamsNotSyncWithPeer.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncBadSyncBadPeers() throws ParameterException {
+ public void testSyncBadSyncBadPeers() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncBadParamsBadPeers.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncBadSyncInvalidTimeout() throws ParameterException {
+ public void testSyncBadSyncInvalidTimeout() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncBadParamsInvalidTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncBadSyncBadTimeout() throws ParameterException {
+ public void testSyncBadSyncBadTimeout() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncBadParamsBadTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncBadSyncUnpairedTimeout() throws ParameterException {
+ public void testSyncBadSyncUnpairedTimeout() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncBadParamsUnpairedTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncGoodSyncGoodTimeoutProducer() throws ParameterException {
+ public void testSyncGoodSyncGoodTimeoutProducer() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncGoodParamsProducerTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncGoodSyncGoodTimeoutConsumer() throws ParameterException {
+ public void testSyncGoodSyncGoodTimeoutConsumer() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncGoodParamsConsumerTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncGoodSyncGoodTimeoutBoth() throws ParameterException {
+ public void testSyncGoodSyncGoodTimeoutBoth() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncGoodParamsBothTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncUnusedConsumerPeers() throws ParameterException {
+ public void testSyncUnusedConsumerPeers() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncUnusedConsumerPeers.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncMismatchedPeers() throws ParameterException {
+ public void testSyncMismatchedPeers() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncMismatchedPeers.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncUnusedProducerPeers() throws ParameterException {
+ public void testSyncUnusedProducerPeers() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncUnusedProducerPeers.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncMismatchedTimeout() throws ParameterException {
+ public void testSyncMismatchedTimeout() throws ParameterException {
final String[] args = {"-c", "src/test/resources/parameters/syncMismatchedTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void syncGoodParametersTest() {
+ public void testSyncGoodParametersTest() {
final String[] args = {"-c", "src/test/resources/parameters/syncGoodParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
<!--
============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.
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onap.policy.apex-pdp.testsuites.integration</groupId>
- <artifactId>integration</artifactId>
+ <artifactId>apex-integration</artifactId>
<version>2.3.0-SNAPSHOT</version>
</parent>
<artifactId>integration-common</artifactId>
<!--
============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.
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onap.policy.apex-pdp.testsuites.integration</groupId>
- <artifactId>integration</artifactId>
+ <artifactId>apex-integration</artifactId>
<version>2.3.0-SNAPSHOT</version>
</parent>
</distributionManagement>
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
/*-
* ============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.
private static final String TEST_POLICY_CONTEXT_ITEM001 = "TestPolicyContextItem001";
private static final String NORMAL_TEST_EXCEPTION = "normal test exception";
private static final String NULL_VALUES_ILLEGAL_TAG =
- "album \"ExternalContextAlbum:0.0.1\" null values are illegal on key ";
+ "album \"ExternalContextAlbum:0.0.1\" null values are illegal on key ";
private static final TreeSet<String> TEST_TREE_SET = new TreeSet<>();
private static final Map<String, String> TEST_HASH_MAP = new HashMap<>();
final Distributor contextDistributor = getDistributor();
- final ContextAlbum policyContextAlbum = contextDistributor
- .createContextAlbum(new AxArtifactKey(POLICY_CONTEXT_ALBUM, VERSION));
+ final ContextAlbum policyContextAlbum =
+ contextDistributor.createContextAlbum(new AxArtifactKey(POLICY_CONTEXT_ALBUM, VERSION));
assertNotNull(policyContextAlbum);
policyContextAlbum.setUserArtifactStack(Constants.getAxArtifactKeyArray());
policyContextAlbum.putAll(valueMap0);
- final TestPolicyContextItem contextItem = (TestPolicyContextItem) policyContextAlbum
- .get(TEST_POLICY_CONTEXT_ITEM);
+ final TestPolicyContextItem contextItem =
+ (TestPolicyContextItem) policyContextAlbum.get(TEST_POLICY_CONTEXT_ITEM);
assertEquals(STRING_VAL, contextItem.getTestPolicyContextItem000().getStringValue());
assertEquals(LONG_VAL, contextItem.getTestPolicyContextItem001().getLongValue());
assertEquals(contextItem.getTestPolicyContextItem004().getLongValue(), testDate.getTime());
assertEquals(TEST_HASH_MAP, contextItem.getTestPolicyContextItem005().getMapValue());
- final TestGlobalContextItem globalContext = getTestGlobalContextItem(contextDistributor, testDate, tci9,
- tciA);
+ final TestGlobalContextItem globalContext = getTestGlobalContextItem(contextDistributor, testDate, tci9, tciA);
final Map<String, Object> valueMap1 = new HashMap<>();
valueMap1.put(GLOBAL_CONTEXT_KEY, globalContext);
globalContextAlbum.putAll(valueMap1);
- final TestGlobalContextItem globalContextItem = (TestGlobalContextItem) globalContextAlbum
- .get(GLOBAL_CONTEXT_KEY);
+ final TestGlobalContextItem globalContextItem =
+ (TestGlobalContextItem) globalContextAlbum.get(GLOBAL_CONTEXT_KEY);
assertFalse(globalContextItem.getTestGlobalContextItem000().getFlag());
assertEquals((Long) testDate.getTime(), globalContextItem.getTestGlobalContextItem007().getLongValue());
assertEquals(testDate, globalContextItem.getTestGlobalContextItem008().getDateValue());
assertEquals(tci9.getDateValue().getTime(),
- globalContextItem.getTestGlobalContextItem009().getDateValue().getTime());
+ globalContextItem.getTestGlobalContextItem009().getDateValue().getTime());
assertEquals(tciA.getDateValue().getTime(),
- globalContextItem.getTestGlobalContextItem00A().getDateValue().getTime());
+ globalContextItem.getTestGlobalContextItem00A().getDateValue().getTime());
assertEquals(TEST_TREE_SET, globalContextItem.getTestGlobalContextItem00B().getSetValue());
assertEquals(TEST_HASH_MAP, globalContextItem.getTestGlobalContextItem00C().getMapValue());
externalContextAlbum.putAll(valueMap2);
externalContextAlbum.getAlbumDefinition().setWritable(false);
- TestExternalContextItem externalContextItem = (TestExternalContextItem) externalContextAlbum
- .get(EXTERNAL_CONTEXT);
+ TestExternalContextItem externalContextItem =
+ (TestExternalContextItem) externalContextAlbum.get(EXTERNAL_CONTEXT);
assertFalse(externalContextItem.getTestExternalContextItem000().getFlag());
assertEquals(BYTE_VAL, externalContextItem.getTestExternalContextItem001().getByteValue());
assertEquals((Long) testDate.getTime(), externalContextItem.getTestExternalContextItem007().getLongValue());
assertEquals(testDate, externalContextItem.getTestExternalContextItem008().getDateValue());
assertEquals(tci9A.getDateValue().getTime(),
- externalContextItem.getTestExternalContextItem009().getDateValue().getTime());
+ externalContextItem.getTestExternalContextItem009().getDateValue().getTime());
assertEquals(tciAa.getDateValue().getTime(),
- externalContextItem.getTestExternalContextItem00A().getDateValue().getTime());
+ externalContextItem.getTestExternalContextItem00A().getDateValue().getTime());
assertEquals(TEST_TREE_SET, externalContextItem.getTestExternalContextItem00B().getSetValue());
assertEquals(TEST_HASH_MAP, externalContextItem.getTestExternalContextItem00C().getMapValue());
fail(EXCEPTION_MESSAGE);
} catch (final ContextRuntimeException e) {
assertEquals("album \"ExternalContextAlbum:0.0.1\" clear() not allowed on read only albums",
- e.getMessage());
+ e.getMessage());
LOGGER.trace(NORMAL_TEST_EXCEPTION, e);
}
externalContextAlbum.get(null);
} catch (final ContextRuntimeException e) {
assertEquals("album \"ExternalContextAlbum:0.0.1\" null keys are illegal on keys for get()",
- e.getMessage());
+ e.getMessage());
LOGGER.trace(NORMAL_TEST_EXCEPTION, e);
}
externalContextAlbum.put(null, null);
} catch (final ContextRuntimeException e) {
assertEquals("album \"ExternalContextAlbum:0.0.1\" null keys are illegal on keys for put()",
- e.getMessage());
+ e.getMessage());
LOGGER.trace(NORMAL_TEST_EXCEPTION, e);
}
}
private void assertContextAlbumContains(final TestExternalContextItem externalContext,
- final ContextAlbum externalContextAlbum) {
+ final ContextAlbum externalContextAlbum) {
try {
externalContextAlbum.containsKey(null);
} catch (final ContextRuntimeException e) {
}
private ContextAlbum getContextAlbum(final Distributor contextDistributor) throws ContextException {
- final ContextAlbum globalContextAlbum = contextDistributor
- .createContextAlbum(new AxArtifactKey(GLOBAL_CONTEXT_ALBUM, VERSION));
+ final ContextAlbum globalContextAlbum =
+ contextDistributor.createContextAlbum(new AxArtifactKey(GLOBAL_CONTEXT_ALBUM, VERSION));
assertNotNull(globalContextAlbum);
globalContextAlbum.setUserArtifactStack(Constants.getAxArtifactKeyArray());
return globalContextAlbum;
}
private TestGlobalContextItem getTestGlobalContextItem(final Distributor contextDistributor, final Date testDate,
- final TestContextDateTzItem tci9, final TestContextDateLocaleItem tciA) throws ContextException {
+ final TestContextDateTzItem tci9, final TestContextDateLocaleItem tciA) throws ContextException {
final AxContextModel globalContextModel = TestContextAlbumFactory.createGlobalContextModel();
final TestGlobalContextItem globalContext = getTestGlobalContextItem(testDate, tci9, tciA);
contextDistributor.registerModel(globalContextModel);
}
private TestGlobalContextItem getTestGlobalContextItem(final Date testDate, final TestContextDateTzItem tci9,
- final TestContextDateLocaleItem tciA) {
+ final TestContextDateLocaleItem tciA) {
final TestGlobalContextItem globalContext = new TestGlobalContextItem();
final TestContextBooleanItem testGlobalContextItem000 = new TestContextBooleanItem(false);
}
private void assertPutMethods(final ContextAlbum policyContextAlbum, final TestContextStringItem contextStringItem,
- final Map<String, Object> valueMapA) {
+ final Map<String, Object> valueMapA) {
try {
policyContextAlbum.put(TEST_POLICY_CONTEXT_ITEM000, contextStringItem);
fail(EXCEPTION_MESSAGE);
} catch (final ContextRuntimeException e) {
assertEquals(getMessage(TEST_POLICY_CONTEXT_ITEM000, "TestContextItem006",
- TestContextStringItem.class.getName(), "stringValue=" + STRING_VAL),
- e.getMessage());
+ TestContextStringItem.class.getName(), "stringValue=" + STRING_VAL), e.getMessage());
LOGGER.trace(NORMAL_TEST_EXCEPTION, e);
}
fail(EXCEPTION_MESSAGE);
} catch (final ContextRuntimeException e) {
assertEquals(getMessage(TEST_POLICY_CONTEXT_ITEM001, "TestContextItem003",
- TestContextLongItem.class.getName(), "longValue=" + INT_VAL_3), e.getMessage());
+ TestContextLongItem.class.getName(), "longValue=" + INT_VAL_3), e.getMessage());
LOGGER.trace(NORMAL_TEST_EXCEPTION, e);
}
}
}
private TestExternalContextItem getTestExternalContextItem(final Date testDate, final TestContextDateTzItem tci9A,
- final TestContextDateLocaleItem tciAa) {
+ final TestContextDateLocaleItem tciAa) {
final TestExternalContextItem externalContext = new TestExternalContextItem();
final TestContextBooleanItem testExternalContextItem000 = new TestContextBooleanItem(false);
final TestContextByteItem testExternalContextItem001 = new TestContextByteItem(BYTE_VAL);
final TestContextIntItem testExternalContextItem002 = new TestContextIntItem(INT_VAL);
final TestContextLongItem testExternalContextItem003 = new TestContextLongItem(LONG_VAL);
- final TestContextFloatItem testExternalContextItem004 = new TestContextFloatItem(new Float(3.14159265359));
+ final TestContextFloatItem testExternalContextItem004 = new TestContextFloatItem(3.14159265359F);
final TestContextDoubleItem testExternalContextItem005 = new TestContextDoubleItem(PI_VAL);
final TestContextStringItem testExternalContextItem006 = new TestContextStringItem(STRING_EXT_VAL);
final TestContextLongObjectItem testExternalContextItem007 = new TestContextLongObjectItem(testDate.getTime());
}
private String getMessage(final String key, final String objName, final String clazzName, final String valString,
- final String compatibleClazzName) {
+ final String compatibleClazzName) {
return "Failed to set context value for key \"" + key + "\" in album \"PolicyContextAlbum:0.0.1\": "
- + "PolicyContextAlbum:0.0.1: object \"" + objName + " [" + valString + "]\" " + "of class \""
- + clazzName + "\"" + " not compatible with class \"" + compatibleClazzName + "\"";
+ + "PolicyContextAlbum:0.0.1: object \"" + objName + " [" + valString + "]\" " + "of class \""
+ + clazzName + "\"" + " not compatible with class \"" + compatibleClazzName + "\"";
}
private void assertFloat(final float actual, final float expected) {
<!--
============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.
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onap.policy.apex-pdp.testsuites.integration</groupId>
- <artifactId>integration</artifactId>
+ <artifactId>apex-integration</artifactId>
<version>2.3.0-SNAPSHOT</version>
</parent>
</distributionManagement>
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
/*-
* ============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.
/**
* Instantiates a new test apex engine.
*
- * @param axLogicExecutorType the type of logic executor to use to construct the sample policy
- * model for this test
+ * @param axLogicExecutorType the type of logic executor to use to construct the sample policy model for this test
* @throws ApexException the apex exception
* @throws InterruptedException the interrupted exception
* @throws IOException Signals that an I/O exception has occurred.
*/
- public TestApexEngine(final String axLogicExecutorType, final EngineParameters parameters)
- throws ApexException, InterruptedException, IOException {
+ public TestApexEngine(final String axLogicExecutorType,
+ final EngineParameters parameters) throws ApexException, InterruptedException, IOException {
logger.debug("Running TestApexEngine test for + " + axLogicExecutorType + "logic . . .");
final AxPolicyModel apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel(axLogicExecutorType);
final Date aDate = new Date(1433453067123L);
final Map<String, Object> eventDataMap = new HashMap<String, Object>();
eventDataMap.put("TestSlogan", "This is a test slogan for event " + event.getName());
- eventDataMap.put("TestMatchCase", new Byte((byte) 123));
+ eventDataMap.put("TestMatchCase", (byte) 123);
eventDataMap.put("TestTimestamp", aDate.getTime());
eventDataMap.put("TestTemperature", 34.5445667);
/*-
* ============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.
assertNotNull(slogan1);
assertEquals("This is a slogan", slogan1);
- Object mc1 = event.put("TestMatchCase", new Byte("4"));
+ Object mc1 = event.put("TestMatchCase", Byte.valueOf("4"));
assertNull(mc1);
mc1 = event.get("TestMatchCase");
assertNotNull(mc1);
assertEquals((byte) 4, mc1);
- Object mc2 = event.put("TestMatchCase", new Byte("16"));
+ Object mc2 = event.put("TestMatchCase", Byte.valueOf("16"));
assertNotNull(mc2);
assertEquals((byte) 4, mc2);
mc2 = event.get("TestMatchCase");
event.put("TestMatchCase", "Hello");
} catch (final Exception e) {
assertEquals("Event0000:0.0.1:NULL:TestMatchCase: object \"Hello\" of class \"java.lang.String\" "
- + "not compatible with class \"java.lang.Byte\"", e.getMessage());
+ + "not compatible with class \"java.lang.Byte\"", e.getMessage());
}
try {
event.put("TestMatchCase", 123.45);
} catch (final Exception e) {
assertEquals("Event0000:0.0.1:NULL:TestMatchCase: object \"123.45\" of class \"java.lang.Double\" "
- + "not compatible with class \"java.lang.Byte\"", e.getMessage());
+ + "not compatible with class \"java.lang.Byte\"", e.getMessage());
}
- event.put("TestMatchCase", new Byte("16"));
+ event.put("TestMatchCase", Byte.valueOf("16"));
final String slogan2 = (String) event.get("TestSlogan");
assertNotNull(slogan2);
final Date aDate = new Date(1433453067123L);
final Map<String, Object> eventDataList = new HashMap<String, Object>();
eventDataList.put("TestSlogan", "This is a test slogan");
- eventDataList.put("TestMatchCase", new Byte("123"));
+ eventDataList.put("TestMatchCase", Byte.valueOf("123"));
eventDataList.put("TestTimestamp", aDate.getTime());
eventDataList.put("TestTemperature", 34.5445667);
/*-
* ============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.
* @throws ContextException the context exception
*/
private void sendEvent(final ApexEngine apexEngine, final TestApexActionListener listener, final String eventName,
- final boolean shouldWork) throws ContextException {
+ final boolean shouldWork) throws ContextException {
final Date aDate = new Date(1433453067123L);
final Map<String, Object> eventDataMap = new HashMap<String, Object>();
eventDataMap.put("TestSlogan", "This is a test slogan");
- eventDataMap.put("TestMatchCase", new Byte((byte) 123));
+ eventDataMap.put("TestMatchCase", (byte) 123);
eventDataMap.put("TestTimestamp", aDate.getTime());
eventDataMap.put("TestTemperature", 34.5445667);
<!--
============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.
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onap.policy.apex-pdp.testsuites.integration</groupId>
- <artifactId>integration</artifactId>
+ <artifactId>apex-integration</artifactId>
<version>2.3.0-SNAPSHOT</version>
</parent>
/*-
* ============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=========================================================
*/
}
/**
- * The listener interface for receiving testApex events. The class that is interested in
- * processing a testApex event implements this interface, and the object created with that class
- * is registered with a component using the component's {@code addTestApexListener} method. When
- * the testApex event occurs, that object's appropriate method is invoked.
+ * The listener interface for receiving testApex events. The class that is interested in processing a testApex event
+ * implements this interface, and the object created with that class is registered with a component using the
+ * component's {@code addTestApexListener} method. When the testApex event occurs, that object's appropriate method
+ * is invoked.
*
* <p>This class listens for events from the Apex engine
*
// CHECKSTYLE:OFF: checkstyle:magicNumber
assert result.get("TestSlogan").equals("This is a test slogan");
- assert result.get("TestMatchCase").equals(new Byte((byte) 123));
+ assert result.get("TestMatchCase").equals((byte) 123);
assert result.get("TestTemperature").equals(34.5445667);
assert ((byte) result.get("TestMatchCaseSelected") >= 0 && (byte) result.get("TestMatchCaseSelected") <= 3);
assert ((byte) result.get("TestEstablishCaseSelected") >= 0
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
} catch (final Exception e) {
e.printStackTrace();
assertEquals("start()<-Machine-1_process-1_engine-1-0:0.0.0,STOPPED, cannot start engine, "
- + "engine has not been initialized, its model is not loaded", e.getMessage());
+ + "engine has not been initialized, its model is not loaded", e.getMessage());
}
}
} catch (final Exception e) {
System.err.println(e.getMessage());
assertEquals("apex model update failed, supplied model with key \"INCOMPATIBLE:0.0.1\" is not a compatible "
- + "model update from the existing engine model "
- + "with key \"SamplePolicyModelJAVASCRIPT:0.0.1\"", e.getMessage());
+ + "model update from the existing engine model " + "with key \"SamplePolicyModelJAVASCRIPT:0.0.1\"",
+ e.getMessage());
}
// Still on old model
System.err.println(e.getMessage());
e.printStackTrace();
assertEquals("apex model update failed, supplied model with key \"SamplePolicyModelJAVASCRIPT:1.0.1\" "
- + "is not a compatible model update from the existing engine model with key "
- + "\"SamplePolicyModelJAVASCRIPT:0.0.1\"", e.getMessage());
+ + "is not a compatible model update from the existing engine model with key "
+ + "\"SamplePolicyModelJAVASCRIPT:0.0.1\"", e.getMessage());
}
// Still on old model
/**
* Utility method to send some events into the test engine.
- *
+ *
* @throws ApexEventException if there is an error
*/
private void sendEvents() throws ApexEventException {
eventDataMap.put("TestTimestamp", testStartTime.getTime());
eventDataMap.put("TestTemperature", 34.5445667);
- final ApexEvent event = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "test", "apex");
+ final ApexEvent event =
+ new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
event.putAll(eventDataMap);
engineServiceEventInterface.sendEvent(event);
- final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "test", "apex");
+ final ApexEvent event2 =
+ new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
event2.putAll(eventDataMap);
engineServiceEventInterface.sendEvent(event2);
assertTrue(result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104"));
assertTrue(result.get("TestSlogan").equals("This is a test slogan"));
- assertTrue(result.get("TestMatchCase").equals(new Byte((byte) 123)));
+ assertTrue(result.get("TestMatchCase").equals((byte) 123));
assertTrue(result.get("TestTemperature").equals(34.5445667));
assertTrue(((byte) result.get("TestMatchCaseSelected")) >= 0
- && ((byte) result.get("TestMatchCaseSelected") <= 3));
+ && ((byte) result.get("TestMatchCaseSelected") <= 3));
assertTrue(((byte) result.get("TestEstablishCaseSelected")) >= 0
- && ((byte) result.get("TestEstablishCaseSelected") <= 3));
+ && ((byte) result.get("TestEstablishCaseSelected") <= 3));
assertTrue(((byte) result.get("TestDecideCaseSelected")) >= 0
- && ((byte) result.get("TestDecideCaseSelected") <= 3));
- assertTrue(((byte) result.get("TestActCaseSelected")) >= 0
- && ((byte) result.get("TestActCaseSelected") <= 3));
+ && ((byte) result.get("TestDecideCaseSelected") <= 3));
+ assertTrue(
+ ((byte) result.get("TestActCaseSelected")) >= 0 && ((byte) result.get("TestActCaseSelected") <= 3));
}
}
-
/**
* Gets the model string.
/*-
* ============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.
eventDataMap.put("TestTimestamp", testStartTime.getTime());
eventDataMap.put("TestTemperature", 34.5445667);
- final ApexEvent event = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "test", "apex");
+ final ApexEvent event =
+ new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
event.setExecutionId(System.nanoTime());
event.putAll(eventDataMap);
engineServiceEventInterface.sendEvent(event);
- final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "test", "apex");
+ final ApexEvent event2 =
+ new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
event2.setExecutionId(System.nanoTime());
event2.putAll(eventDataMap);
engineServiceEventInterface.sendEvent(event2);
eventDataMap.put("TestTimestamp", testStartTime.getTime());
eventDataMap.put("TestTemperature", 34.5445667);
- final ApexEvent event1 = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "test", "apex");
+ final ApexEvent event1 =
+ new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
event1.putAll(eventDataMap);
event1.setExecutionId(System.nanoTime());
ThreadUtilities.sleep(100);
}
- final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "test", "apex");
+ final ApexEvent event2 =
+ new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
event2.setExecutionId(System.nanoTime());
event2.putAll(eventDataMap);
eventDataMap.put("TestTimestamp", testStartTime.getTime());
eventDataMap.put("TestTemperature", 34.5445667);
- final ApexEvent event = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "test", "apex");
+ final ApexEvent event =
+ new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
event.setExecutionId(System.nanoTime());
event.putAll(eventDataMap);
engineServiceEventInterface.sendEvent(event);
- final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "test", "apex");
+ final ApexEvent event2 =
+ new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
event2.setExecutionId(System.nanoTime());
event2.putAll(eventDataMap);
engineServiceEventInterface.sendEvent(event2);
eventDataMap.put("TestTimestamp", testStartTime.getTime());
eventDataMap.put("TestTemperature", 34.5445667);
- final ApexEvent event1 = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "test", "apex");
+ final ApexEvent event1 =
+ new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
event1.putAll(eventDataMap);
final ApexEventListener myEventListener1 = new ApexEventListener() {
ThreadUtilities.sleep(100);
}
- final ApexEvent event2 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "test", "apex");
+ final ApexEvent event2 =
+ new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
event2.putAll(eventDataMap);
final ApexEventListener myEventListener2 = new ApexEventListener() {
assertTrue(result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104"));
assertTrue(result.get("TestSlogan").equals("This is a test slogan"));
- assertTrue(result.get("TestMatchCase").equals(new Byte((byte) 123)));
+ assertTrue(result.get("TestMatchCase").equals((byte) 123));
assertTrue(result.get("TestTemperature").equals(34.5445667));
assertTrue(((byte) result.get("TestMatchCaseSelected")) >= 0
- && ((byte) result.get("TestMatchCaseSelected") <= 3));
+ && ((byte) result.get("TestMatchCaseSelected") <= 3));
assertTrue(((byte) result.get("TestEstablishCaseSelected")) >= 0
- && ((byte) result.get("TestEstablishCaseSelected") <= 3));
+ && ((byte) result.get("TestEstablishCaseSelected") <= 3));
assertTrue(((byte) result.get("TestDecideCaseSelected")) >= 0
- && ((byte) result.get("TestDecideCaseSelected") <= 3));
- assertTrue(((byte) result.get("TestActCaseSelected")) >= 0
- && ((byte) result.get("TestActCaseSelected") <= 3));
+ && ((byte) result.get("TestDecideCaseSelected") <= 3));
+ assertTrue(
+ ((byte) result.get("TestActCaseSelected")) >= 0 && ((byte) result.get("TestActCaseSelected") <= 3));
}
}
<!--
============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.
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onap.policy.apex-pdp.testsuites.performance</groupId>
- <artifactId>performance</artifactId>
+ <artifactId>apex-performance</artifactId>
<version>2.3.0-SNAPSHOT</version>
</parent>
File tempFile = File.createTempFile(modelName, ".apex");
tempFile.deleteOnExit();
- final String[] cliArgs =
- {"-m", modelPath + "/" + modelName + ".json", "-o", tempFile.getCanonicalPath(), "-ow"};
+ // @formatter:off
+ final String[] cliArgs = {
+ "-m",
+ modelPath + "/" + modelName + ".json",
+ "-o",
+ tempFile.getCanonicalPath(),
+ "-ow"
+ };
+ // @formatter:on
runModel2Cli(cliArgs);
assertTrue(tempFile.isFile());