Fix sonars in apex-pdp 39/118039/3
authorJim Hahn <jrh3@att.com>
Wed, 17 Feb 2021 20:23:38 +0000 (15:23 -0500)
committerJim Hahn <jrh3@att.com>
Thu, 18 Feb 2021 17:47:55 +0000 (17:47 +0000)
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:
auth/cli-codegen/src/main/java/org/onap/policy/apex/auth/clicodegen/CgStringRenderer.java
context/context-management/src/main/java/org/onap/policy/apex/context/impl/distribution/AbstractDistributor.java
context/context-management/src/main/java/org/onap/policy/apex/context/impl/locking/AbstractLockManager.java
core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnEvent.java
core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AbstractExecutionContext.java
core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskExecutionContext.java
core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContext.java
core/core-engine/src/test/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImplTest.java
core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/java/classes/ClassUtils.java
core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/impl/ws/RawMessageHandler.java
core/core-infrastructure/src/main/java/org/onap/policy/apex/core/infrastructure/messaging/util/MessagingUtils.java
core/core-protocols/src/main/java/org/onap/policy/apex/core/protocols/Message.java
examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicyDecideTaskSelectionLogic.java
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConcept.java
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKey.java
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfo.java
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInformation.java
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxModel.java
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/DefaultApexDao.java
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReader.java
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReaderTest.java
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriterTest.java
model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbum.java
model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextModel.java
model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineModel.java
model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEventModel.java
model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxField.java
model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxPolicyModel.java
model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxState.java
model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateOutput.java
model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateTaskReference.java
model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxStateTree.java
model/utilities/src/main/java/org/onap/policy/apex/model/utilities/CollectionUtils.java
model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TreeMapUtils.java
plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConusmerTest.java
plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientProducerTest.java
plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restrequestor/src/test/java/org/onap/policy/apex/plugins/event/carrier/restrequestor/RestRequestorCarrierTechnologyParametersTest.java
plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-xml/src/test/java/org/onap/policy/apex/plugins/event/protocol/xml/XmlTaggedEventConsumerTest.java
plugins/plugins-event/plugins-event-protocol/plugins-event-protocol-yaml/src/test/java/org/onap/policy/apex/plugins/event/protocol/yaml/YamlPluginStabilityTest.java
plugins/plugins-executor/plugins-executor-javascript/src/test/java/org/onap/policy/apex/plugins/executor/javascript/JavascriptTaskExecutorTest.java
services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java
services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java
services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParameters.java
services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextCharDelimitedParameters.java
services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextTokenDelimitedParameters.java
services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonTaggedEventConsumerTest.java
services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java
services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterActivator.java
testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java
testsuites/integration/integration-executor-test/src/test/java/org/onap/policy/apex/testsuites/integration/executor/handling/TestApexSamplePolicyCreateModelFiles.java
testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/EventGenerator.java
testsuites/performance/performance-benchmark-test/src/main/java/org/onap/policy/apex/testsuites/performance/benchmark/eventgenerator/events/InputEvent.java
tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2CliTest.java
tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2event/Model2EventSchemaTest.java
tools/model-generator/src/test/java/org/onap/policy/apex/tools/model/generator/model2event/Model2EventTest.java
tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java
tools/simple-wsclient/src/test/java/org/onap/policy/apex/tools/simple/wsclient/WsClientTest.java
tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/CliParser.java

index 9eb154c..b2cd9b9 100644 (file)
@@ -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}.
index 1d73f58..3444f93 100644 (file)
@@ -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()");
     }
index a2bd45c..4eb878b 100644 (file)
@@ -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);
index 2f9627d..d4b2124 100644 (file)
@@ -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
index a47ccaa..5276731 100644 (file)
@@ -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;
index 1a19d18..49459df 100644 (file)
@@ -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;
 
index 9c3c2be..69d51c4 100644 (file)
@@ -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;
index e539750..d559d75 100644 (file)
@@ -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();
 
index aa3adf4..03bedce 100644 (file)
@@ -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.
      *
index acd7bdf..0493eaf 100644 (file)
@@ -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();
index 463e85f..bda1f87 100644 (file)
@@ -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);
-        }
-    }
 }
index 6853cc7..b79308e 100644 (file)
@@ -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;
index c0aa620..1805d81 100644 (file)
@@ -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
index 8bbc652..0e2c6be 100644 (file)
@@ -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);
     }
index 7438473..1b6f014 100644 (file)
@@ -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);
     }
 
index fc8c0cd..4b84a40 100644 (file)
@@ -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);
index 446a00a..2619d2e 100644 (file)
@@ -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
+}
index 9c71638..da6fb49 100644 (file)
@@ -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;
index 39e8b0d..738d15e 100644 (file)
@@ -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();
         }
index 39eacce..db7360e 100644 (file)
@@ -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
 
index 92f6206..d75f202 100644 (file)
@@ -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;
index fbbe246..147eb20 100644 (file)
@@ -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;
index 7e15003..629e255 100644 (file)
@@ -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;
index da04aad..9fbcc81 100644 (file)
@@ -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
index 3524f12..23310b2 100644 (file)
@@ -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.
index f4938dc..511d4f3 100644 (file)
@@ -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
index a1d6a8b..654a83c 100644 (file)
@@ -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;
index 7b7dba8..d55fbd3 100644 (file)
@@ -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
+}
index 44b71f8..80e967f 100644 (file)
@@ -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;
index 87caf03..27c1873 100644 (file)
@@ -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;
index a3cb9e6..c98e38f 100644 (file)
@@ -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;
index cd21742..a27e1af 100644 (file)
@@ -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.
 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;
     }
 }
index 0d90d8c..190b270 100644 (file)
@@ -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.
      */
index 4f43e6c..d48f7f9 100644 (file)
@@ -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.
index fafde8b..20d6feb 100644 (file)
@@ -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;
 
index ac82713..ac35081 100644 (file)
@@ -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
+}
index fdf094f..d5268b1 100644 (file)
@@ -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
index 52b84bc..320d7ba 100644 (file)
@@ -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());
     }
 }
index 0577be7..ab91149 100644 (file)
@@ -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.
 
 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;
index 031d605..991c89b 100644 (file)
@@ -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();
index 076c50b..e12e458 100644 (file)
@@ -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);
         }
 
index 5a90f84..e688aad 100644 (file)
@@ -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();
     }
 
index b3a2644..68d5f8a 100644 (file)
@@ -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();
     }
 
index 989d3f2..d15d7ed 100644 (file)
@@ -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();
     }
 
index f9328f4..ff363af 100644 (file)
@@ -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
      */
index 52d8981..3bdcf53 100644 (file)
@@ -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());
     }
 }
index 9f420d8..71ff288 100644 (file)
@@ -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
index 6a30963..b9424c2 100644 (file)
@@ -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()),
index fee2dc6..dbd3d91 100644 (file)
@@ -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.
index a007292..9566917 100644 (file)
@@ -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();
+        }
     }
 }
index 5bdcb7a..91f84b6 100644 (file)
@@ -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();
 
index 71c3d79..2cccc7d 100644 (file)
@@ -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;
index 24a9f60..56c4197 100644 (file)
@@ -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
index 552101f..9c7eccd 100644 (file)
@@ -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
+}
index 5e2b051..c918060 100644 (file)
@@ -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
index 9931c12..ca123c9 100644 (file)
@@ -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);
             }
         }
 
index 6faafe7..e3e775a 100644 (file)
@@ -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
      */
index 67ef7d7..d97711d 100644 (file)
@@ -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[]
 }