/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
* @author Sven van der Meer (sven.van.der.meer@ericsson.com)
* @author John Keeney (John.Keeney@ericsson.com)
*/
-public class CgStringRenderer implements AttributeRenderer {
+public class CgStringRenderer implements AttributeRenderer<Object> {
/**
* {@inheritDoc}.
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
/**
* Create an instance of an abstract Context Distributor.
*/
- public AbstractDistributor() {
+ protected AbstractDistributor() {
LOGGER.entry("AbstractContextDistributor()");
LOGGER.exit("AbstractContextDistributor()");
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
private ReadWriteLock getLock(final String lockTypeKey, final String lockKey, final boolean createMode)
throws ContextException {
- // Check if we have a lock type map for this lock type yet
- if (!lockMaps.containsKey(lockTypeKey)) {
- // Create a lock type map for the lock type
- lockMaps.put(lockTypeKey, Collections.synchronizedMap(new HashMap<String, ReadWriteLock>()));
- }
+ // Find or create a map for the lock type
+ Map<String, ReadWriteLock> lockTypeMap = lockMaps.computeIfAbsent(lockTypeKey,
+ unusedKey -> Collections.synchronizedMap(new HashMap<String, ReadWriteLock>()));
// Find or create a lock in the lock map
- ReadWriteLock lock = lockMaps.get(lockTypeKey).get(lockKey);
+ ReadWriteLock lock = lockTypeMap.get(lockKey);
if (lock != null) {
return lock;
}
lock = getReentrantReadWriteLock(lockTypeKey + "_" + lockKey);
// Add the lock to the lock map
- lockMaps.get(lockTypeKey).put(lockKey, lock);
+ lockTypeMap.put(lockKey, lock);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("created lock {}_{}", lockTypeKey, lockKey);
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Setter
private AxConcept[] userArtifactStack;
- private static Random rand = new Random(System.nanoTime());
+ /*
+ * This is not used for encryption/security, thus disabling sonar.
+ */
+ private static Random rand = new Random(System.nanoTime()); // NOSONAR
// An identifier for the current event execution. The default value here will always be a random
// number, and should
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Getter
public class AbstractExecutionContext {
/** A constant <code>boolean true</code> value available for reuse e.g., for the return value */
- public final Boolean isTrue = true;
+ public static final Boolean IS_TRUE = true;
/**
* A constant <code>boolean false</code> value available for reuse e.g., for the return value
*/
- public final Boolean isFalse = false;
+ public static final Boolean IS_FALSE = false;
/** the execution ID for the current APEX policy execution instance. */
public final Long executionId;
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.Properties;
import java.util.TreeMap;
import lombok.Getter;
-import lombok.Setter;
import org.onap.policy.apex.context.ContextAlbum;
import org.onap.policy.apex.context.ContextRuntimeException;
-import org.onap.policy.apex.context.SchemaHelper;
import org.onap.policy.apex.core.engine.context.ApexInternalContext;
import org.onap.policy.apex.core.engine.executor.Executor;
import org.onap.policy.apex.core.engine.executor.TaskExecutor;
import org.onap.policy.apex.model.basicmodel.concepts.AxConcept;
import org.onap.policy.apex.model.policymodel.concepts.AxTask;
import org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter;
-import org.onap.policy.common.utils.coder.CoderException;
-import org.onap.policy.common.utils.coder.StandardCoder;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.util.Properties;
import java.util.TreeMap;
import lombok.Getter;
-import lombok.Setter;
import org.onap.policy.apex.context.ContextAlbum;
import org.onap.policy.apex.context.ContextRuntimeException;
import org.onap.policy.apex.core.engine.context.ApexInternalContext;
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
(new Thread() {
@Override
public void run() {
- assertTrue(engine.handleEvent(event));
- assertEquals(AxEngineState.STOPPED, engine.getState());
+ engine.handleEvent(event);
}
}).start();
await().atLeast(50, TimeUnit.MILLISECONDS).until(() -> engine.getState().equals(AxEngineState.EXECUTING));
(new Thread() {
@Override
public void run() {
- assertTrue(engine.handleEvent(event));
- assertEquals(AxEngineState.STOPPED, engine.getState());
+ engine.handleEvent(event);
}
}).start();
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
// Try get the classes in the bootstrap loader
- try {
- final Class<?> nullclassloader = Class.forName("sun.misc.Launcher");
- if (nullclassloader != null) {
- Method mmethod = nullclassloader.getMethod("getBootstrapClassPath");
- if (mmethod != null) {
- final Object cp = mmethod.invoke(null, (Object[]) null);
- if (cp != null) {
- mmethod = cp.getClass().getMethod("getURLs");
- if (mmethod != null) {
- final URL[] moreurls = (URL[]) (mmethod.invoke(cp, (Object[]) null));
- if (moreurls != null && moreurls.length > 0) {
- if (urls.length == 0) {
- urls = moreurls;
- } else {
- final URL[] result = Arrays.copyOf(urls, urls.length + moreurls.length);
- System.arraycopy(moreurls, 0, result, urls.length, moreurls.length);
- urls = result;
- }
- }
- }
- }
- }
- // end long way!
- }
- } catch (final ClassNotFoundException e) {
- LOGGER.warn("Failed to find default path for JRE libraries", e);
- }
+ urls = getClassesFromBootstrapLoader(urls);
// Iterate over the class path entries
for (final URL url : urls) {
return classNameSet;
}
+ private static URL[] getClassesFromBootstrapLoader(URL[] urls)
+ throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
+ try {
+ final Class<?> nullclassloader = Class.forName("sun.misc.Launcher");
+ if (nullclassloader == null) {
+ return urls;
+ }
+
+ Method mmethod = nullclassloader.getMethod("getBootstrapClassPath");
+ if (mmethod == null) {
+ return urls;
+ }
+
+ final Object cp = mmethod.invoke(null, (Object[]) null);
+ if (cp == null) {
+ return urls;
+ }
+
+ mmethod = cp.getClass().getMethod("getURLs");
+ if (mmethod == null) {
+ return urls;
+ }
+
+ final URL[] moreurls = (URL[]) (mmethod.invoke(cp, (Object[]) null));
+ if (moreurls == null || moreurls.length == 0) {
+ return urls;
+ }
+
+ if (urls.length == 0) {
+ return moreurls;
+ } else {
+ final URL[] result = Arrays.copyOf(urls, urls.length + moreurls.length);
+ System.arraycopy(moreurls, 0, result, urls.length, moreurls.length);
+ return result;
+ }
+ } catch (final ClassNotFoundException e) {
+ LOGGER.warn("Failed to find default path for JRE libraries", e);
+ return urls;
+ }
+ }
+
/**
* Find all classes in directories and JARs in those directories.
*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
while ((messageBlock = messageBlockQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
dataHandler.post(messageBlock);
}
- } catch (final InterruptedException e) {
- // restore the interrupt status
- Thread.currentThread().interrupt();
- LOGGER.debug(RAW_MESSAGE_LISTENING_INTERRUPTED);
- break;
- }
- try {
// Read string messages from the queue and pass it to the data handler
String stringMessage = null;
while ((stringMessage = stringMessageQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
dataHandler.post(stringMessage);
}
- } catch (final InterruptedException e) {
- // restore the interrupt status
- Thread.currentThread().interrupt();
- LOGGER.debug(RAW_MESSAGE_LISTENING_INTERRUPTED);
- break;
- }
- // Wait for new messages
- try {
+ // Wait for new messages
Thread.sleep(QUEUE_POLL_TIMEOUT);
+
} catch (final InterruptedException e) {
// restore the interrupt status
Thread.currentThread().interrupt();
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
public static byte[] serializeObject(final Object object) {
LOGGER.entry(object.getClass().getName());
final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
- ObjectOutputStream oos = null;
- try {
- oos = new ObjectOutputStream(bytesOut);
+ try (ObjectOutputStream oos = new ObjectOutputStream(bytesOut)) {
oos.writeObject(object);
} catch (final IOException e) {
LOGGER.warn("error on object serialization", e);
- } finally {
- flushAndClose(oos, bytesOut);
}
return bytesOut.toByteArray();
}
-
- /**
- * Flush and close an object stream and a byte array output stream.
- *
- * @param oos the object output stream
- * @param bytesOut the byte array output stream
- */
- private static void flushAndClose(final ObjectOutputStream oos, final ByteArrayOutputStream bytesOut) {
- try {
- if (oos != null) {
- oos.flush();
- oos.close();
- }
- if (bytesOut != null) {
- bytesOut.close();
- }
-
- } catch (final IOException e) {
- LOGGER.error("Failed to close the Srialization operation");
- LOGGER.catching(e);
- }
- }
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @param action the action or message type of the message
* @param targetKey the artifact key of the artifact to which this message relates
*/
- public Message(final Action action, final AxArtifactKey targetKey) {
+ protected Message(final Action action, final AxArtifactKey targetKey) {
this(action, targetKey, null);
}
* @param targetKey the artifact key of the artifact to which this message relates
* @param messageData the message data to deliver
*/
- public Message(final Action action, final AxArtifactKey targetKey, final String messageData) {
+ protected Message(final Action action, final AxArtifactKey targetKey, final String messageData) {
this.action = action;
this.targetKey = targetKey;
this.messageData = messageData;
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
private static final String AUTO_LEARN_ALBUM = "AutoLearnAlbum";
private static final String AUTO_LEARN = "AutoLearn";
- private static final Random RAND = new Random(System.currentTimeMillis());
+ /*
+ * This is not used for encryption/security, thus disabling sonar.
+ */
+ private static final Random RAND = new Random(System.currentTimeMillis()); // NOSONAR
+
private static final double WANT = 50.0;
private int size;
/**
* Calculate the return value of the learning.
- *
+ *
* @param diff the difference
* @param random the random value
* @param closestupi closest to i upwards
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
/**
* Default constructor.
*/
- public AxConcept() {
+ protected AxConcept() {
// Default constructor
}
*
* @param copyConcept the concept to copy from
*/
- public AxConcept(final AxConcept copyConcept) {
+ protected AxConcept(final AxConcept copyConcept) {
Assertions.argumentNotNull(copyConcept, "copy concept may not be null");
copyConcept.copyTo(this);
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
/**
* Default constructor.
*/
- public AxKey() {
+ protected AxKey() {
super();
}
*
* @param copyConcept the concept to copy from
*/
- public AxKey(final AxKey copyConcept) {
+ protected AxKey(final AxKey copyConcept) {
super(copyConcept);
}
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
private static final int MAX_DESCRIPTION_LENGTH_8192 = 8192;
private static final int UUID_BYTE_LENGTH_16 = 16;
- private static final Random sharedRandom = new Random();
+ /*
+ * This is not used for encryption/security, thus disabling sonar.
+ */
+ private static final Random sharedRandom = new Random(); // NOSONAR
@EmbeddedId
@XmlElement(name = "key", required = true)
public static UUID generateReproducibleUuid(final String seed) {
Random random = sharedRandom;
if (!StringUtils.isEmpty(seed)) {
- random = new Random(seed.hashCode());
+ /*
+ * This is not used for encryption/security, thus disabling sonar.
+ */
+ random = new Random(seed.hashCode()); // NOSONAR
}
final byte[] array = new byte[UUID_BYTE_LENGTH_16];
random.nextBytes(array);
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
}
final AxArtifactKey artifactKey = (AxArtifactKey) axKey;
- if (!keyInfoMap.containsKey(artifactKey)) {
+
+ keyInfoMap.computeIfAbsent(artifactKey, unusedKey -> {
final AxKeyInfo keyInfo = new AxKeyInfo(artifactKey);
// generate a reproducible UUID
keyInfo.setUuid(AxKeyInfo.generateReproducibleUuid(keyInfo.getId() + keyInfo.getDescription()));
- keyInfoMap.put(artifactKey, keyInfo);
- }
+ return keyInfo;
+ });
}
}
return new AxConceptGetterImpl<>((NavigableMap<AxArtifactKey, AxKeyInfo>) keyInfoMap).getAll(conceptKeyName,
conceptKeyVersion);
}
-}
\ No newline at end of file
+}
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
-import javax.persistence.JoinColumns;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
// @formatter:off
@OneToOne(cascade = CascadeType.ALL)
- @JoinColumns({ @JoinColumn(name = "keyInformationName", referencedColumnName = "name"),
- @JoinColumn(name = "keyInformationVersion", referencedColumnName = "version") })
+ @JoinColumn(name = "keyInformationName", referencedColumnName = "name")
+ @JoinColumn(name = "keyInformationVersion", referencedColumnName = "version")
@XmlElement(name = "keyInformation", required = true)
@XmlJavaTypeAdapter(KeyInfoMarshalFilter.class)
private AxKeyInformation keyInformation;
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
public class DefaultApexDao implements ApexDao {
private static final XLogger LOGGER = XLoggerFactory.getXLogger(DefaultApexDao.class);
+ private static final String COL_LOCALNAME = "local_name";
+ private static final String COL_PARENT_VERSION = "parent_version";
+ private static final String COL_PARENT_NAME = "parent_name";
+ private static final String COL_VERSION = "key_version";
+ private static final String COL_NAME = "key_name";
+
private static final String SELECT_C_FROM = "SELECT c FROM ";
- private static final String AND_C_KEY_LOCAL_NAME = "' AND c.key.localName='";
- private static final String AND_C_KEY_PARENT_KEY_VERSION = "' AND c.key.parentKeyVersion='";
- private static final String C_WHERE_C_KEY_PARENT_KEY_NAME = " c WHERE c.key.parentKeyName='";
- private static final String AND_C_KEY_VERSION = "' AND c.key.version='";
- private static final String C_WHERE_C_KEY_NAME = " c WHERE c.key.name='";
+ private static final String AND_C_KEY_LOCAL_NAME = " AND c.key.localName=:" + COL_LOCALNAME;
+ private static final String AND_C_KEY_PARENT_KEY_VERSION = " AND c.key.parentKeyVersion=:" + COL_PARENT_VERSION;
+ private static final String C_WHERE_C_KEY_PARENT_KEY_NAME = " c WHERE c.key.parentKeyName=:" + COL_PARENT_NAME;
+ private static final String AND_C_KEY_VERSION = " AND c.key.version=:" + COL_VERSION;
+ private static final String C_WHERE_C_KEY_NAME = " c WHERE c.key.name=:" + COL_NAME;
private static final String DELETE_FROM = "DELETE FROM ";
// Entity manager for JPA
final EntityManager mg = getEntityManager();
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();
+ mg.createQuery(DELETE_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_NAME + AND_C_KEY_VERSION, someClass)
+ .setParameter(COL_NAME, key.getName())
+ .setParameter(COL_VERSION, key.getVersion())
+ .executeUpdate();
mg.getTransaction().commit();
} 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();
+ + AND_C_KEY_PARENT_KEY_VERSION
+ + AND_C_KEY_LOCAL_NAME, someClass)
+ .setParameter(COL_PARENT_NAME, key.getParentKeyName())
+ .setParameter(COL_PARENT_VERSION, key.getParentKeyVersion())
+ .setParameter(COL_LOCALNAME, key.getLocalName())
+ .executeUpdate();
mg.getTransaction().commit();
} finally {
mg.close();
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();
+ + AND_C_KEY_VERSION, someClass)
+ .setParameter(COL_NAME, key.getName())
+ .setParameter(COL_VERSION, key.getVersion())
+ .executeUpdate();
}
mg.getTransaction().commit();
} finally {
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();
+ + AND_C_KEY_PARENT_KEY_VERSION + AND_C_KEY_LOCAL_NAME, someClass)
+ .setParameter(COL_PARENT_NAME, key.getParentKeyName())
+ .setParameter(COL_PARENT_VERSION, key.getParentKeyVersion())
+ .setParameter(COL_LOCALNAME, key.getLocalName())
+ .executeUpdate();
}
mg.getTransaction().commit();
} 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)
+ + AND_C_KEY_PARENT_KEY_VERSION, someClass)
+ .setParameter(COL_PARENT_NAME, parentKey.getName())
+ .setParameter(COL_PARENT_VERSION, parentKey.getVersion())
.getResultList();
} finally {
mg.close();
final EntityManager mg = getEntityManager();
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();
+ ret = mg.createQuery(SELECT_C_FROM + someClass.getSimpleName() + C_WHERE_C_KEY_NAME
+ + AND_C_KEY_VERSION, someClass)
+ .setParameter(COL_NAME, key.getName())
+ .setParameter(COL_VERSION, key.getVersion())
+ .getResultList();
} finally {
mg.close();
}
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();
+ + AND_C_KEY_PARENT_KEY_VERSION + AND_C_KEY_LOCAL_NAME, someClass)
+ .setParameter(COL_PARENT_NAME, key.getParentKeyName())
+ .setParameter(COL_PARENT_VERSION, key.getParentKeyVersion())
+ .setParameter(COL_LOCALNAME, key.getLocalName())
+ .getResultList();
} finally {
mg.close();
}
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// (starts with <?xml...>
private static final String XML_INPUT_TYPE_REGEXP = "^\\s*<\\?xml.*>\\s*";
// starts with some kind of bracket [ or (
- private static final String JSON_INPUT_TYPE_REGEXP = "^\\s*[\\(\\{\\[][\\s+\\S]*[\\)\\}\\]]";
+ private static final String JSON_INPUT_TYPE_REGEXP = "^\\s*[\\(\\{\\[][\\s\\S]*[\\)\\}\\]]";
// or {, then has something, then has
// and has a close bracket
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.mockito.runners.MockitoJUnitRunner;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.concepts.AxModel;
+@RunWith(MockitoJUnitRunner.class)
public class ApexModelReaderTest {
@Mock
private Unmarshaller unmarshallerMock;
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.mockito.runners.MockitoJUnitRunner;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.concepts.AxModel;
import org.w3c.dom.Document;
+@RunWith(MockitoJUnitRunner.class)
public class ApexModelWriterTest {
@Mock
private Marshaller marshallerMock;
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.List;
import javax.persistence.AttributeOverride;
-import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
// @formatter:off
@Embedded
- @AttributeOverrides({
- @AttributeOverride(name = "name", column = @Column(name = "itemSchemaName")),
- @AttributeOverride(name = "version", column = @Column(name = "itemSchemaVersion"))
- })
+ @AttributeOverride(name = "name", column = @Column(name = "itemSchemaName"))
+ @AttributeOverride(name = "version", column = @Column(name = "itemSchemaVersion"))
@Column(name = "itemSchema")
@XmlElement(name = "itemSchema", required = true)
private AxArtifactKey itemSchema;
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
-import javax.persistence.JoinColumns;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
// @formatter:off
@OneToOne(cascade = CascadeType.ALL)
- @JoinColumns({
- @JoinColumn(name = "schemasName", referencedColumnName = "name"),
- @JoinColumn(name = "schemasVersion", referencedColumnName = "version")
- })
+ @JoinColumn(name = "schemasName", referencedColumnName = "name")
+ @JoinColumn(name = "schemasVersion", referencedColumnName = "version")
@XmlElement(name = "schemas", required = true)
private AxContextSchemas schemas;
@OneToOne(cascade = CascadeType.ALL)
- @JoinColumns({
- @JoinColumn(name = "albumsName", referencedColumnName = "name"),
- @JoinColumn(name = "albumsVersion", referencedColumnName = "version")
- })
+ @JoinColumn(name = "albumsName", referencedColumnName = "name")
+ @JoinColumn(name = "albumsVersion", referencedColumnName = "version")
@XmlElement(name = "albums", required = true)
private AxContextAlbums albums;
// @formatter:on
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
-import javax.persistence.JoinColumns;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
@XmlElement(required = true)
private AxEngineState state;
- // @formatter:off
- @JoinColumns({
- @JoinColumn(name = "statsParentKeyName", referencedColumnName = "parentKeyName", updatable = false,
- insertable = false),
- @JoinColumn(name = "statsParentKeyVersion", referencedColumnName = "parentKeyVersion", updatable = false,
- insertable = false),
- @JoinColumn(name = "statsParentLocalName ", referencedColumnName = "parentLocalName", updatable = false,
- insertable = false),
- @JoinColumn(name = "statsLocalName", referencedColumnName = "localName", updatable = false,
- insertable = false)})
+ @JoinColumn(name = "statsParentKeyName", referencedColumnName = "parentKeyName", updatable = false,
+ insertable = false)
+ @JoinColumn(name = "statsParentKeyVersion", referencedColumnName = "parentKeyVersion", updatable = false,
+ insertable = false)
+ @JoinColumn(name = "statsParentLocalName ", referencedColumnName = "parentLocalName", updatable = false,
+ insertable = false)
+ @JoinColumn(name = "statsLocalName", referencedColumnName = "localName", updatable = false, insertable = false)
private AxEngineStats stats;
- // @formatter:on
/**
* The Default Constructor creates an engine model with a null key and all its fields undefined.
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
-import javax.persistence.JoinColumns;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
// @formatter:off
@OneToOne(cascade = CascadeType.ALL)
- @JoinColumns({ @JoinColumn(name = "schemasName", referencedColumnName = "name"),
- @JoinColumn(name = "schemasVersion", referencedColumnName = "version") })
+ @JoinColumn(name = "schemasName", referencedColumnName = "name")
+ @JoinColumn(name = "schemasVersion", referencedColumnName = "version")
@XmlElement(name = "schemas", required = true)
private AxContextSchemas schemas;
@OneToOne(cascade = CascadeType.ALL)
- @JoinColumns({ @JoinColumn(name = "eventsName", referencedColumnName = "name"),
- @JoinColumn(name = "eventsVersion", referencedColumnName = "version") })
+ @JoinColumn(name = "eventsName", referencedColumnName = "name")
+ @JoinColumn(name = "eventsVersion", referencedColumnName = "version")
@XmlElement(name = "events", required = true)
private AxEvents events;
// @formatter:on
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.List;
import javax.persistence.AttributeOverride;
-import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
// @formatter:off
@Embedded
- @AttributeOverrides({ @AttributeOverride(name = "name", column = @Column(name = "fieldSchemaName")),
- @AttributeOverride(name = "version", column = @Column(name = "fieldSchemaVersion")) })
+ @AttributeOverride(name = "name", column = @Column(name = "fieldSchemaName"))
+ @AttributeOverride(name = "version", column = @Column(name = "fieldSchemaVersion"))
@Column(name = "fieldSchemaKey")
@XmlElement(required = true)
private AxArtifactKey fieldSchemaKey;
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
-import javax.persistence.JoinColumns;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.xml.bind.Marshaller;
// @formatter:off
@OneToOne(cascade = CascadeType.ALL)
- @JoinColumns({@JoinColumn(name = "policiesName", referencedColumnName = "name"),
- @JoinColumn(name = "policiesVersion", referencedColumnName = "version")})
+ @JoinColumn(name = "policiesName", referencedColumnName = "name")
+ @JoinColumn(name = "policiesVersion", referencedColumnName = "version")
@XmlElement(name = "policies", required = true)
private AxPolicies policies;
@OneToOne(cascade = CascadeType.ALL)
- @JoinColumns({@JoinColumn(name = "tasksName", referencedColumnName = "name"),
- @JoinColumn(name = "tasksVersion", referencedColumnName = "version")})
+ @JoinColumn(name = "tasksName", referencedColumnName = "name")
+ @JoinColumn(name = "tasksVersion", referencedColumnName = "version")
@XmlElement(name = "tasks", required = true)
private AxTasks tasks;
@OneToOne(cascade = CascadeType.ALL)
- @JoinColumns({@JoinColumn(name = "eventsName", referencedColumnName = "name"),
- @JoinColumn(name = "eventsVersion", referencedColumnName = "version")})
+ @JoinColumn(name = "eventsName", referencedColumnName = "name")
+ @JoinColumn(name = "eventsVersion", referencedColumnName = "version")
@XmlElement(name = "events", required = true)
private AxEvents events;
@OneToOne(cascade = CascadeType.ALL)
- @JoinColumns({@JoinColumn(name = "albumsName", referencedColumnName = "name"),
- @JoinColumn(name = "albumsVersion", referencedColumnName = "version")})
+ @JoinColumn(name = "albumsName", referencedColumnName = "name")
+ @JoinColumn(name = "albumsVersion", referencedColumnName = "version")
@XmlElement(name = "albums", required = false)
@XmlJavaTypeAdapter(EmptyAlbumsAdapter.class)
private AxContextAlbums albums;
@OneToOne(cascade = CascadeType.ALL)
- @JoinColumns({@JoinColumn(name = "schemasName", referencedColumnName = "name"),
- @JoinColumn(name = "schemasVersion", referencedColumnName = "version")})
+ @JoinColumn(name = "schemasName", referencedColumnName = "name")
+ @JoinColumn(name = "schemasVersion", referencedColumnName = "version")
@XmlElement(name = "schemas", required = true)
private AxContextSchemas schemas;
// @formatter:on
}
return schemas.compareTo(other.schemas);
}
-}
\ No newline at end of file
+}
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.TreeMap;
import java.util.TreeSet;
import javax.persistence.AttributeOverride;
-import javax.persistence.AttributeOverrides;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
// @formatter:off
@Embedded
- @AttributeOverrides({@AttributeOverride(name = "name", column = @Column(name = "inTriggerName")),
- @AttributeOverride(name = "version", column = @Column(name = "inTriggerVersion"))})
+ @AttributeOverride(name = "name", column = @Column(name = "inTriggerName"))
+ @AttributeOverride(name = "version", column = @Column(name = "inTriggerVersion"))
@Column(name = "trigger")
@XmlElement(required = true)
private AxArtifactKey trigger;
private Map<String, AxStateFinalizerLogic> stateFinalizerLogicMap;
@Embedded
- @AttributeOverrides({@AttributeOverride(name = "name", column = @Column(name = "defaultTaskName")),
- @AttributeOverride(name = "version", column = @Column(name = "defaultTaskVersion"))})
+ @AttributeOverride(name = "name", column = @Column(name = "defaultTaskName"))
+ @AttributeOverride(name = "version", column = @Column(name = "defaultTaskVersion"))
@Column(name = "defaultTask")
@XmlElement(required = true)
private AxArtifactKey defaultTask;
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.List;
import javax.persistence.AttributeOverride;
-import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
// @formatter:off
@Embedded
- @AttributeOverrides({@AttributeOverride(name = "name", column = @Column(name = "outgoingEventName")),
- @AttributeOverride(name = "version", column = @Column(name = "outgoingEventVersion"))})
+ @AttributeOverride(name = "name", column = @Column(name = "outgoingEventName"))
+ @AttributeOverride(name = "version", column = @Column(name = "outgoingEventVersion"))
@Column(name = "outgoingEvent")
@XmlElement(required = true)
private AxArtifactKey outgoingEvent;
@Embedded
- @AttributeOverrides({@AttributeOverride(name = "parentKeyName", column = @Column(name = "nextStateParentKeyName")),
- @AttributeOverride(name = "parentKeyVersion", column = @Column(name = "nextStateParentKeyVersion")),
- @AttributeOverride(name = "parentLocalName", column = @Column(name = "nextStateParentLocalName")),
- @AttributeOverride(name = "localName", column = @Column(name = "nextStateLocalName"))})
+ @AttributeOverride(name = "parentKeyName", column = @Column(name = "nextStateParentKeyName"))
+ @AttributeOverride(name = "parentKeyVersion", column = @Column(name = "nextStateParentKeyVersion"))
+ @AttributeOverride(name = "parentLocalName", column = @Column(name = "nextStateParentLocalName"))
+ @AttributeOverride(name = "localName", column = @Column(name = "nextStateLocalName"))
@Column(name = "nextState")
@XmlElement(required = true)
private AxReferenceKey nextState;
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.List;
import javax.persistence.AttributeOverride;
-import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
// @formatter:off
@Embedded
- @AttributeOverrides({@AttributeOverride(name = "parentKeyName", column = @Column(name = "outputParentKeyName")),
- @AttributeOverride(name = "parentKeyVersion", column = @Column(name = "outputParentKeyVersion")),
- @AttributeOverride(name = "parentLocalName", column = @Column(name = "outputParentLocalName")),
- @AttributeOverride(name = "localName", column = @Column(name = "outputLocalName"))})
+ @AttributeOverride(name = "parentKeyName", column = @Column(name = "outputParentKeyName"))
+ @AttributeOverride(name = "parentKeyVersion", column = @Column(name = "outputParentKeyVersion"))
+ @AttributeOverride(name = "parentLocalName", column = @Column(name = "outputParentLocalName"))
+ @AttributeOverride(name = "localName", column = @Column(name = "outputLocalName"))
@Column(name = "output")
@XmlElement(required = true)
private AxReferenceKey output;
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.apex.model.policymodel.concepts;
import java.util.ArrayList;
+import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
+import lombok.EqualsAndHashCode;
import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
import org.onap.policy.common.utils.validation.Assertions;
* <p>Validation checks for recursive state use, in other words validation forbids the use of a given
* state more than once in a state tree.
*/
+@EqualsAndHashCode
public class AxStateTree implements Comparable<AxStateTree> {
private final AxState thisState;
private final Set<AxStateTree> nextStates;
}
final AxStateTree other = otherObj;
- if (!thisState.equals(other.thisState)) {
- return thisState.compareTo(other.thisState);
+ int result = thisState.compareTo(other.thisState);
+ if (result != 0) {
+ return result;
}
- if (!nextStates.equals(other.nextStates)) {
- return (nextStates.hashCode() - other.nextStates.hashCode());
+
+ result = Integer.compare(nextStates.size(), other.nextStates.size());
+ if (result != 0) {
+ return result;
+ }
+
+ Iterator<AxStateTree> iter1 = nextStates.iterator();
+ Iterator<AxStateTree> iter2 = other.nextStates.iterator();
+
+ while (iter1.hasNext()) {
+ result = iter1.next().compareTo(iter2.next());
+ if (result != 0) {
+ return result;
+ }
}
+
return 0;
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
-public abstract class CollectionUtils {
+public class CollectionUtils {
/**
* Private constructor used to prevent sub class instantiation.
*/
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
-public abstract class TreeMapUtils {
+public class TreeMapUtils {
/**
* This class is a utility class that can't be instantiated.
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import javax.ws.rs.core.Response;
import org.junit.After;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.mockito.runners.MockitoJUnitRunner;
import org.onap.policy.apex.service.engine.event.ApexEventException;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
* This class tests the ApexRestClientConusmer class.
*
*/
+@RunWith(MockitoJUnitRunner.class)
public class ApexRestClientConusmerTest {
private final PrintStream stdout = System.out;
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.mockito.runners.MockitoJUnitRunner;
import org.onap.policy.apex.service.engine.event.ApexEventConsumer;
import org.onap.policy.apex.service.engine.event.ApexEventException;
import org.onap.policy.apex.service.engine.event.SynchronousEventCache;
* Test the ApexRestClientProducer class.
*
*/
+@RunWith(MockitoJUnitRunner.class)
public class ApexRestClientProducerTest {
@Mock
private Client httpClientMock;
.hasMessageContaining("send of event to URL \"http://some.place.that.does.not/exist\" using HTTP \"POST\" "
+ "failed with status code 400");
}
-}
\ No newline at end of file
+}
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
* Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Test
public void testRestRequestorCarrierTechnologyParametersBadList() {
- ApexCommandLineArguments arguments = new ApexCommandLineArguments();
- arguments.setToscaPolicyFilePath("src/test/resources/prodcons/RESTRequestorWithHTTPHeaderBadList.json");
- arguments.setRelativeFileRoot(".");
-
- assertThatThrownBy(() -> {
- new ApexParameterHandler().getParameters(arguments);
- }).hasMessageContaining("HTTP header array entry is null\n parameter");
+ verifyException("src/test/resources/prodcons/RESTRequestorWithHTTPHeaderBadList.json",
+ "HTTP header array entry is null\n parameter");
}
@Test
public void testRestRequestorCarrierTechnologyParametersNotKvPairs() {
- ApexCommandLineArguments arguments = new ApexCommandLineArguments();
- arguments.setToscaPolicyFilePath("src/test/resources/prodcons/RESTRequestorWithHTTPHeaderNotKvPairs.json");
- arguments.setRelativeFileRoot(".");
-
- assertThatThrownBy(() -> {
- new ApexParameterHandler().getParameters(arguments);
- }).hasMessageContaining("HTTP header array entries must have one key and one value: [aaa, bbb, ccc]");
+ verifyException("src/test/resources/prodcons/RESTRequestorWithHTTPHeaderNotKvPairs.json",
+ "HTTP header array entries must have one key and one value: [aaa, bbb, ccc]");
}
@Test
public void testRestRequestorCarrierTechnologyParametersNulls() {
+ verifyException("src/test/resources/prodcons/RESTRequestorWithHTTPHeaderNulls.json",
+ "HTTP header key is null or blank: [null, bbb]");
+ }
+
+ private void verifyException(String fileName, String expectedMsg) {
ApexCommandLineArguments arguments = new ApexCommandLineArguments();
- arguments.setToscaPolicyFilePath("src/test/resources/prodcons/RESTRequestorWithHTTPHeaderNulls.json");
+ arguments.setToscaPolicyFilePath(fileName);
arguments.setRelativeFileRoot(".");
- assertThatThrownBy(() -> {
- new ApexParameterHandler().getParameters(arguments);
- }).hasMessageContaining("HTTP header key is null or blank: [null, bbb]");
+ assertThatThrownBy(() -> new ApexParameterHandler().getParameters(arguments)).describedAs(fileName)
+ .hasMessageContaining(expectedMsg);
}
@Test
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
@Test
public void testGarbageTextLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream("hello there".getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertNull(textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyNull("testGarbageTextLine", "hello there");
}
/**
*/
@Test
public void testPartialEventLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "1469781869268</TestTimestamp></MainTag>".getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertNull(textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyNull("testPartialEventLine", "1469781869268</TestTimestamp></MainTag>");
}
/**
*/
@Test
public void testFullEventLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>".getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>", textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyLine("testFullEventLine", "<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>",
+ "<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>");
}
/**
*/
@Test
public void testFullEventGarbageBeforeLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "Garbage<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>".getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertTrue(textBlock.isEndOfText());
+ verifyEnd("testFullEventGarbageBeforeLine",
+ "Garbage<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>");
}
/**
*/
@Test
public void testFullEventGarbageBeforeAfterLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "Garbage<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>Rubbish"
- .getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertTrue(textBlock.isEndOfText());
+ verifyEnd("testFullEventGarbageBeforeAfterLine",
+ "Garbage<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>Rubbish");
}
/**
*/
@Test
public void testFullEventGarbageAfterLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>Rubbish".getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>Rubbish",
- textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyLine("testFullEventGarbageAfterLine",
+ "<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>Rubbish",
+ "<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>Rubbish");
}
/**
*/
@Test
public void testGarbageTextMultiLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream("hello\nthere".getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertTrue(textBlock.isEndOfText());
+ verifyEnd("testGarbageTextMultiLine", "hello\nthere");
}
/**
*/
@Test
public void testPartialEventMultiLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "1469781869268\n</TestTimestamp>\n</MainTag>".getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertTrue(textBlock.isEndOfText());
+ verifyEnd("testPartialEventMultiLine", "1469781869268\n</TestTimestamp>\n</MainTag>");
}
/**
*/
@Test
public void testFullEventMultiLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\n\n".getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>",
- textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyLine("testFullEventMultiLine",
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\n\n",
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>");
}
/**
*/
@Test
public void testFullEventGarbageBeforeMultiLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "Garbage\n<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\n\n"
- .getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>",
- textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyLine("testFullEventGarbageBeforeMultiLine",
+ "Garbage\n<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\n\n",
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>");
}
/**
public void testFullEventGarbageBeforeAfterMultiLine() throws IOException {
String garbageString = "Garbage\n<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>"
+ "\n</MainTag>\nRubbish\n\n";
- final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish",
- textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyLine("testFullEventsGarbageAfterLine", garbageString,
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish");
}
/**
*/
@Test
public void testFullEventGarbageAfterMultiLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish"
- .getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish",
- textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyLine("testFullEventGarbageAfterMultiLine",
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish",
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish");
}
/**
*/
@Test
public void testPartialEventsLine() throws IOException {
- String garbageString = "1469781869268</TestTimestamp></MainTag><?xml><MainTag>"
- + "<TestTimestamp>1469781869268</TestTimestamp>";
- final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertTrue(textBlock.isEndOfText());
+ verifyEnd("testPartialEventsLine", "1469781869268</TestTimestamp></MainTag><?xml><MainTag>"
+ + "<TestTimestamp>1469781869268</TestTimestamp>");
}
/**
*/
@Test
public void testFullEventsGarbageBeforeLine() throws IOException {
- String garbageString = "Garbage<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>"
- + "<?xml><MainTag><TestTimestamp>";
- final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertTrue(textBlock.isEndOfText());
+ verifyEnd("testPartialEventsLine",
+ "Garbage<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp></MainTag>"
+ + "<?xml><MainTag><TestTimestamp>");
}
/**
*/
@Test
public void testFullEventsGarbageBeforeAfterLine() throws IOException {
- String garbageString = "Garbage<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp>"
- + "</MainTag>Rubbish<?xml><MainTag><TestTimestamp>\nRefuse";
- final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertTrue(textBlock.isEndOfText());
+ verifyEnd("testFullEventGarbageBeforeLine", "Garbage<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp>"
+ + "</MainTag>Rubbish<?xml><MainTag><TestTimestamp>\nRefuse");
}
/**
public void testFullEventsGarbageAfterLine() throws IOException {
String garbageString = "<?xml><MainTag><TestTimestamp>1469781869268</TestTimestamp>"
+ "</MainTag>Rubbish<?xml><MainTag><TestTimestamp>Refuse";
- final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals(textBlock.getText(), garbageString);
- assertTrue(textBlock.isEndOfText());
+ verifyLine("testFullEventsGarbageAfterLine", garbageString, garbageString);
}
/**
*/
@Test
public void testPartialEventsMultiLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "1469781869268\n</TestTimestamp>\n</MainTag>\n<?xml>\n<MainTag>\n<TestTimestamp>".getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>", textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyLine("testPartialEventsMultiLine",
+ "1469781869268\n</TestTimestamp>\n</MainTag>\n<?xml>\n<MainTag>\n<TestTimestamp>",
+ "<?xml>\n<MainTag>\n<TestTimestamp>");
}
/**
public void testFullEventsMultiLine() throws IOException {
String garbageString = "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n"
+ "</MainTag>\n<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\n";
- final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>",
- textBlock.getText());
- assertFalse(textBlock.isEndOfText());
- textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>",
- textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyLines("testFullEventsMultiLine", garbageString,
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>",
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>");
}
/**
public void testFullEventsGarbageBeforeMultiLine() throws IOException {
String garbageString = "Garbage\n<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n"
+ "</MainTag>\n\n<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\n";
- final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes());
-
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>",
- textBlock.getText());
- assertFalse(textBlock.isEndOfText());
- textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>",
- textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyLines("testFullEventsGarbageBeforeMultiLine", garbageString,
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>",
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>");
}
/**
String garbageString = "Garbage\n<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n"
+ "</MainTag>\nRubbish\n<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n"
+ "</MainTag>\nRefuse\n";
- final InputStream xmlInputStream = new ByteArrayInputStream(garbageString.getBytes());
- final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
- xmlTaggedReader.init(xmlInputStream);
-
- TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish",
- textBlock.getText());
- assertFalse(textBlock.isEndOfText());
-
- textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRefuse",
- textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyLines("testFullEventsGarbageBeforeAfterMultiLine", garbageString,
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish",
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRefuse");
}
/**
*/
@Test
public void testFullEventsGarbageAfterMultiLine() throws IOException {
- final InputStream xmlInputStream = new ByteArrayInputStream(
- "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish"
- .getBytes());
+ verifyLine("testFullEventsGarbageAfterMultiLine",
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish",
+ "<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish");
+ }
+
+ private void verifyNull(String testName, String xml) throws IOException {
+ final InputStream xmlInputStream = new ByteArrayInputStream(xml.getBytes());
+
+ final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
+ xmlTaggedReader.init(xmlInputStream);
+
+ final TextBlock textBlock = xmlTaggedReader.readTextBlock();
+ assertNull(testName, textBlock.getText());
+ assertTrue(testName, textBlock.isEndOfText());
+ }
+
+ private void verifyLine(String testName, String xml, String expected) throws IOException {
+ final InputStream xmlInputStream = new ByteArrayInputStream(xml.getBytes());
+
+ final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
+ xmlTaggedReader.init(xmlInputStream);
+
+ final TextBlock textBlock = xmlTaggedReader.readTextBlock();
+ assertEquals(testName, expected, textBlock.getText());
+ assertTrue(testName, textBlock.isEndOfText());
+ }
+
+ private void verifyLines(String testName, String xml, String expected, String expected2) throws IOException {
+ final InputStream xmlInputStream = new ByteArrayInputStream(xml.getBytes());
+
+ final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
+ xmlTaggedReader.init(xmlInputStream);
+
+ TextBlock textBlock = xmlTaggedReader.readTextBlock();
+ assertEquals(testName, expected, textBlock.getText());
+ assertFalse(testName, textBlock.isEndOfText());
+
+ textBlock = xmlTaggedReader.readTextBlock();
+ assertEquals(testName, expected2, textBlock.getText());
+ assertTrue(testName, textBlock.isEndOfText());
+ }
+
+ private void verifyEnd(String testName, String xml) throws IOException {
+ final InputStream xmlInputStream = new ByteArrayInputStream(xml.getBytes());
final HeaderDelimitedTextBlockReader xmlTaggedReader = new HeaderDelimitedTextBlockReader("<?xml", null, true);
xmlTaggedReader.init(xmlInputStream);
final TextBlock textBlock = xmlTaggedReader.readTextBlock();
- assertEquals("<?xml>\n<MainTag>\n<TestTimestamp>1469781869268</TestTimestamp>\n</MainTag>\nRubbish",
- textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ assertTrue(testName, textBlock.isEndOfText());
}
}
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.apex.plugins.event.protocol.yaml;
-import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
task.getTaskLogic().setLogic("var x = 5;");
jte.prepare();
+ Properties props = new Properties();
assertThatThrownBy(() -> {
- jte.execute(-1, new Properties(), null);
+ jte.execute(-1, props, null);
}).isInstanceOf(NullPointerException.class);
jte.cleanUp();
assertThatThrownBy(() -> {
jte.prepare();
- jte.execute(-1, new Properties(), incomingParameters);
+ jte.execute(-1, props, incomingParameters);
}).hasMessage("execute-post: task logic execution failure on task \"TestTask\" in model NULL:0.0.0");
jte.cleanUp();
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
final String errorMessage = APEX_FILE_CONSUMER_PREAMBLE + consumerName
+ "\" failed to open file for reading: \"" + fileCarrierTechnologyParameters.getFileName()
+ "\"";
- LOGGER.warn(errorMessage, e);
throw new ApexEventException(errorMessage, e);
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
/**
* The default carrier technology parameter class that may be specialized by carrier technology plugins that require
* plugin specific parameters.
- *
+ *
* <p>The following parameters are defined: <ol> <li>label: The label of the carrier technology.
* <li>eventProducerPluginClass: The name of the plugin class that will be used by Apex to produce and emit output
* events for this carrier technology <li>eventConsumerPluginClass: The name of the plugin class that will be used by
* Constructor to create a carrier technology parameters instance with the name of a sub class of this class and
* register the instance with the parameter service.
*/
- public CarrierTechnologyParameters() {
+ protected CarrierTechnologyParameters() {
super();
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
* Constructor to create an event protocol parameters instance with the name of a sub class of this class and
* register the instance with the parameter service.
*/
- public EventProtocolParameters() {
+ protected EventProtocolParameters() {
super();
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
/**
* Constructor to create an event protocol parameters instance with the name of a sub class of this class.
*/
- public EventProtocolTextCharDelimitedParameters() {
+ protected EventProtocolTextCharDelimitedParameters() {
super();
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
/**
* Constructor to create an event protocol parameters instance with the name of a sub class of this class.
*/
- public EventProtocolTextTokenDelimitedParameters() {
+ protected EventProtocolTextTokenDelimitedParameters() {
super();
}
/**
* Check if there must be a delimiter at the start of the first text block.
- *
+ *
* @return true if there must be a delimiter at the start of the text block
*/
public boolean isDelimiterAtStart() {
/**
* Sets if there has to be a delimiter at the start of the first text block.
- *
+ *
* @param delimiterAtStart
* true if there must be a delimiter at the start of the text block
*/
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
@Test
public void testGarbageText() throws IOException {
- final InputStream jsonInputStream = new ByteArrayInputStream("hello there".getBytes());
-
- final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}');
- taggedReader.init(jsonInputStream);
-
- final TextBlock textBlock = taggedReader.readTextBlock();
- assertNull(textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyNoEvent("testGarbageText", "hello there");
}
@Test
public void testPartialEvent() throws IOException {
- final InputStream jsonInputStream = new ByteArrayInputStream("\"TestTimestamp\": 1469781869268}".getBytes());
-
- final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}');
- taggedReader.init(jsonInputStream);
-
- final TextBlock textBlock = taggedReader.readTextBlock();
- assertNull(textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyNoEvent("testGarbageText", "\"TestTimestamp\": 1469781869268}");
}
@Test
public void testFullEvent() throws IOException {
- final InputStream jsonInputStream = new ByteArrayInputStream("{TestTimestamp\": 1469781869268}".getBytes());
-
- final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}');
- taggedReader.init(jsonInputStream);
-
- TextBlock textBlock = taggedReader.readTextBlock();
- assertEquals("{TestTimestamp\": 1469781869268}", textBlock.getText());
-
- textBlock = taggedReader.readTextBlock();
- assertNull(textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyMulti("testFullEvent", "{TestTimestamp\": 1469781869268}", "{TestTimestamp\": 1469781869268}");
}
@Test
public void testFullEventGarbageBefore() throws IOException {
- final InputStream jsonInputStream =
- new ByteArrayInputStream("Garbage{TestTimestamp\": 1469781869268}".getBytes());
-
- final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}');
- taggedReader.init(jsonInputStream);
-
- TextBlock textBlock = taggedReader.readTextBlock();
- assertEquals("{TestTimestamp\": 1469781869268}", textBlock.getText());
- assertFalse(textBlock.isEndOfText());
-
- textBlock = taggedReader.readTextBlock();
- assertNull(textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ verifyMulti("testFullEventGarbageBefore", "Garbage{TestTimestamp\": 1469781869268}",
+ "{TestTimestamp\": 1469781869268}");
}
@Test
public void testFullEventGarbageBeforeAfter() throws IOException {
- final InputStream jsonInputStream =
- new ByteArrayInputStream("Garbage{TestTimestamp\": 1469781869268}Rubbish".getBytes());
+ verifyMulti("testFullEventGarbageBeforeAfter", "Garbage{TestTimestamp\": 1469781869268}Rubbish",
+ "{TestTimestamp\": 1469781869268}");
+ }
+
+ @Test
+ public void testFullEventGarbageAfter() throws IOException {
+ verifyMulti("testFullEventGarbageAfter", "{TestTimestamp\": 1469781869268}Rubbish",
+ "{TestTimestamp\": 1469781869268}");
+ }
+
+ private void verifyNoEvent(String testName, String input) throws IOException {
+ final InputStream jsonInputStream = new ByteArrayInputStream(input.getBytes());
final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}');
taggedReader.init(jsonInputStream);
- TextBlock textBlock = taggedReader.readTextBlock();
- assertEquals("{TestTimestamp\": 1469781869268}", textBlock.getText());
- assertFalse(textBlock.isEndOfText());
-
- textBlock = taggedReader.readTextBlock();
- assertNull(textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ final TextBlock textBlock = taggedReader.readTextBlock();
+ assertNull(testName, textBlock.getText());
+ assertTrue(testName, textBlock.isEndOfText());
}
- @Test
- public void testFullEventGarbageAfter() throws IOException {
- final InputStream jsonInputStream =
- new ByteArrayInputStream("{TestTimestamp\": 1469781869268}Rubbish".getBytes());
+ private void verifyMulti(String testName, String input, String expected) throws IOException {
+ final InputStream jsonInputStream = new ByteArrayInputStream(input.getBytes());
final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}');
taggedReader.init(jsonInputStream);
TextBlock textBlock = taggedReader.readTextBlock();
- assertEquals("{TestTimestamp\": 1469781869268}", textBlock.getText());
- assertFalse(textBlock.isEndOfText());
+ assertEquals(testName, expected, textBlock.getText());
+ assertFalse(testName, textBlock.isEndOfText());
textBlock = taggedReader.readTextBlock();
- assertNull(textBlock.getText());
- assertTrue(textBlock.isEndOfText());
+ assertNull(testName, textBlock.getText());
+ assertTrue(testName, textBlock.isEndOfText());
}
}
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
* Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Test
public void testSyncGoodSyncGoodTimeoutProducer() throws ParameterException {
- final String[] args = {"-p", "src/test/resources/parameters/syncGoodParamsProducerTimeout.json"};
- final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
-
- final ApexParameters parameters = new ApexParameterHandler().getParameters(arguments);
- assertEquals(12345, parameters.getEventInputParameters().get("SyncConsumer0")
- .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
- assertEquals(1, parameters.getEventInputParameters().get("SyncConsumer1")
- .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
- assertEquals(12345, parameters.getEventOutputParameters().get("SyncProducer0")
- .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
- assertEquals(1, parameters.getEventOutputParameters().get("SyncProducer1")
- .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
-
+ verifySyncGoodSyncGoodTimeout("src/test/resources/parameters/syncGoodParamsProducerTimeout.json");
}
@Test
public void testSyncGoodSyncGoodTimeoutConsumer() throws ParameterException {
- final String[] args = {"-p", "src/test/resources/parameters/syncGoodParamsConsumerTimeout.json"};
- final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
-
- final ApexParameters parameters = new ApexParameterHandler().getParameters(arguments);
- assertEquals(12345, parameters.getEventInputParameters().get("SyncConsumer0")
- .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
- assertEquals(1, parameters.getEventInputParameters().get("SyncConsumer1")
- .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
- assertEquals(12345, parameters.getEventOutputParameters().get("SyncProducer0")
- .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
- assertEquals(1, parameters.getEventOutputParameters().get("SyncProducer1")
- .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
-
+ verifySyncGoodSyncGoodTimeout("src/test/resources/parameters/syncGoodParamsConsumerTimeout.json");
}
@Test
public void testSyncGoodSyncGoodTimeoutBoth() throws ParameterException {
- final String[] args = {"-p", "src/test/resources/parameters/syncGoodParamsBothTimeout.json"};
+ verifySyncGoodSyncGoodTimeout("src/test/resources/parameters/syncGoodParamsBothTimeout.json");
+ }
+
+ private void verifySyncGoodSyncGoodTimeout(String fileName) throws ParameterException {
+ final String[] args = {"-p", fileName};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
final ApexParameters parameters = new ApexParameterHandler().getParameters(arguments);
- assertEquals(12345, parameters.getEventInputParameters().get("SyncConsumer0")
+ assertEquals(fileName, 12345, parameters.getEventInputParameters().get("SyncConsumer0")
.getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
- assertEquals(1, parameters.getEventInputParameters().get("SyncConsumer1")
+ assertEquals(fileName, 1, parameters.getEventInputParameters().get("SyncConsumer1")
.getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
- assertEquals(12345, parameters.getEventOutputParameters().get("SyncProducer0")
+ assertEquals(fileName, 12345, parameters.getEventOutputParameters().get("SyncProducer0")
.getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
- assertEquals(1, parameters.getEventOutputParameters().get("SyncProducer1")
+ assertEquals(fileName, 1, parameters.getEventOutputParameters().get("SyncProducer1")
.getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS));
-
}
@Test
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 Nordix Foundation.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
() -> Registry.register(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER,
new PdpStatusPublisher(topicSinks,
apexStarterParameterGroup.getPdpStatusParameters().getTimeIntervalMs())),
- () -> stopAndRemovePdpStatusPublisher())
+ this::stopAndRemovePdpStatusPublisher)
.addAction("Register pdp update listener",
() -> msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(), pdpUpdateListener),
() -> msgDispatcher.unregister(PdpMessageType.PDP_UPDATE.name()))
() -> msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(), pdpStateChangeListener),
() -> msgDispatcher.unregister(PdpMessageType.PDP_STATE_CHANGE.name()))
.addAction("Message Dispatcher",
- () -> registerMsgDispatcher(),
- () -> unregisterMsgDispatcher())
+ this::registerMsgDispatcher,
+ this::unregisterMsgDispatcher)
.addAction("Create REST server",
() -> restServer =
new ApexStarterRestServer(apexStarterParameterGroup.getRestServerParameters()),
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
public class DefaultTaskLogic {
private static final int BOUND_FOR_RANDOM_INT = 4;
- private static final Random rand = new Random();
+
+ /*
+ * This is not used for encryption/security, thus disabling sonar.
+ */
+ private static final Random rand = new Random(); // NOSONAR
/**
* Gets the event.
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
package org.onap.policy.apex.testsuites.integration.executor.handling;
+import static org.assertj.core.api.Assertions.assertThatCode;
+
import org.junit.Test;
import org.onap.policy.apex.model.basicmodel.test.TestApexModel;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
public class TestApexSamplePolicyCreateModelFiles {
@Test
- public void testModelWriteReadJava() throws Exception {
- final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("JAVA");
- final TestApexModel<AxPolicyModel> testApexPolicyModel =
- new TestApexModel<AxPolicyModel>(AxPolicyModel.class, apexPolicyModelCreator);
- testApexPolicyModel.testApexModelWriteReadXml();
- testApexPolicyModel.testApexModelWriteReadJson();
- }
-
- @Test
- public void testModelWriteReadJavascript() throws Exception {
- final TestApexSamplePolicyModelCreator apexPolicyModelCreator =
- new TestApexSamplePolicyModelCreator("JAVASCRIPT");
- final TestApexModel<AxPolicyModel> testApexPolicyModel =
- new TestApexModel<AxPolicyModel>(AxPolicyModel.class, apexPolicyModelCreator);
- testApexPolicyModel.testApexModelWriteReadXml();
- testApexPolicyModel.testApexModelWriteReadJson();
- }
-
- @Test
- public void testModelWriteReadJRuby() throws Exception {
- final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("JRUBY");
- final TestApexModel<AxPolicyModel> testApexPolicyModel =
- new TestApexModel<AxPolicyModel>(AxPolicyModel.class, apexPolicyModelCreator);
- testApexPolicyModel.testApexModelWriteReadXml();
- testApexPolicyModel.testApexModelWriteReadJson();
- }
-
- @Test
- public void testModelWriteReadJython() throws Exception {
- final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("JYTHON");
- final TestApexModel<AxPolicyModel> testApexPolicyModel =
- new TestApexModel<AxPolicyModel>(AxPolicyModel.class, apexPolicyModelCreator);
- testApexPolicyModel.testApexModelWriteReadXml();
- testApexPolicyModel.testApexModelWriteReadJson();
- }
-
- @Test
- public void testModelWriteReadMvel() throws Exception {
- final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator("MVEL");
- final TestApexModel<AxPolicyModel> testApexPolicyModel =
- new TestApexModel<AxPolicyModel>(AxPolicyModel.class, apexPolicyModelCreator);
- testApexPolicyModel.testApexModelWriteReadXml();
- testApexPolicyModel.testApexModelWriteReadJson();
+ public void testModelWriteRead() throws Exception {
+ String[] types = {"JAVA", "JAVASCRIPT", "JRUBY", "JYTHON", "MVEL"};
+ for (String type: types) {
+ final TestApexSamplePolicyModelCreator apexPolicyModelCreator = new TestApexSamplePolicyModelCreator(type);
+ final TestApexModel<AxPolicyModel> testApexPolicyModel =
+ new TestApexModel<AxPolicyModel>(AxPolicyModel.class, apexPolicyModelCreator);
+ assertThatCode(() -> testApexPolicyModel.testApexModelWriteReadXml()).doesNotThrowAnyException();
+ assertThatCode(() -> testApexPolicyModel.testApexModelWriteReadJson()).doesNotThrowAnyException();
+ }
}
}
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @throws Exception the exception
*/
public static void main(final String[] args) {
- LOGGER.info("Starting event generator with arguments: " + Arrays.toString(args));
+ if (LOGGER.isInfoEnabled()) {
+ LOGGER.info("Starting event generator with arguments: {}", Arrays.toString(args));
+ }
EventGeneratorParameterHandler parameterHandler = new EventGeneratorParameterHandler();
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* Constructor, assign default values to fields.
*/
public InputEvent() {
- final Random rand = new Random();
+ /*
+ * This is not used for encryption/security, thus disabling sonar.
+ */
+ final Random rand = new Random(); // NOSONAR
+
testMatchCase = rand.nextInt(4);
name = "Event0" + rand.nextInt(2) + "00";
testTemperature = rand.nextDouble() * 1000;
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.apex.tools.model.generator.model2cli;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertTrue;
@Test
public void testModel2CliBadOptions() {
- final String[] cliArgs = {"-zabbu"};
-
- final String outputString = runModel2Cli(cliArgs);
-
- assertTrue(outputString.contains("usage: gen-model2cli"));
+ assertThat(runModel2Cli(new String[] {"-zabbu"})).contains("usage: gen-model2cli");
}
@Test
public void testModel2CliHelp() {
- final String[] cliArgs = {"-h"};
-
- final String outputString = runModel2Cli(cliArgs);
-
- assertTrue(outputString.contains("usage: gen-model2cli"));
+ assertThat(runModel2Cli(new String[] {"-h"})).contains("usage: gen-model2cli");
}
@Test
public void testModel2CliVersion() {
- final String[] cliArgs = {"-v"};
-
- final String outputString = runModel2Cli(cliArgs);
-
- assertTrue(outputString.contains("gen-model2cli"));
+ assertThat(runModel2Cli(new String[] {"-v"})).contains("gen-model2cli").doesNotContain("usage:");
}
@Test
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters;
import org.onap.policy.apex.context.parameters.ContextParameterConstants;
import org.onap.policy.apex.context.parameters.SchemaParameters;
+import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.common.parameters.ParameterService;
import org.stringtemplate.v4.STGroupFile;
}
@Test
- public void testEventSchemaStimuli() {
+ public void testEventSchemaStimuli() throws ApexException {
modelFile = "src/test/resources/SmallModel.json";
- type = "stimuli";
- Model2JsonEventSchema app = new Model2JsonEventSchema(modelFile, type, APP_NAME);
- assertThatCode(() -> {
- int ret = app.runApp();
- assertEquals(0, ret);
- }).doesNotThrowAnyException();
- }
-
- @Test
- public void testEventSchemaResponse() {
- modelFile = "src/test/resources/SmallModel.json";
- type = "response";
- Model2JsonEventSchema app = new Model2JsonEventSchema(modelFile, type, APP_NAME);
- assertThatCode(() -> {
- int ret = app.runApp();
- assertEquals(0, ret);
- }).doesNotThrowAnyException();
- }
- @Test
- public void testEventSchemaInternal() {
- modelFile = "src/test/resources/SmallModel.json";
- type = "internal";
- Model2JsonEventSchema app = new Model2JsonEventSchema(modelFile, type, APP_NAME);
- assertThatCode(() -> {
- int ret = app.runApp();
- assertEquals(0, ret);
- }).doesNotThrowAnyException();
+ String[] types = {"stimuli", "response", "internal"};
+ for (String type2: types) {
+ type = type2;
+ Model2JsonEventSchema app = new Model2JsonEventSchema(modelFile, type, APP_NAME);
+ assertEquals(type, 0, app.runApp());
+ }
}
@Test
ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
ModelService.clear();
}
-}
\ No newline at end of file
+}
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.apex.tools.model.generator.model2event;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.Assert.assertTrue;
@Test
public void testModel2EventBadOptions() {
- final String[] EventArgs =
- { "-zabbu" };
-
- final String outputString = runModel2Event(EventArgs);
-
- assertTrue(outputString.contains("usage: gen-model2event"));
+ assertThat(runModel2Event(new String[] {"-zabbu"})).contains("usage: gen-model2event");
}
@Test
public void testModel2EventHelp() {
- final String[] EventArgs =
- { "-h" };
-
- final String outputString = runModel2Event(EventArgs);
-
- assertTrue(outputString.contains("usage: gen-model2event"));
+ assertThat(runModel2Event(new String[] {"-h"})).contains("usage: gen-model2event");
}
@Test
public void testModel2EventVersion() {
- final String[] EventArgs =
- { "-v" };
-
- final String outputString = runModel2Event(EventArgs);
-
- assertTrue(outputString.contains("gen-model2event"));
+ assertThat(runModel2Event(new String[] {"-v"})).contains("gen-model2event").doesNotContain("usage:");
}
@Test
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
/** Application name, used as prompt. */
private final String appName;
-
+
// Output and error streams
private PrintStream outStream;
private PrintStream errStream;
};
thread.setName("ClientThread");
thread.start();
-
+
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- String event = "";
+ StringBuilder event = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
if ("exit".equals(line)) {
final String current = line.trim();
if ("".equals(current)) {
- this.send(event);
- event = "";
+ this.send(event.toString());
+ event = new StringBuilder();
} else {
- event += current;
+ event.append(current);
}
}
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.apex.tools.simple.wsclient;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@Test
public void testWsClientNoOptions() {
- final String[] EventArgs = new String[]
- {};
-
- final String outputString = runWsClient(EventArgs);
-
- assertTrue(outputString.contains("ws-client: starting simple event echo"));
+ assertThat(runWsClient(new String[] {})).contains("ws-client: starting simple event echo");
}
@Test
public void testWsClientBadOptions() {
- final String[] EventArgs =
- { "-zabbu" };
-
- final String outputString = runWsClient(EventArgs);
-
- assertTrue(outputString.contains("usage: ws-client"));
+ assertThat(runWsClient(new String[] {"-zabbu"})).contains("usage: ws-client");
}
@Test
public void testWsClientHelp() {
- final String[] EventArgs =
- { "-h" };
-
- final String outputString = runWsClient(EventArgs);
-
- assertTrue(outputString.contains("usage: ws-client"));
+ assertThat(runWsClient(new String[] {"-h"})).contains("usage: ws-client");
}
@Test
public void testWsClientVersion() {
- final String[] EventArgs =
- { "-v" };
-
- final String outputString = runWsClient(EventArgs);
-
- assertTrue(outputString.contains("ws-client"));
+ assertThat(runWsClient(new String[] {"-v"})).contains("ws-client").doesNotContain("usage:");
}
@Test
public void testWsClientNoServerArg() {
- final String[] EventArgs =
- { "-s" };
-
- final String outputString = runWsClient(EventArgs);
-
- assertTrue(outputString.contains("ws-client"));
+ assertThat(runWsClient(new String[] {"-s"})).contains("ws-client");
}
@Test
public void testWsClientNoPortArg() {
- final String[] EventArgs =
- { "-p" };
-
- final String outputString = runWsClient(EventArgs);
-
- assertTrue(outputString.contains("ws-client"));
+ assertThat(runWsClient(new String[] {"-p"})).contains("usage: ws-client");
}
@Test
public void testWsClientBadPortArg() {
- final String[] EventArgs =
- { "-p", "hello" };
-
- final String outputString = runWsClient(EventArgs);
-
- assertTrue(outputString.contains("ws-client"));
+ assertThat(runWsClient(new String[] {"-p", "hello"})).contains("ws-client");
}
@Test
public void testWsClientBadServerArg() {
- final String[] EventArgs =
- { "-s", "asdsadadasd:asdasdsadasd@@" };
-
- final String outputString = runWsClient(EventArgs);
-
- assertTrue(outputString.contains("ws-client"));
+ assertThat(runWsClient(new String[] {"-s", "asdsadadasd:asdasdsadasd"})).contains("ws-client");
}
@Test
public void testWsClientConsole() {
- final String[] EventArgs =
- { "-c", "-s", "AServerThatDoesntExist", "-p", "99999999" };
-
- final String outputString = runWsClient(EventArgs);
-
- assertTrue(outputString.contains("terminate the application typing"));
+ assertThat(runWsClient(new String[] {"-c", "-s", "AServerThatDoesntExist", "-p", "99999999"}))
+ .contains("terminate the application typing");
}
@Test
public void testWsClientEcho() {
- final String[] EventArgs =
- { "-s", "AServerThatDoesntExist", "-p", "99999999" };
-
- final String outputString = runWsClient(EventArgs);
-
- assertTrue(outputString.contains(
- "Once started, the application will simply print out all received events to standard out"));
+ assertThat(runWsClient(new String[] {"-s", "AServerThatDoesntExist", "-p", "99999999"})).contains(
+ "Once started, the application will simply print out all received events to standard out");
}
/**
* Run the application.
- *
+ *
* @param eventArgs the command arguments
* @return a string containing the command output
*/
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
////// end::**
////
+import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
@SuppressWarnings("resource")
// tag::cliParserVersion[]
public String getAppVersion() {
- return new Scanner(CliParser.class.getResourceAsStream("/app-version.txt"), "UTF-8").useDelimiter("\\A").next();
+ return new Scanner(CliParser.class.getResourceAsStream("/app-version.txt"), StandardCharsets.UTF_8)
+ .useDelimiter("\\A").next();
}
// end::cliParserVersion[]
}