diff options
author | Jim Hahn <jrh3@att.com> | 2021-02-17 15:23:38 -0500 |
---|---|---|
committer | Jim Hahn <jrh3@att.com> | 2021-02-18 17:47:55 +0000 |
commit | b6977d2f7ce64ece732ac1a1a0525dac972d7ccf (patch) | |
tree | 4966f5aa4737b0fef8241989eb216cce7fbe9294 | |
parent | 4e05982e36aa66b83fa0ee44b9631412442c3969 (diff) |
Fix sonars in apex-pdp
Addressed the following issues:
- initialize mocks before use
- use parameterized queries
- Random() is not secure
- provide parameterized type for generics
- unused imports
- constructor visibility
- use compute() instead of containsKey()/put()
- make final fields static
- rename constants to all upper case
- no assert() in Thread.run() methods
- nested try
- nested if/else
- too many break/continue
- use try-with-resources
- repeatable annotations
- overlapping characters in reg ex
- hashcode is not sufficient in compareTo()
- need equals() with compareTo()
- make class an interface
- use parameterized test
- multiple calls in assert()
- log or re-throw
- use different type of lambda
- use parameterized logging
- use StringBuilder instead of concatenation
- use StandardCharsets.UTF_8
Issue-ID: POLICY-2906
Change-Id: I2cf8c885e3e22c2c6cbe6403a34906928afad022
Signed-off-by: Jim Hahn <jrh3@att.com>
58 files changed, 509 insertions, 720 deletions
diff --git a/auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CgStringRenderer.java b/auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CgStringRenderer.java index 9eb154cb8..b2cd9b9ca 100644 --- a/auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CgStringRenderer.java +++ b/auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CgStringRenderer.java @@ -1,19 +1,20 @@ /*- * ============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========================================================= */ @@ -30,7 +31,7 @@ import org.stringtemplate.v4.StringRenderer; * @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}. diff --git a/context/context-management/src/main/java/org/onap/policy/apex/context/impl/distribution/AbstractDistributor.java b/context/context-management/src/main/java/org/onap/policy/apex/context/impl/distribution/AbstractDistributor.java index 1d73f58f1..3444f9342 100644 --- a/context/context-management/src/main/java/org/onap/policy/apex/context/impl/distribution/AbstractDistributor.java +++ b/context/context-management/src/main/java/org/onap/policy/apex/context/impl/distribution/AbstractDistributor.java @@ -2,6 +2,7 @@ * ============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. @@ -74,7 +75,7 @@ public abstract class AbstractDistributor implements Distributor { /** * Create an instance of an abstract Context Distributor. */ - public AbstractDistributor() { + protected AbstractDistributor() { LOGGER.entry("AbstractContextDistributor()"); LOGGER.exit("AbstractContextDistributor()"); } diff --git a/context/context-management/src/main/java/org/onap/policy/apex/context/impl/locking/AbstractLockManager.java b/context/context-management/src/main/java/org/onap/policy/apex/context/impl/locking/AbstractLockManager.java index a2bd45ccc..4eb878b1c 100644 --- a/context/context-management/src/main/java/org/onap/policy/apex/context/impl/locking/AbstractLockManager.java +++ b/context/context-management/src/main/java/org/onap/policy/apex/context/impl/locking/AbstractLockManager.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -166,14 +167,12 @@ public abstract class AbstractLockManager implements LockManager { */ 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; } @@ -191,7 +190,7 @@ public abstract class AbstractLockManager implements LockManager { 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); diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnEvent.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnEvent.java index 2f9627dd1..d4b212421 100644 --- a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnEvent.java +++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnEvent.java @@ -2,6 +2,7 @@ * ============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. @@ -68,7 +69,10 @@ public class EnEvent extends HashMap<String, Object> { @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 diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AbstractExecutionContext.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AbstractExecutionContext.java index a47ccaa48..527673108 100644 --- a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AbstractExecutionContext.java +++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AbstractExecutionContext.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -35,12 +36,12 @@ import org.onap.policy.common.utils.coder.StandardCoder; @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; diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskExecutionContext.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskExecutionContext.java index 1a19d18b8..49459dfae 100644 --- a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskExecutionContext.java +++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskExecutionContext.java @@ -2,6 +2,7 @@ * ============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. @@ -29,10 +30,8 @@ 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.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; @@ -40,8 +39,6 @@ import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; 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; diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContext.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContext.java index 9c3c2be0f..69d51c45a 100644 --- a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContext.java +++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContext.java @@ -2,6 +2,7 @@ * ============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. @@ -24,10 +25,8 @@ package org.onap.policy.apex.core.engine.executor.context; 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; diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImplTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImplTest.java index e539750e6..d559d7591 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImplTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImplTest.java @@ -2,6 +2,7 @@ * ============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. @@ -309,8 +310,7 @@ public class ApexEngineImplTest { (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)); @@ -330,8 +330,7 @@ public class ApexEngineImplTest { (new Thread() { @Override public void run() { - assertTrue(engine.handleEvent(event)); - assertEquals(AxEngineState.STOPPED, engine.getState()); + engine.handleEvent(event); } }).start(); diff --git a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/java/classes/ClassUtils.java b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/java/classes/ClassUtils.java index aa3adf4d0..03bedce81 100644 --- a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/java/classes/ClassUtils.java +++ b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/java/classes/ClassUtils.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -24,6 +25,7 @@ import java.io.File; 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; @@ -91,33 +93,7 @@ public abstract class ClassUtils { 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) { @@ -141,6 +117,47 @@ public abstract class ClassUtils { 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. * diff --git a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/impl/ws/RawMessageHandler.java b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/impl/ws/RawMessageHandler.java index acd7bdfea..0493eafb5 100644 --- a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/impl/ws/RawMessageHandler.java +++ b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/impl/ws/RawMessageHandler.java @@ -2,6 +2,7 @@ * ============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. @@ -158,29 +159,16 @@ public class RawMessageHandler<M> implements WebSocketMessageListener<M>, Runnab 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(); diff --git a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/util/MessagingUtils.java b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/util/MessagingUtils.java index 463e85f3e..bda1f870c 100644 --- a/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/util/MessagingUtils.java +++ b/core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/util/MessagingUtils.java @@ -2,6 +2,7 @@ * ============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. @@ -218,37 +219,11 @@ public final class MessagingUtils { 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); - } - } } diff --git a/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Message.java b/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Message.java index 6853cc75c..b79308e4a 100644 --- a/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Message.java +++ b/core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Message.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -55,7 +56,7 @@ public abstract class Message implements Serializable { * @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); } @@ -66,7 +67,7 @@ public abstract class Message implements Serializable { * @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; diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicyDecideTaskSelectionLogic.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicyDecideTaskSelectionLogic.java index c0aa620ac..1805d81a2 100644 --- a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicyDecideTaskSelectionLogic.java +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicyDecideTaskSelectionLogic.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -35,7 +36,11 @@ public class AutoLearnPolicyDecideTaskSelectionLogic { 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; @@ -146,7 +151,7 @@ public class AutoLearnPolicyDecideTaskSelectionLogic { /** * Calculate the return value of the learning. - * + * * @param diff the difference * @param random the random value * @param closestupi closest to i upwards diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConcept.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConcept.java index 8bbc652e7..0e2c6bef2 100644 --- a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConcept.java +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConcept.java @@ -2,6 +2,7 @@ * ============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. @@ -41,7 +42,7 @@ public abstract class AxConcept implements Serializable, Comparable<AxConcept> { /** * Default constructor. */ - public AxConcept() { + protected AxConcept() { // Default constructor } @@ -50,7 +51,7 @@ public abstract class AxConcept implements Serializable, Comparable<AxConcept> { * * @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); } diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKey.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKey.java index 743847358..1b6f0148f 100644 --- a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKey.java +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKey.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -67,7 +68,7 @@ public abstract class AxKey extends AxConcept { /** * Default constructor. */ - public AxKey() { + protected AxKey() { super(); } @@ -76,7 +77,7 @@ public abstract class AxKey extends AxConcept { * * @param copyConcept the concept to copy from */ - public AxKey(final AxKey copyConcept) { + protected AxKey(final AxKey copyConcept) { super(copyConcept); } diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfo.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfo.java index fc8c0cd14..4b84a403a 100644 --- a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfo.java +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfo.java @@ -2,6 +2,7 @@ * ============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. @@ -63,7 +64,10 @@ public class AxKeyInfo extends AxConcept { 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) @@ -334,7 +338,10 @@ public class AxKeyInfo extends AxConcept { 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); diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInformation.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInformation.java index 446a00a68..2619d2eea 100644 --- a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInformation.java +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInformation.java @@ -2,6 +2,7 @@ * ============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. @@ -148,12 +149,13 @@ public class AxKeyInformation extends AxConcept implements AxConceptGetter<AxKey } 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; + }); } } @@ -422,4 +424,4 @@ public class AxKeyInformation extends AxConcept implements AxConceptGetter<AxKey return new AxConceptGetterImpl<>((NavigableMap<AxArtifactKey, AxKeyInfo>) keyInfoMap).getAll(conceptKeyName, conceptKeyVersion); } -}
\ No newline at end of file +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxModel.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxModel.java index 9c71638fc..da6fb49c6 100644 --- a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxModel.java +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxModel.java @@ -2,6 +2,7 @@ * ============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. @@ -30,7 +31,6 @@ import javax.persistence.Entity; 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; @@ -76,8 +76,8 @@ public class AxModel extends AxConcept { // @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; diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/DefaultApexDao.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/DefaultApexDao.java index 39e8b0def..738d15ed3 100644 --- a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/DefaultApexDao.java +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/DefaultApexDao.java @@ -2,6 +2,7 @@ * ============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. @@ -47,12 +48,18 @@ import org.slf4j.ext.XLoggerFactory; 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 @@ -151,8 +158,10 @@ public class DefaultApexDao implements ApexDao { 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(); @@ -171,8 +180,12 @@ public class DefaultApexDao implements ApexDao { 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(); @@ -234,7 +247,10 @@ public class DefaultApexDao implements ApexDao { 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 { @@ -260,9 +276,11 @@ public class DefaultApexDao implements ApexDao { 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 { @@ -372,8 +390,9 @@ public class DefaultApexDao implements ApexDao { 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(); @@ -391,8 +410,11 @@ public class DefaultApexDao implements ApexDao { 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(); } @@ -418,8 +440,11 @@ public class DefaultApexDao implements ApexDao { 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(); } diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReader.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReader.java index 39eacce30..db7360e75 100644 --- a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReader.java +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReader.java @@ -2,6 +2,7 @@ * ============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. @@ -61,7 +62,7 @@ public class ApexModelReader<C extends AxConcept> { // (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 diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReaderTest.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReaderTest.java index 92f6206bb..d75f20253 100644 --- a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReaderTest.java +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReaderTest.java @@ -2,6 +2,7 @@ * ============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. @@ -39,12 +40,15 @@ import javax.xml.bind.PropertyException; 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; diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriterTest.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriterTest.java index fbbe2467c..147eb206a 100644 --- a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriterTest.java +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriterTest.java @@ -2,6 +2,7 @@ * ============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. @@ -34,13 +35,16 @@ import javax.xml.bind.JAXBException; 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; diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbum.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbum.java index 7e15003a0..629e2556c 100644 --- a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbum.java +++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbum.java @@ -2,6 +2,7 @@ * ============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. @@ -23,7 +24,6 @@ package org.onap.policy.apex.model.contextmodel.concepts; import java.util.List; import javax.persistence.AttributeOverride; -import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.EmbeddedId; @@ -101,10 +101,8 @@ public class AxContextAlbum extends AxConcept { // @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; diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextModel.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextModel.java index da04aad83..9fbcc81cb 100644 --- a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextModel.java +++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextModel.java @@ -2,6 +2,7 @@ * ============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. @@ -25,7 +26,6 @@ import java.util.List; 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; @@ -64,18 +64,14 @@ public class AxContextModel extends AxModel { // @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 diff --git a/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineModel.java b/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineModel.java index 3524f1290..23310b219 100644 --- a/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineModel.java +++ b/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineModel.java @@ -2,6 +2,7 @@ * ============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. @@ -27,7 +28,6 @@ import javax.persistence.Column; 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; @@ -77,18 +77,14 @@ public class AxEngineModel extends AxContextModel { @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. diff --git a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEventModel.java b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEventModel.java index f4938dcea..511d4f3d0 100644 --- a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEventModel.java +++ b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEventModel.java @@ -2,6 +2,7 @@ * ============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. @@ -25,7 +26,6 @@ import java.util.List; 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; @@ -64,14 +64,14 @@ public class AxEventModel extends AxModel { // @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 diff --git a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxField.java b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxField.java index a1d6a8ba1..654a83ced 100644 --- a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxField.java +++ b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxField.java @@ -2,6 +2,7 @@ * ============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. @@ -23,7 +24,6 @@ package org.onap.policy.apex.model.eventmodel.concepts; import java.util.List; import javax.persistence.AttributeOverride; -import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.EmbeddedId; @@ -83,8 +83,8 @@ public class AxField extends AxConcept { // @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; diff --git a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxPolicyModel.java b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxPolicyModel.java index 7b7dba800..d55fbd329 100644 --- a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxPolicyModel.java +++ b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxPolicyModel.java @@ -2,6 +2,7 @@ * ============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. @@ -28,7 +29,6 @@ import java.util.TreeSet; 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; @@ -120,33 +120,33 @@ public class AxPolicyModel extends AxModel { // @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 @@ -749,4 +749,4 @@ public class AxPolicyModel extends AxModel { } return schemas.compareTo(other.schemas); } -}
\ No newline at end of file +} diff --git a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxState.java b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxState.java index 44b71f84a..80e967fdf 100644 --- a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxState.java +++ b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxState.java @@ -3,6 +3,7 @@ * 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. @@ -29,7 +30,6 @@ import java.util.Set; 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; @@ -140,8 +140,8 @@ public class AxState extends AxConcept { // @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; @@ -195,8 +195,8 @@ public class AxState extends AxConcept { 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; diff --git a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateOutput.java b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateOutput.java index 87caf03a2..27c187356 100644 --- a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateOutput.java +++ b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateOutput.java @@ -2,6 +2,7 @@ * ============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. @@ -23,7 +24,6 @@ package org.onap.policy.apex.model.policymodel.concepts; import java.util.List; import javax.persistence.AttributeOverride; -import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.EmbeddedId; @@ -79,17 +79,17 @@ public class AxStateOutput extends AxConcept { // @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; diff --git a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateTaskReference.java b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateTaskReference.java index a3cb9e647..c98e38fbf 100644 --- a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateTaskReference.java +++ b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateTaskReference.java @@ -2,6 +2,7 @@ * ============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. @@ -23,7 +24,6 @@ package org.onap.policy.apex.model.policymodel.concepts; import java.util.List; import javax.persistence.AttributeOverride; -import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.EmbeddedId; @@ -91,10 +91,10 @@ public class AxStateTaskReference extends AxConcept { // @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; diff --git a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateTree.java b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateTree.java index cd21742a4..a27e1af1e 100644 --- a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateTree.java +++ b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateTree.java @@ -2,6 +2,7 @@ * ============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. @@ -22,10 +23,12 @@ 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; @@ -38,6 +41,7 @@ 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; @@ -144,12 +148,26 @@ public class AxStateTree implements Comparable<AxStateTree> { } 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; } } diff --git a/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/CollectionUtils.java b/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/CollectionUtils.java index 0d90d8ceb..190b270ea 100644 --- a/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/CollectionUtils.java +++ b/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/CollectionUtils.java @@ -1,19 +1,20 @@ /*- * ============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========================================================= */ @@ -28,7 +29,7 @@ import java.util.ListIterator; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public abstract class CollectionUtils { +public class CollectionUtils { /** * Private constructor used to prevent sub class instantiation. */ diff --git a/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TreeMapUtils.java b/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TreeMapUtils.java index 4f43e6c4d..d48f7f951 100644 --- a/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TreeMapUtils.java +++ b/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TreeMapUtils.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -32,7 +33,7 @@ import java.util.NavigableMap; * * @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. diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConusmerTest.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConusmerTest.java index fafde8b98..20d6feb5b 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConusmerTest.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConusmerTest.java @@ -2,6 +2,7 @@ * ============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. @@ -36,9 +37,11 @@ import javax.ws.rs.client.WebTarget; 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; @@ -47,6 +50,7 @@ import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMo * This class tests the ApexRestClientConusmer class. * */ +@RunWith(MockitoJUnitRunner.class) public class ApexRestClientConusmerTest { private final PrintStream stdout = System.out; diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientProducerTest.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientProducerTest.java index ac8271309..ac35081f2 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientProducerTest.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientProducerTest.java @@ -2,6 +2,7 @@ * ============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. @@ -31,9 +32,11 @@ import javax.ws.rs.client.Invocation.Builder; 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; @@ -45,6 +48,7 @@ import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMo * Test the ApexRestClientProducer class. * */ +@RunWith(MockitoJUnitRunner.class) public class ApexRestClientProducerTest { @Mock private Client httpClientMock; @@ -293,4 +297,4 @@ public class ApexRestClientProducerTest { .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 +} diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RestRequestorCarrierTechnologyParametersTest.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RestRequestorCarrierTechnologyParametersTest.java index fdf094f54..d5268b14c 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RestRequestorCarrierTechnologyParametersTest.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RestRequestorCarrierTechnologyParametersTest.java @@ -3,6 +3,7 @@ * 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. @@ -41,35 +42,29 @@ public class RestRequestorCarrierTechnologyParametersTest { @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 diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XmlTaggedEventConsumerTest.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XmlTaggedEventConsumerTest.java index 52b84bc5b..320d7ba22 100644 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XmlTaggedEventConsumerTest.java +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XmlTaggedEventConsumerTest.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -44,14 +45,7 @@ public class XmlTaggedEventConsumerTest { */ @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"); } /** @@ -61,15 +55,7 @@ public class XmlTaggedEventConsumerTest { */ @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>"); } /** @@ -79,15 +65,8 @@ public class XmlTaggedEventConsumerTest { */ @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>"); } /** @@ -97,14 +76,8 @@ public class XmlTaggedEventConsumerTest { */ @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>"); } /** @@ -114,15 +87,8 @@ public class XmlTaggedEventConsumerTest { */ @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"); } /** @@ -132,16 +98,9 @@ public class XmlTaggedEventConsumerTest { */ @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"); } /** @@ -151,13 +110,7 @@ public class XmlTaggedEventConsumerTest { */ @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"); } /** @@ -167,14 +120,7 @@ public class XmlTaggedEventConsumerTest { */ @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>"); } /** @@ -184,16 +130,9 @@ public class XmlTaggedEventConsumerTest { */ @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>"); } /** @@ -203,17 +142,9 @@ public class XmlTaggedEventConsumerTest { */ @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>"); } /** @@ -225,15 +156,9 @@ public class XmlTaggedEventConsumerTest { 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"); } /** @@ -243,17 +168,9 @@ public class XmlTaggedEventConsumerTest { */ @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"); } /** @@ -263,15 +180,8 @@ public class XmlTaggedEventConsumerTest { */ @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>"); } /** @@ -281,15 +191,9 @@ public class XmlTaggedEventConsumerTest { */ @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>"); } /** @@ -299,15 +203,8 @@ public class XmlTaggedEventConsumerTest { */ @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"); } /** @@ -319,14 +216,8 @@ public class XmlTaggedEventConsumerTest { 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); } /** @@ -336,15 +227,9 @@ public class XmlTaggedEventConsumerTest { */ @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>"); } /** @@ -356,20 +241,10 @@ public class XmlTaggedEventConsumerTest { 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>"); } /** @@ -381,20 +256,10 @@ public class XmlTaggedEventConsumerTest { 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>"); } /** @@ -407,20 +272,10 @@ public class XmlTaggedEventConsumerTest { 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"); } /** @@ -430,16 +285,55 @@ public class XmlTaggedEventConsumerTest { */ @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()); } } diff --git a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/YamlPluginStabilityTest.java b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/YamlPluginStabilityTest.java index 0577be703..ab911499a 100644 --- a/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/YamlPluginStabilityTest.java +++ b/plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/YamlPluginStabilityTest.java @@ -2,6 +2,7 @@ * ============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. @@ -21,11 +22,8 @@ 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; diff --git a/plugins/plugins-executor/plugins-executor-javascript/src/test/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskExecutorTest.java b/plugins/plugins-executor/plugins-executor-javascript/src/test/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskExecutorTest.java index 031d605e1..991c89bcb 100644 --- a/plugins/plugins-executor/plugins-executor-javascript/src/test/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskExecutorTest.java +++ b/plugins/plugins-executor/plugins-executor-javascript/src/test/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskExecutorTest.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -117,8 +118,9 @@ public class JavascriptTaskExecutorTest { 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(); @@ -128,7 +130,7 @@ public class JavascriptTaskExecutorTest { 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(); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java index 076c50b40..e12e4588e 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java @@ -2,6 +2,7 @@ * ============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. @@ -129,7 +130,6 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { 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); } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java index 5a90f847d..e688aad17 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java @@ -1,19 +1,20 @@ /*- * ============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========================================================= */ @@ -28,7 +29,7 @@ import org.onap.policy.common.parameters.ValidationStatus; /** * 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 @@ -50,7 +51,7 @@ public abstract class CarrierTechnologyParameters implements ParameterGroup { * 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(); } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParameters.java index b3a264481..68d5f8a56 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParameters.java @@ -1,19 +1,20 @@ /*- * ============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========================================================= */ @@ -49,7 +50,7 @@ public abstract class EventProtocolParameters implements ParameterGroup { * 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(); } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextCharDelimitedParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextCharDelimitedParameters.java index 989d3f266..d15d7ed47 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextCharDelimitedParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextCharDelimitedParameters.java @@ -1,19 +1,20 @@ /*- * ============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========================================================= */ @@ -43,7 +44,7 @@ public abstract class EventProtocolTextCharDelimitedParameters extends EventProt /** * Constructor to create an event protocol parameters instance with the name of a sub class of this class. */ - public EventProtocolTextCharDelimitedParameters() { + protected EventProtocolTextCharDelimitedParameters() { super(); } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextTokenDelimitedParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextTokenDelimitedParameters.java index f9328f418..ff363aff6 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextTokenDelimitedParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextTokenDelimitedParameters.java @@ -1,19 +1,20 @@ /*- * ============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========================================================= */ @@ -48,7 +49,7 @@ public abstract class EventProtocolTextTokenDelimitedParameters extends EventPro /** * Constructor to create an event protocol parameters instance with the name of a sub class of this class. */ - public EventProtocolTextTokenDelimitedParameters() { + protected EventProtocolTextTokenDelimitedParameters() { super(); } @@ -92,7 +93,7 @@ public abstract class EventProtocolTextTokenDelimitedParameters extends EventPro /** * 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() { @@ -101,7 +102,7 @@ public abstract class EventProtocolTextTokenDelimitedParameters extends EventPro /** * 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 */ diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonTaggedEventConsumerTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonTaggedEventConsumerTest.java index 52d8981c3..3bdcf53d9 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonTaggedEventConsumerTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonTaggedEventConsumerTest.java @@ -1,19 +1,20 @@ /*- * ============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========================================================= */ @@ -40,91 +41,60 @@ public class JsonTaggedEventConsumerTest { @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()); } } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java index 9f420d8fb..71ff28877 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java @@ -3,6 +3,7 @@ * 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. @@ -191,53 +192,32 @@ public class SyncParameterTests { @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 diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterActivator.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterActivator.java index 6a309632e..b9424c274 100644 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterActivator.java +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterActivator.java @@ -1,7 +1,7 @@ /*- * ============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. @@ -128,7 +128,7 @@ public class ApexStarterActivator { () -> 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())) @@ -136,8 +136,8 @@ public class ApexStarterActivator { () -> 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()), diff --git a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java index fee2dc6de..dbd3d918f 100644 --- a/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java +++ b/testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java @@ -2,6 +2,7 @@ * ============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. @@ -29,7 +30,11 @@ import org.onap.policy.apex.core.engine.executor.context.TaskExecutionContext; */ 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. diff --git a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyCreateModelFiles.java b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyCreateModelFiles.java index a00729268..956691797 100644 --- a/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyCreateModelFiles.java +++ b/testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyCreateModelFiles.java @@ -1,73 +1,42 @@ /*- * ============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(); + } } } diff --git a/testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/EventGenerator.java b/testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/EventGenerator.java index 5bdcb7a64..91f84b66b 100644 --- a/testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/EventGenerator.java +++ b/testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/EventGenerator.java @@ -2,6 +2,7 @@ * ============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. @@ -142,7 +143,9 @@ public class EventGenerator { * @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(); diff --git a/testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/events/InputEvent.java b/testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/events/InputEvent.java index 71c3d797a..2cccc7dc0 100644 --- a/testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/events/InputEvent.java +++ b/testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/events/InputEvent.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -50,7 +51,11 @@ public class InputEvent { * 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; diff --git a/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2CliTest.java b/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2CliTest.java index 24a9f60ce..56c4197ea 100644 --- a/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2CliTest.java +++ b/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2CliTest.java @@ -2,6 +2,7 @@ * ============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. @@ -21,6 +22,7 @@ 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; @@ -52,29 +54,17 @@ public class Model2CliTest { @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 diff --git a/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2event/Model2EventSchemaTest.java b/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2event/Model2EventSchemaTest.java index 552101f94..9c7eccd0f 100644 --- a/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2event/Model2EventSchemaTest.java +++ b/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2event/Model2EventSchemaTest.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -33,6 +34,7 @@ import org.junit.Test; 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; @@ -81,36 +83,15 @@ public class Model2EventSchemaTest { } @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 @@ -139,4 +120,4 @@ public class Model2EventSchemaTest { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); ModelService.clear(); } -}
\ No newline at end of file +} diff --git a/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2event/Model2EventTest.java b/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2event/Model2EventTest.java index 5e2b05124..c9180607e 100644 --- a/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2event/Model2EventTest.java +++ b/tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2event/Model2EventTest.java @@ -2,6 +2,7 @@ * ============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. @@ -21,6 +22,7 @@ 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; @@ -55,32 +57,17 @@ public class Model2EventTest { @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 diff --git a/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java b/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java index 9931c1292..ca123c9bb 100644 --- a/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java +++ b/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -41,7 +42,7 @@ public class SimpleConsole extends WebSocketClient { /** Application name, used as prompt. */ private final String appName; - + // Output and error streams private PrintStream outStream; private PrintStream errStream; @@ -131,9 +132,9 @@ public class SimpleConsole extends WebSocketClient { }; 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)) { @@ -142,10 +143,10 @@ public class SimpleConsole extends WebSocketClient { 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); } } diff --git a/tools/simple-wsclient/src/test/java/org/onap/policy/apex/tools/simple/wsclient/WsClientTest.java b/tools/simple-wsclient/src/test/java/org/onap/policy/apex/tools/simple/wsclient/WsClientTest.java index 6faafe759..e3e775af4 100644 --- a/tools/simple-wsclient/src/test/java/org/onap/policy/apex/tools/simple/wsclient/WsClientTest.java +++ b/tools/simple-wsclient/src/test/java/org/onap/policy/apex/tools/simple/wsclient/WsClientTest.java @@ -2,6 +2,7 @@ * ============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. @@ -21,8 +22,8 @@ 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; @@ -44,108 +45,59 @@ public class WsClientTest { @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 */ diff --git a/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/CliParser.java b/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/CliParser.java index 67ef7d7dd..d97711d4a 100644 --- a/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/CliParser.java +++ b/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/CliParser.java @@ -1,6 +1,7 @@ /*- * ============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. @@ -27,6 +28,7 @@ package org.onap.policy.apex.tools.common; ////// end::** //// +import java.nio.charset.StandardCharsets; import java.util.Scanner; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; @@ -111,7 +113,8 @@ public class CliParser { @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[] } |