Fix sonars in policy-common 36/121136/3
authorJim Hahn <jrh3@att.com>
Thu, 6 May 2021 15:28:53 +0000 (11:28 -0400)
committerJim Hahn <jrh3@att.com>
Thu, 6 May 2021 19:26:24 +0000 (15:26 -0400)
Fixed sonars:
- use "var" instead of actual type name
- re-interrupt threads
- use rej2 split() instead of String split()

Issue-ID: POLICY-3285
Change-Id: I82261e0b8a53ee5c5264556fbf5cec37454f014e
Signed-off-by: Jim Hahn <jrh3@att.com>
83 files changed:
common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java
common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java
common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java
common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java
common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java
common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java
common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java
common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidationResult.java
common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidator.java
common-parameters/src/main/java/org/onap/policy/common/parameters/FieldValidator.java
common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterException.java
common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterService.java
common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java
common-parameters/src/main/java/org/onap/policy/common/parameters/ValueValidator.java
gson/src/main/java/org/onap/policy/common/gson/DoubleConverter.java
gson/src/main/java/org/onap/policy/common/gson/GsonMessageBodyHandler.java
gson/src/main/java/org/onap/policy/common/gson/InstantAsMillisTypeAdapter.java
gson/src/main/java/org/onap/policy/common/gson/JacksonFieldAdapterFactory.java
gson/src/main/java/org/onap/policy/common/gson/JacksonMethodAdapterFactory.java
gson/src/main/java/org/onap/policy/common/gson/MapDoubleAdapterFactory.java
gson/src/main/java/org/onap/policy/common/gson/internal/JacksonTypeAdapter.java
integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java
integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java
integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java
integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java
integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java
integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java
integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java
integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java
integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java
integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java
integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java
integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java
integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java
integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxy.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedDmaapTopicSinkFactory.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedDmaapTopicSourceFactory.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSinkFactory.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedUebTopicSourceFactory.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactory.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/TopicBaseHashedFactory.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisher.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSink.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSource.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSource.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBase.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/IndexedHttpClientFactory.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/client/internal/JerseyClient.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/IndexedHttpServletServerFactory.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/RestServer.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/YamlMessageBodyHandler.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyJerseyServer.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/http/server/internal/JettyServletServer.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcher.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcher.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroup.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/report/HealthCheckReport.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/DmaapPropertyUtils.java
policy-endpoints/src/main/java/org/onap/policy/common/endpoints/utils/UebPropertyUtils.java
utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java
utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java
utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java
utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java
utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java
utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java
utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java
utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java
utils/src/main/java/org/onap/policy/common/utils/cmd/CommandLineArgumentsHandler.java
utils/src/main/java/org/onap/policy/common/utils/coder/PropertyCoder.java
utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoder.java
utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoderObject.java
utils/src/main/java/org/onap/policy/common/utils/coder/StandardValCoder.java
utils/src/main/java/org/onap/policy/common/utils/coder/YamlJsonTranslator.java
utils/src/main/java/org/onap/policy/common/utils/network/NetworkUtil.java
utils/src/main/java/org/onap/policy/common/utils/properties/BeanConfigurator.java
utils/src/main/java/org/onap/policy/common/utils/properties/PropertyObjectUtils.java
utils/src/main/java/org/onap/policy/common/utils/properties/SpecProperties.java
utils/src/main/java/org/onap/policy/common/utils/properties/exception/PropertyException.java
utils/src/main/java/org/onap/policy/common/utils/resources/ResourceUtils.java
utils/src/main/java/org/onap/policy/common/utils/resources/TextFileUtils.java
utils/src/main/java/org/onap/policy/common/utils/security/CryptoUtils.java
utils/src/main/java/org/onap/policy/common/utils/validation/Version.java

index 47c0504..e457f5f 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP-Logging
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -143,7 +143,7 @@ public class OnapLoggingContext {
      * with key "TransactionElapsedTime".
      */
     public void transactionEnded() {
-        Instant transactionEndTime = Instant.now();
+        var transactionEndTime = Instant.now();
         setTransactionEndTimestamp(transactionEndTime);
         setTransactionElapsedTime(transactionEndTime);
     }
@@ -163,7 +163,7 @@ public class OnapLoggingContext {
      * "MetricElapsedTime".
      */
     public void metricEnded() {
-        Instant metricEndTime = Instant.now();
+        var metricEndTime = Instant.now();
         setMetricEndTimestamp(metricEndTime);
         setMetricElapsedTime(metricEndTime);
     }
@@ -449,7 +449,7 @@ public class OnapLoggingContext {
      * @param transactionStartTime transaction start time
      */
     public void setTransactionBeginTimestamp(Instant transactionStartTime) {
-        SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+        var sdf = new SimpleDateFormat(TIME_FORMAT);
         context.put(TRANSACTION_BEGIN_TIME_STAMP, sdf.format(Date.from(transactionStartTime)));
     }
 
@@ -468,7 +468,7 @@ public class OnapLoggingContext {
      * @param transactionEndTime transaction end time
      */
     public void setTransactionEndTimestamp(Instant transactionEndTime) {
-        SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+        var sdf = new SimpleDateFormat(TIME_FORMAT);
         context.put(TRANSACTION_END_TIME_STAMP, sdf.format(Date.from(transactionEndTime)));
     }
 
@@ -510,7 +510,7 @@ public class OnapLoggingContext {
      * @param metricStartTime metric start time
      */
     public void setMetricBeginTimestamp(Instant metricStartTime) {
-        SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+        var sdf = new SimpleDateFormat(TIME_FORMAT);
         context.put(METRIC_BEGIN_TIME_STAMP, sdf.format(Date.from(metricStartTime)));
     }
 
@@ -529,7 +529,7 @@ public class OnapLoggingContext {
      * @param metricEndTime metric end time
      */
     public void setMetricEndTimestamp(Instant metricEndTime) {
-        SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+        var sdf = new SimpleDateFormat(TIME_FORMAT);
         context.put(METRIC_END_TIME_STAMP, sdf.format(Date.from(metricEndTime)));
     }
 
index b7c93c6..86eb4dd 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP-Logging
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.common.logging;
 
+import java.util.regex.Pattern;
 import javax.servlet.http.HttpServletRequest;
 
 public class OnapLoggingUtils {
 
+    private static final Pattern COMMA_PAT = Pattern.compile(",");
+    private static final Pattern CURLS_PAT = Pattern.compile("[{][}]");
+
     private OnapLoggingUtils() {
         // Private constructor to prevent subclassing
     }
@@ -37,7 +41,7 @@ public class OnapLoggingUtils {
      */
     public static OnapLoggingContext getLoggingContextForRequest(HttpServletRequest request,
         OnapLoggingContext baseContext) {
-        OnapLoggingContext requestContext = new OnapLoggingContext(baseContext);
+        var requestContext = new OnapLoggingContext(baseContext);
         if (request.getLocalAddr() != null) { // may be null in junit tests
             requestContext.setServerIpAddress(request.getLocalAddr());
         }
@@ -45,7 +49,7 @@ public class OnapLoggingUtils {
         // otherwise from remote address in the request
         String forwarded = request.getHeader("X-Forwarded-For");
         if (forwarded != null && forwarded.trim().length() > 0) {
-            forwarded = forwarded.trim().split(",")[0];
+            forwarded = COMMA_PAT.split(forwarded.trim())[0];
             requestContext.setClientIpAddress(forwarded);
         } else if (request.getRemoteAddr() != null) { // may be null in junit tests
             requestContext.setClientIpAddress(request.getRemoteAddr());
@@ -72,8 +76,8 @@ public class OnapLoggingUtils {
             return format;
         }
         int index;
-        StringBuilder builder = new StringBuilder();
-        String[] token = format.split("[{][}]");
+        var builder = new StringBuilder();
+        String[] token = CURLS_PAT.split(format);
         for (index = 0; index < arguments.length; index++) {
             if (index < token.length) {
                 builder.append(token[index]);
index 23be38b..0240399 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP-Logging
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -62,8 +62,8 @@ public class EventData {
 
     @Override
     public int hashCode() {
-        final int prime = 31;
-        int result = 1;
+        final var prime = 31;
+        var result = 1;
         result = prime * result + ((requestId == null) ? 0 : requestId.hashCode());
         return result;
     }
index 1a87de5..f520368 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP-Logging
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -49,7 +49,7 @@ public class EventTrackInfoHandler extends TimerTask {
      */
     private void cleanUp() {
 
-        EventTrackInfo eventTrackInfo = PolicyLogger.getEventTracker();
+        var eventTrackInfo = PolicyLogger.getEventTracker();
         if (eventTrackInfo == null) {
             return;
         }
index 3f94483..1565956 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP-Logging
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -301,8 +301,8 @@ public class PolicyLogger {
 
         setMdcHostInfo();
 
-        Instant startTime = Instant.now();
-        Instant endTime = Instant.now();
+        var startTime = Instant.now();
+        var endTime = Instant.now();
 
         seTimeStamps(startTime, endTime);
 
@@ -334,8 +334,8 @@ public class PolicyLogger {
         MDC.put(MDC_INSTANCE_UUID, "");
         MDC.put(MDC_ALERT_SEVERITY, "");
 
-        Instant startTime = Instant.now();
-        Instant endTime = Instant.now();
+        var startTime = Instant.now();
+        var endTime = Instant.now();
 
         seTimeStamps(startTime, endTime);
 
@@ -348,7 +348,7 @@ public class PolicyLogger {
     }
 
     private static void seTimeStamps(Instant startTime, Instant endTime) {
-        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
+        var sdf = new SimpleDateFormat(DATE_FORMAT);
 
         String formatedTime = sdf.format(Date.from(startTime));
         MDC.put(BEGIN_TIME_STAMP, formatedTime);
@@ -874,7 +874,7 @@ public class PolicyLogger {
         if (eventTracker == null) {
             eventTracker = new EventTrackInfo();
         }
-        EventData event = new EventData();
+        var event = new EventData();
         event.setRequestId(eventId);
         event.setStartTime(Instant.now());
         eventTracker.storeEventData(event);
@@ -1007,7 +1007,7 @@ public class PolicyLogger {
             return;
         }
 
-        EventData event = eventTracker.getEventDataByRequestId(eventId);
+        var event = eventTracker.getEventDataByRequestId(eventId);
 
         if (event != null) {
             Instant endTime = event.getEndTime();
@@ -1035,7 +1035,7 @@ public class PolicyLogger {
             return;
         }
 
-        EventData event = eventTracker.getEventDataByRequestId(eventId.toString());
+        var event = eventTracker.getEventDataByRequestId(eventId.toString());
 
         if (event != null) {
             Instant endTime = event.getEndTime();
@@ -1226,13 +1226,13 @@ public class PolicyLogger {
      * @param arguments the messages
      */
     private static String getNormalizedStackTrace(Throwable throwable, String... arguments) {
-        StringWriter sw = new StringWriter();
-        PrintWriter pw = new PrintWriter(sw);
+        var sw = new StringWriter();
+        var pw = new PrintWriter(sw);
         throwable.printStackTrace(pw);
         String newStValue = sw.toString().replace('|', '!').replace("\n", " - ");
         int curSize = arguments == null ? 0 : arguments.length;
-        StringBuilder newArgument = new StringBuilder();
-        for (int i = 0; i < curSize; i++) {
+        var newArgument = new StringBuilder();
+        for (var i = 0; i < curSize; i++) {
             newArgument.append(arguments[i]);
             newArgument.append(":");
         }
@@ -1246,7 +1246,7 @@ public class PolicyLogger {
     private static void startCleanUp() {
 
         if (!isEventTrackerRunning) {
-            EventTrackInfoHandler ttrcker = new EventTrackInfoHandler();
+            var ttrcker = new EventTrackInfoHandler();
             timer = new Timer(true);
             timer.scheduleAtFixedRate(ttrcker, timerDelayTime, checkInterval);
             debugLogger.info("EventTrackInfoHandler begins! : {}", new Date());
@@ -1279,7 +1279,7 @@ public class PolicyLogger {
      */
     public static LoggerType init(Properties properties) {
 
-        Properties loggerProperties = getLoggerProperties(properties);
+        var loggerProperties = getLoggerProperties(properties);
 
         // fetch and verify definitions of some properties
         try {
@@ -1321,7 +1321,7 @@ public class PolicyLogger {
     }
 
     private static int getIntProp(Properties properties, String propName, int defaultValue) {
-        final int propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue)));
+        final var propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue)));
 
         debugLogger.info("{} value: {}", propName, propValue);
 
index fadb254..2dabc01 100644 (file)
@@ -186,7 +186,7 @@ public class FlexLogger extends SecurityManager {
      * loads the logger properties.
      */
     private static LoggerType initlogger() {
-        LoggerType loggerType = LoggerType.EELF;
+        var loggerType = LoggerType.EELF;
         Properties properties = null;
 
         try {
@@ -196,7 +196,7 @@ public class FlexLogger extends SecurityManager {
             if (properties != null) {
                 String overrideLogbackLevel = properties.getProperty("override.logback.level.setup");
                 displayMessage("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel);
-                String loggerTypeString = properties.getProperty("logger.type");
+                var loggerTypeString = properties.getProperty("logger.type");
                 if ("EELF".equalsIgnoreCase(loggerTypeString) && "TRUE".equalsIgnoreCase(overrideLogbackLevel)) {
                     displayMessage("FlexLogger: start listener.");
                     properties = PropertyUtil.getProperties("config/policyLogger.properties",
@@ -234,8 +234,8 @@ public class FlexLogger extends SecurityManager {
             String auditLevel = properties.getProperty("audit.level");
             String errorLevel = properties.getProperty("error.level");
 
-            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00");
-            Instant startTime = Instant.now();
+            var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00");
+            var startTime = Instant.now();
             String formatedTime = sdf.format(Date.from(startTime));
             displayMessage("FlexLogger.propertiesChanged : called at time : " + formatedTime);
             displayMessage("FlexLogger.propertiesChanged : debugLevel : " + debugLevel);
index b824143..ccd6048 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP-Logging
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -64,9 +64,9 @@ public class PropertyUtil {
      */
     public static Properties getProperties(File file) throws IOException {
         // create an InputStream (may throw a FileNotFoundException)
-        try (FileInputStream fis = new FileInputStream(file)) {
+        try (var fis = new FileInputStream(file)) {
             // create the properties instance
-            Properties rval = new Properties();
+            var rval = new Properties();
 
             // load properties (may throw an IOException)
             rval.load(fis);
@@ -202,7 +202,7 @@ public class PropertyUtil {
                 lastModified = timestamp;
 
                 // Save old set, and initial set of changed properties.
-                Properties oldProperties = properties;
+                var oldProperties = properties;
                 HashSet<String> changedProperties = new HashSet<>(oldProperties.stringPropertyNames());
 
                 // Fetch the list of listeners that we will potentially notify,
@@ -238,7 +238,7 @@ public class PropertyUtil {
                     for (final Listener notify : listeners) {
                         // Copy 'properties' and 'changedProperties', so it doesn't
                         // cause problems if the recipient makes changes.
-                        final Properties tmpProperties = (Properties) (properties.clone());
+                        final var tmpProperties = (Properties) (properties.clone());
                         final HashSet<String> tmpChangedProperties = new HashSet<>(changedProperties);
 
                         // Do the notification in a separate thread, so blocking
@@ -276,7 +276,7 @@ public class PropertyUtil {
 
         // Convert the file to a canonical form in order to avoid the situation
         // where different names refer to the same file.
-        File tempFile = file.getCanonicalFile();
+        var tempFile = file.getCanonicalFile();
 
         // See if there is an existing registration. The 'synchronized' block
         // is needed to handle the case where a new listener is added at about
index fa0c66c..e162053 100644 (file)
@@ -88,7 +88,7 @@ public class BeanValidationResult extends ValidationResultImpl {
      * @return {@code true} if the value is not null, {@code false} otherwise
      */
     public boolean validateNotNull(String subName, Object subObject) {
-        ObjectValidationResult result = new ObjectValidationResult(subName, subObject);
+        var result = new ObjectValidationResult(subName, subObject);
 
         if (result.validateNotNull()) {
             return true;
@@ -126,7 +126,7 @@ public class BeanValidationResult extends ValidationResultImpl {
             return true;
         }
 
-        BeanValidationResult result = new BeanValidationResult(listName, null);
+        var result = new BeanValidationResult(listName, null);
         for (T item : list) {
             if (item == null) {
                 result.addResult("item", item, ValidationStatus.INVALID, "null");
@@ -158,7 +158,7 @@ public class BeanValidationResult extends ValidationResultImpl {
             return true;
         }
 
-        BeanValidationResult result = new BeanValidationResult(mapName, null);
+        var result = new BeanValidationResult(mapName, null);
         for (Entry<String, V> ent : map.entrySet()) {
             entryValidator.accept(result, ent);
         }
@@ -186,7 +186,7 @@ public class BeanValidationResult extends ValidationResultImpl {
             return null;
         }
 
-        StringBuilder builder = new StringBuilder();
+        var builder = new StringBuilder();
 
         builder.append(initialIndentation);
         builder.append('"');
index 947def4..4ed7e42 100644 (file)
@@ -55,7 +55,7 @@ public class BeanValidator {
      * @return the validation result
      */
     public BeanValidationResult validateTop(String name, Object object) {
-        BeanValidationResult result = new BeanValidationResult(name, object);
+        var result = new BeanValidationResult(name, object);
         if (object == null) {
             return result;
         }
@@ -94,7 +94,7 @@ public class BeanValidator {
      */
     private void validateFields(BeanValidationResult result, Object object, Class<?> clazz) {
         for (Field field : clazz.getDeclaredFields()) {
-            FieldValidator validator = makeFieldValidator(clazz, field);
+            var validator = makeFieldValidator(clazz, field);
             validator.validateField(result, object);
         }
     }
@@ -337,8 +337,8 @@ public class BeanValidator {
 
         Collection<?> list = (Collection<?>) value;
 
-        BeanValidationResult result2 = new BeanValidationResult(fieldName, value);
-        int count = 0;
+        var result2 = new BeanValidationResult(fieldName, value);
+        var count = 0;
         for (Object item : list) {
             itemValidator.validateValue(result2, String.valueOf(count++), item);
         }
@@ -370,12 +370,12 @@ public class BeanValidator {
 
         Map<?, ?> map = (Map<?, ?>) value;
 
-        BeanValidationResult result2 = new BeanValidationResult(fieldName, value);
+        var result2 = new BeanValidationResult(fieldName, value);
 
         for (Entry<?, ?> entry : map.entrySet()) {
             String name = getEntryName(entry);
 
-            BeanValidationResult result3 = new BeanValidationResult(name, entry);
+            var result3 = new BeanValidationResult(name, entry);
             keyValidator.validateValue(result3, "key", entry.getKey());
             valueValidator.validateValue(result3, "value", entry.getValue());
 
@@ -399,7 +399,7 @@ public class BeanValidator {
      * @return a name for the entry
      */
     protected <K, V> String getEntryName(Map.Entry<K, V> entry) {
-        K key = entry.getKey();
+        var key = entry.getKey();
         if (key == null) {
             return "";
         }
index efe48bb..51c5d57 100644 (file)
@@ -121,7 +121,7 @@ public class FieldValidator extends ValueValidator {
             return;
         }
 
-        AnnotatedType tannot = field.getAnnotatedType();
+        var tannot = field.getAnnotatedType();
         if (!(tannot instanceof AnnotatedParameterizedType)) {
             return;
         }
@@ -131,7 +131,7 @@ public class FieldValidator extends ValueValidator {
             return;
         }
 
-        ItemValidator itemValidator = new ItemValidator(validator, targs[0]);
+        var itemValidator = new ItemValidator(validator, targs[0]);
         if (itemValidator.isEmpty()) {
             return;
         }
@@ -149,7 +149,7 @@ public class FieldValidator extends ValueValidator {
             return;
         }
 
-        AnnotatedType tannot = field.getAnnotatedType();
+        var tannot = field.getAnnotatedType();
         if (!(tannot instanceof AnnotatedParameterizedType)) {
             return;
         }
@@ -159,8 +159,8 @@ public class FieldValidator extends ValueValidator {
             return;
         }
 
-        ItemValidator keyValidator = new ItemValidator(validator, targs[0]);
-        ItemValidator valueValidator = new ItemValidator(validator, targs[1]);
+        var keyValidator = new ItemValidator(validator, targs[0]);
+        var valueValidator = new ItemValidator(validator, targs[1]);
         if (keyValidator.isEmpty() && valueValidator.isEmpty()) {
             return;
         }
@@ -226,7 +226,7 @@ public class FieldValidator extends ValueValidator {
     public <T extends Annotation> T getAnnotation(Class<T> annotClass) {
 
         // field annotation takes precedence over class annotation
-        T annot = field.getAnnotation(annotClass);
+        var annot = field.getAnnotation(annotClass);
         if (annot != null) {
             setFieldAnnotated(true);
             return annot;
@@ -243,8 +243,8 @@ public class FieldValidator extends ValueValidator {
      * @return the field's "getter" method, or {@code null} if it is not found
      */
     private Method getAccessor(Class<?> clazz, String fieldName) {
-        String capname = StringUtils.capitalize(fieldName);
-        Method accessor2 = getMethod(clazz, "get" + capname);
+        var capname = StringUtils.capitalize(fieldName);
+        var accessor2 = getMethod(clazz, "get" + capname);
         if (accessor2 != null) {
             return accessor2;
         }
index 0b29a4e..84faa9c 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.
@@ -84,15 +85,15 @@ public class ParameterException extends Exception {
 
     /**
      * Build a cascaded message from an exception and all its nested exceptions.
-     * 
+     *
      * @param throwable the top level exception
      * @return cascaded message string
      */
     public static String buildCascadedMessage(final Throwable throwable) {
-        final StringBuilder builder = new StringBuilder();
+        final var builder = new StringBuilder();
         builder.append(throwable.getMessage());
 
-        for (Throwable t = throwable; t != null; t = t.getCause()) {
+        for (var t = throwable; t != null; t = t.getCause()) {
             builder.append("\ncaused by: ");
             builder.append(t.getMessage());
         }
index 358e553..7bf0ac5 100644 (file)
@@ -1,19 +1,20 @@
 /*-
  * ============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.
  * 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=========================================================
  */
@@ -27,10 +28,10 @@ import java.util.concurrent.ConcurrentHashMap;
 
 /**
  * The parameter service makes ONAP PF parameter groups available to all classes in a JVM.
- * 
+ *
  * <p>The reason for having a parameter service is to avoid having to pass parameters down long call chains in modules
  * such as PDPs and editors. The parameter service makes correct and verified parameters available statically.
- * 
+ *
  * <p>The parameter service must be used with care because changing a parameter set anywhere in a JVM will affect all
  * users of those parameters anywhere in the JVM.
  *
@@ -70,7 +71,7 @@ public abstract class ParameterService {
         if (overwrite && parameterGroupMap.containsKey(parameterGroup.getName())) {
             deregister(parameterGroup);
         }
-        
+
         register(parameterGroup);
     }
 
@@ -104,7 +105,7 @@ public abstract class ParameterService {
      */
     public static <T extends ParameterGroup> T get(final String parameterGroupName) {
         @SuppressWarnings("unchecked")
-        final T parameterGroup = (T) parameterGroupMap.get(parameterGroupName);
+        final var parameterGroup = (T) parameterGroupMap.get(parameterGroupName);
 
         if (parameterGroup == null) {
             throw new ParameterRuntimeException("\"" + parameterGroupName + "\" not found in parameter service");
index 3583737..b68c62e 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
- *  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.
@@ -73,7 +73,7 @@ public class ParameterValidationResult implements ValidationResult {
      * @param parameterValue field's value
      */
     private void checkMinValue(final Field field, final Object parameterValue) {
-        Min minAnnot = field.getAnnotation(Min.class);
+        var minAnnot = field.getAnnotation(Min.class);
         if (minAnnot != null && ((Number) parameterValue).longValue() < minAnnot.value()) {
             setResult(ValidationStatus.INVALID, "must be >= " + minAnnot.value());
         }
@@ -86,7 +86,7 @@ public class ParameterValidationResult implements ValidationResult {
      * @param parameterValue field's value
      */
     private void checkMaxValue(final Field field, final Object parameterValue) {
-        Max maxAnnot = field.getAnnotation(Max.class);
+        var maxAnnot = field.getAnnotation(Max.class);
         if (maxAnnot != null && ((Number) parameterValue).longValue() > maxAnnot.value()) {
             setResult(ValidationStatus.INVALID, "must be <= " + maxAnnot.value());
         }
@@ -102,7 +102,7 @@ public class ParameterValidationResult implements ValidationResult {
      * @return the field's annotation, or {@code null} if it does not exist
      */
     private static <T extends Annotation> T getAnyAnnotation(final Field field, Class<T> annotClass) {
-        T annot = field.getAnnotation(annotClass);
+        var annot = field.getAnnotation(annotClass);
         if (annot != null) {
             return annot;
         }
@@ -157,7 +157,7 @@ public class ParameterValidationResult implements ValidationResult {
             return null;
         }
 
-        StringBuilder validationResultBuilder = new StringBuilder();
+        var validationResultBuilder = new StringBuilder();
 
         validationResultBuilder.append(initialIndentation);
         validationResultBuilder.append("field \"");
index 6a641a1..a8a0e61 100644 (file)
@@ -103,7 +103,7 @@ public class ValueValidator {
      * @param checker function to validate the value
      */
     public <T extends Annotation> void addAnnotation(Class<T> annotClass, Checker checker) {
-        T annot = getAnnotation(annotClass);
+        var annot = getAnnotation(annotClass);
         if (annot != null) {
             checkers.add(checker);
 
@@ -122,7 +122,7 @@ public class ValueValidator {
      * @param checker function to validate the value
      */
     public <T extends Annotation> void addAnnotation(Class<T> annotClass, CheckerWithAnnot<T> checker) {
-        T annot = getAnnotation(annotClass);
+        var annot = getAnnotation(annotClass);
         if (annot != null) {
             checkers.add((result, fieldName, value) -> checker.test(result, fieldName, annot, value));
         }
index 81803ff..cbf5d0e 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -98,7 +98,7 @@ public class DoubleConverter {
         }
 
         Double num = (Double) value;
-        long longval = num.longValue();
+        var longval = num.longValue();
 
         if (Double.compare(num.doubleValue(), longval) != 0) {
             // it isn't integral - return unchanged value
@@ -106,7 +106,7 @@ public class DoubleConverter {
         }
 
         // it's integral - determine if it's an integer or a long
-        int intval = (int) longval;
+        var intval = (int) longval;
 
         if (intval == longval) {
             return intval;
index df3def3..a8017d2 100644 (file)
@@ -116,7 +116,7 @@ public class GsonMessageBodyHandler implements MessageBodyReader<Object>, Messag
     public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                     MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
 
-        try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
+        try (var writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
             Type jsonType = (type.equals(genericType) ? type : genericType);
             gson.toJson(object, jsonType, writer);
         }
@@ -152,7 +152,7 @@ public class GsonMessageBodyHandler implements MessageBodyReader<Object>, Messag
     public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                     MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
 
-        try (InputStreamReader streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
+        try (var streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
             Type jsonType = (type.equals(genericType) ? type : genericType);
             return gson.fromJson(streamReader, jsonType);
         }
index c63b03c..c38a3e9 100644 (file)
@@ -47,7 +47,7 @@ public class InstantAsMillisTypeAdapter extends TypeAdapter<Instant> {
             in.nextNull();
             return null;
         } else {
-            long millis = in.nextLong();
+            var millis = in.nextLong();
             return Instant.ofEpochMilli(millis);
         }
     }
index 3458a59..18157b0 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -54,7 +54,7 @@ public class JacksonFieldAdapterFactory implements TypeAdapterFactory {
             return null;
         }
 
-        ClassWalker data = new ClassWalker();
+        var data = new ClassWalker();
         data.walkClassHierarchy(clazz);
 
         if (data.getInProps(Field.class).isEmpty() && data.getOutProps(Field.class).isEmpty()) {
index de96231..b741400 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -58,7 +58,7 @@ public class JacksonMethodAdapterFactory implements TypeAdapterFactory {
             return null;
         }
 
-        ClassWalker data = new ClassWalker();
+        var data = new ClassWalker();
         data.walkClassHierarchy(clazz);
 
         if (data.getInProps(Method.class).isEmpty() && data.getOutProps(Method.class).isEmpty()
index 575c41e..057e97f 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -112,7 +112,7 @@ public class MapDoubleAdapterFactory implements TypeAdapterFactory {
 
         @Override
         public T read(JsonReader in) throws IOException {
-            T value = delegate.read(in);
+            var value = delegate.read(in);
 
             DoubleConverter.convertFromDouble(value);
 
index 1171fd4..34d61f4 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -22,7 +22,6 @@ package org.onap.policy.common.gson.internal;
 
 import com.google.gson.Gson;
 import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
 import com.google.gson.TypeAdapter;
 import com.google.gson.stream.JsonReader;
 import com.google.gson.stream.JsonWriter;
@@ -78,7 +77,7 @@ public class JacksonTypeAdapter<T> extends TypeAdapter<T> {
         JsonElement tree = delegate.toJsonTree(value);
 
         if (tree.isJsonObject()) {
-            JsonObject jsonObj = tree.getAsJsonObject();
+            var jsonObj = tree.getAsJsonObject();
 
             // serialize each item from the value into the target tree
             for (Serializer serializer : serializers) {
@@ -92,10 +91,10 @@ public class JacksonTypeAdapter<T> extends TypeAdapter<T> {
     @Override
     public T read(JsonReader in) throws IOException {
         JsonElement tree = elementAdapter.read(in);
-        T object = delegate.fromJsonTree(tree);
+        var object = delegate.fromJsonTree(tree);
 
         if (tree.isJsonObject()) {
-            JsonObject jsonObj = tree.getAsJsonObject();
+            var jsonObj = tree.getAsJsonObject();
 
             // deserialize each item from the tree into the target object
             for (Deserializer dser : deserializers) {
index 32246c8..03fbdb5 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Integrity Audit
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -22,7 +22,6 @@ package org.onap.policy.common.ia;
 
 import java.util.Collections;
 import java.util.Comparator;
-import java.util.Date;
 import java.util.List;
 import java.util.Properties;
 import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
@@ -149,10 +148,12 @@ public class AuditThread extends Thread {
              */
             runUntilInterrupted();
 
+        } catch (InterruptedException e) {
+            handleAuditLoopException(e);
+            Thread.currentThread().interrupt();
+
         } catch (Exception e) {
-            String msg = "AuditThread.run: Could not start audit loop. Exception thrown; message=" + e.getMessage();
-            logger.error(MessageCodes.EXCEPTION_ERROR, e, msg);
-            integrityAudit.setThreadInitialized(false);
+            handleAuditLoopException(e);
         }
 
         dbDao.destroy();
@@ -160,16 +161,22 @@ public class AuditThread extends Thread {
         logger.info("AuditThread.run: Exiting");
     }
 
+    private void handleAuditLoopException(Exception exception) {
+        String msg = "AuditThread.run: Could not start audit loop. Exception thrown; message=" + exception.getMessage();
+        logger.error(MessageCodes.EXCEPTION_ERROR, exception, msg);
+        integrityAudit.setThreadInitialized(false);
+    }
+
     private void runUntilInterrupted() throws InterruptedException {
-        boolean auditCompleted = false;
+        var auditCompleted = false;
 
-        DbAudit dbAudit = new DbAudit(dbDao);
+        var dbAudit = new DbAudit(dbDao);
 
         IntegrityAuditEntity entityCurrentlyDesignated;
         IntegrityAuditEntity thisEntity;
         integrityAudit.setThreadInitialized(true); // An exception will set it to false
 
-        boolean interrupted = false;
+        var interrupted = false;
 
         while (!interrupted) {
             try {
@@ -210,6 +217,7 @@ public class AuditThread extends Thread {
                 if (isInterruptedException(e)) {
                     String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() + "; Stopping.";
                     logger.error(MessageCodes.EXCEPTION_ERROR, e, msg);
+                    Thread.currentThread().interrupt();
                     interrupted = true;
 
                 } else {
@@ -347,10 +355,10 @@ public class AuditThread extends Thread {
 
         IntegrityAuditEntity thisEntity = null;
 
-        int designatedEntityIndex = -1;
-        int entityIndex = 0;
-        int priorCandidateIndex = -1;
-        int subsequentCandidateIndex = -1;
+        var designatedEntityIndex = -1;
+        var entityIndex = 0;
+        var priorCandidateIndex = -1;
+        var subsequentCandidateIndex = -1;
 
         for (IntegrityAuditEntity integrityAuditEntity : integrityAuditEntityList) {
 
@@ -561,7 +569,7 @@ public class AuditThread extends Thread {
          */
         List<IntegrityAuditEntity> integrityAuditEntityList =
                 dbDao.getIntegrityAuditEntities(this.persistenceUnit, this.nodeType);
-        int listSize = integrityAuditEntityList.size();
+        var listSize = integrityAuditEntityList.size();
         if (logger.isDebugEnabled()) {
             logger.debug("getIntegrityAuditEntityList: Got " + listSize + " IntegrityAuditEntity records");
         }
@@ -634,10 +642,10 @@ public class AuditThread extends Thread {
                     + integrityAuditEntity.getLastUpdated());
         }
 
-        boolean stale = false;
+        var stale = false;
 
-        Date currentTime = AuditorTime.getInstance().getDate();
-        Date lastUpdated = integrityAuditEntity.getLastUpdated();
+        var currentTime = AuditorTime.getInstance().getDate();
+        var lastUpdated = integrityAuditEntity.getLastUpdated();
 
         /*
          * If lastUpdated is null, we assume that the audit never ran for that node.
@@ -690,8 +698,8 @@ public class AuditThread extends Thread {
 
         long timeDifference;
 
-        Date currentTime = AuditorTime.getInstance().getDate();
-        Date lastUpdated = thisEntity.getLastUpdated();
+        var currentTime = AuditorTime.getInstance().getDate();
+        var lastUpdated = thisEntity.getLastUpdated();
 
         long lastUpdatedTime = lastUpdated.getTime();
         timeDifference = currentTime.getTime() - lastUpdatedTime;
index f69173f..c8ca41c 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Integrity Audit
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -123,7 +123,7 @@ public class DbAudit {
          * nodes. Since the audit is run in a round-robin, every instance will be compared against
          * every other instance.
          */
-        IntegrityAuditEntity myIae = dbDao.getMyIntegrityAuditEntity();
+        var myIae = dbDao.getMyIntegrityAuditEntity();
 
         if (myIae == null) {
 
@@ -267,7 +267,7 @@ public class DbAudit {
      * @return DAO properties for the given DB node
      */
     private Properties getTheirDaoProperties(IntegrityAuditEntity iae) {
-        Properties theirProperties = new Properties();
+        var theirProperties = new Properties();
 
         theirProperties.put(IntegrityAuditProperties.DB_DRIVER, iae.getJdbcDriver());
         theirProperties.put(IntegrityAuditProperties.DB_URL, iae.getJdbcUrl());
@@ -294,7 +294,7 @@ public class DbAudit {
             logger.debug("dbAudit: Second comparison; traversing classNameSet, size=" + classNameSet.size());
         }
 
-        int errorCount = 0;
+        var errorCount = 0;
 
         for (String clazzName : classNameSet) {
 
@@ -327,7 +327,7 @@ public class DbAudit {
                     IntegrityAuditEntity myIae, String clazzName, Set<Object> keySet, Map<Object, Object> myEntries)
                     throws IntegrityAuditException {
 
-        int errorCount = 0;
+        var errorCount = 0;
         for (IntegrityAuditEntity iae : iaeList) {
             if (iae.getId() == myIae.getId()) {
                 if (logger.isDebugEnabled()) {
@@ -363,7 +363,7 @@ public class DbAudit {
             return 0;
         }
 
-        StringBuilder keyBuilder = new StringBuilder();
+        var keyBuilder = new StringBuilder();
         for (Object key : misMatchedKeySet) {
             keyBuilder.append(key.toString());
             keyBuilder.append(", ");
index ff4d297..27d035f 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Integrity Audit
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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,14 +31,11 @@ import javax.persistence.EntityManager;
 import javax.persistence.EntityManagerFactory;
 import javax.persistence.EntityTransaction;
 import javax.persistence.Persistence;
-import javax.persistence.PersistenceUnitUtil;
 import javax.persistence.Query;
 import javax.persistence.TypedQuery;
-import javax.persistence.criteria.CriteriaBuilder;
 import javax.persistence.criteria.CriteriaQuery;
 import javax.persistence.criteria.Root;
 import javax.persistence.metamodel.ManagedType;
-import javax.persistence.metamodel.Metamodel;
 import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
 import org.onap.policy.common.logging.flexlogger.FlexLogger;
 import org.onap.policy.common.logging.flexlogger.Logger;
@@ -132,7 +129,7 @@ public class DbDao {
      */
     private void validateProperties(String resourceName, String persistenceUnit, Properties properties)
             throws IntegrityAuditPropertiesException {
-        StringBuilder badparams = new StringBuilder();
+        var badparams = new StringBuilder();
         if (IntegrityAudit.parmsAreBad(resourceName, persistenceUnit, properties, badparams)) {
             String msg = "DbDao: Bad parameters: badparams" + badparams;
             throw new IntegrityAuditPropertiesException(msg);
@@ -158,9 +155,9 @@ public class DbDao {
     public Map<Object, Object> getAllMyEntries(String className) {
         logger.debug("getAllMyEntries: Entering, className=" + className);
         HashMap<Object, Object> resultMap = new HashMap<>();
-        EntityManager em = emf.createEntityManager();
+        var em = emf.createEntityManager();
         try {
-            CriteriaBuilder cb = em.getCriteriaBuilder();
+            var cb = em.getCriteriaBuilder();
             CriteriaQuery<Object> cq = cb.createQuery();
             Root<?> rootEntry = cq.from(Class.forName(className));
             CriteriaQuery<Object> all = cq.select(rootEntry);
@@ -168,7 +165,7 @@ public class DbDao {
             List<Object> objectList = allQuery.getResultList();
             // Now create the map
 
-            PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
+            var util = emf.getPersistenceUnitUtil();
             for (Object o : objectList) {
                 Object key = util.getIdentifier(o);
                 resultMap.put(key, o);
@@ -192,7 +189,7 @@ public class DbDao {
         logger.debug("getAllMyEntries: Entering, className=" + className + ",\n keySet=" + keySet);
 
         HashMap<Object, Object> resultMap = new HashMap<>();
-        EntityManager em = emf.createEntityManager();
+        var em = emf.createEntityManager();
         try {
             Class<?> clazz = Class.forName(className);
             for (Object key : keySet) {
@@ -221,17 +218,17 @@ public class DbDao {
         logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n className=" + className);
         HashMap<Object, Object> resultMap = new HashMap<>();
 
-        EntityManagerFactory theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
-        EntityManager em = theEmf.createEntityManager();
+        var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
+        var em = theEmf.createEntityManager();
         try {
-            CriteriaBuilder cb = em.getCriteriaBuilder();
+            var cb = em.getCriteriaBuilder();
             CriteriaQuery<Object> cq = cb.createQuery();
             Root<?> rootEntry = cq.from(Class.forName(className));
             CriteriaQuery<Object> all = cq.select(rootEntry);
             TypedQuery<Object> allQuery = em.createQuery(all);
             List<Object> objectList = allQuery.getResultList();
 
-            PersistenceUnitUtil util = theEmf.getPersistenceUnitUtil();
+            var util = theEmf.getPersistenceUnitUtil();
             for (Object o : objectList) {
                 Object key = util.getIdentifier(o);
                 resultMap.put(key, o);
@@ -262,8 +259,8 @@ public class DbDao {
             Set<Object> keySet) {
         logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n properties= " + properties
                 + ",\n className=" + className + ",\n keySet= " + keySet);
-        EntityManagerFactory theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
-        EntityManager em = theEmf.createEntityManager();
+        var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
+        var em = theEmf.createEntityManager();
         HashMap<Object, Object> resultMap = new HashMap<>();
         try {
             Class<?> clazz = Class.forName(className);
@@ -296,7 +293,7 @@ public class DbDao {
         logger.debug("getIntegrityAuditEntities: Entering, persistenceUnit=" + persistenceUnit + ",\n nodeType= "
                 + nodeType);
         try {
-            EntityManager em = emf.createEntityManager();
+            var em = emf.createEntityManager();
             // Start a transaction
             EntityTransaction et = em.getTransaction();
 
@@ -304,7 +301,7 @@ public class DbDao {
 
             // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
             // found, create a new entry
-            Query iaequery = em
+            var iaequery = em
                     .createQuery("Select i from IntegrityAuditEntity i where i.persistenceUnit=:pu and i.nodeType=:nt");
             iaequery.setParameter("pu", persistenceUnit);
             iaequery.setParameter("nt", nodeType);
@@ -357,7 +354,7 @@ public class DbDao {
      */
     public IntegrityAuditEntity getIntegrityAuditEntity(long id) throws DbDaoTransactionException {
         try {
-            EntityManager em = emf.createEntityManager();
+            var em = emf.createEntityManager();
 
             // Start a transaction
             EntityTransaction et = em.getTransaction();
@@ -385,7 +382,7 @@ public class DbDao {
     public Set<String> getPersistenceClassNames() {
         logger.debug("DbDao: getPersistenceClassNames() entry");
         HashSet<String> returnList = new HashSet<>();
-        final Metamodel mm = emf.getMetamodel();
+        final var mm = emf.getMetamodel();
         logger.debug("\n" + persistenceUnit + " persistence unit classes:");
         for (final ManagedType<?> managedType : mm.getManagedTypes()) {
             Class<?> clazz = managedType.getJavaType();
@@ -496,7 +493,7 @@ public class DbDao {
                     BiConsumer<EntityManager, IntegrityAuditEntity> updater) throws DbDaoTransactionException {
         try {
 
-            EntityManager em = emf.createEntityManager();
+            var em = emf.createEntityManager();
 
             // Start a transaction
             EntityTransaction et = em.getTransaction();
@@ -582,7 +579,7 @@ public class DbDao {
                 throw new DbDaoTransactionException(msg);
             }
 
-            EntityManager em = emf.createEntityManager();
+            var em = emf.createEntityManager();
             // Start a transaction
             EntityTransaction et = em.getTransaction();
 
@@ -590,7 +587,7 @@ public class DbDao {
 
             // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
             // found, create a new entry
-            Query iaequery = em.createQuery("Delete from IntegrityAuditEntity");
+            var iaequery = em.createQuery("Delete from IntegrityAuditEntity");
 
             int returnCode = iaequery.executeUpdate();
 
@@ -650,7 +647,7 @@ public class DbDao {
                 /*
                  * Define query
                  */
-                Query query = em.createQuery(
+                var query = em.createQuery(
                         "Select i from IntegrityAuditEntity i where i.persistenceUnit=:pu and i.nodeType=:nt");
                 query.setParameter("pu", persistenceUnit);
                 query.setParameter("nt", nodeType);
@@ -703,7 +700,7 @@ public class DbDao {
                 continue;
             }
 
-            IntegrityAuditEntity integrityAuditEntity = (IntegrityAuditEntity) o;
+            var integrityAuditEntity = (IntegrityAuditEntity) o;
             if (integrityAuditEntity.getResourceName().equals(resourceName)) {
                 if (logger.isDebugEnabled()) {
                     logger.debug("changeDesignated: Designating resourceName="
index 41aea11..10900e3 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Integrity Audit
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -68,7 +68,7 @@ public class IntegrityAudit {
             throws IntegrityAuditException {
 
         logger.info("Constructor: Entering and checking for nulls");
-        StringBuilder parmList = new StringBuilder();
+        var parmList = new StringBuilder();
         if (parmsAreBad(resourceName, persistenceUnit, properties, parmList)) {
             logger.error("Constructor: Parms contain nulls; cannot run audit for resourceName=" + resourceName
                     + ", persistenceUnit=" + persistenceUnit + ", bad parameters: " + parmList);
index 121b28b..1c8277c 100644 (file)
@@ -100,7 +100,7 @@ public class IntegrityAuditEntity implements Serializable {
      */
     @PrePersist
     public void prePersist() {
-        Date date = AuditorTime.getInstance().getDate();
+        var date = AuditorTime.getInstance().getDate();
         this.createdDate = date;
         this.lastUpdated = date;
     }
index 4728fe8..6c48a6d 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Integrity Audit
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -26,6 +26,7 @@ import static org.junit.Assert.assertFalse;
 
 import java.util.List;
 import java.util.Properties;
+import java.util.regex.Pattern;
 import javax.persistence.EntityManager;
 import javax.persistence.EntityManagerFactory;
 import javax.persistence.Persistence;
@@ -51,6 +52,7 @@ public class DbAuditTest extends IntegrityAuditTestBase {
 
     private static Logger logger = FlexLogger.getLogger(DbAuditTest.class);
 
+    private static final Pattern COMMA_PAT = Pattern.compile(",");
     private static final String RESOURCE_NAME = "pdp1";
 
     private EntityManagerFactory emf2;
@@ -238,7 +240,7 @@ public class DbAuditTest extends IntegrityAuditTestBase {
         assertFalse(dbglog.getExtracted().isEmpty());
 
         String mismatchIndex = dbglog.getExtracted().get(dbglog.getExtracted().size() - 1);
-        int mismatchEntries = mismatchIndex.trim().split(",").length;
+        int mismatchEntries = COMMA_PAT.split(mismatchIndex.trim()).length;
         logger.info("mismatchTest: mismatchIndex found: '" + mismatchIndex + "'" + " mismatachEntries = "
                 + mismatchEntries);
 
index 6210392..9a6616e 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Integrity Monitor
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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,6 +34,7 @@ import java.util.function.Consumer;
 import java.util.function.IntConsumer;
 import java.util.function.LongConsumer;
 import java.util.function.Supplier;
+import java.util.regex.Pattern;
 import javax.management.JMX;
 import javax.management.MBeanServerConnection;
 import javax.persistence.EntityManager;
@@ -42,7 +43,6 @@ import javax.persistence.EntityTransaction;
 import javax.persistence.FlushModeType;
 import javax.persistence.LockModeType;
 import javax.persistence.Persistence;
-import javax.persistence.Query;
 import javax.persistence.TypedQuery;
 import org.apache.commons.lang3.StringUtils;
 import org.eclipse.persistence.config.PersistenceUnitProperties;
@@ -63,6 +63,9 @@ public class IntegrityMonitor {
 
     private static final Logger logger = LoggerFactory.getLogger(IntegrityMonitor.class.getName());
 
+    private static final Pattern COMMA_PAT = Pattern.compile(",");
+    private static final Pattern SEMICOLON_PAT = Pattern.compile(";");
+
     // only allow one instance of IntegrityMonitor
     private static IntegrityMonitor instance = null;
 
@@ -212,7 +215,7 @@ public class IntegrityMonitor {
         // singleton check since this constructor can be called from a child or
         // sub-class
         if (instance != null) {
-            String msg = "IM object exists and only one instance allowed";
+            var msg = "IM object exists and only one instance allowed";
             logger.error("{}", msg);
             throw new IntegrityMonitorException("IntegrityMonitor constructor exception: " + msg);
         }
@@ -466,7 +469,7 @@ public class IntegrityMonitor {
     private static String getJmxUrlFromProps() throws IntegrityMonitorException {
 
         // get the jmx remote port and construct the JMX URL
-        Properties systemProps = System.getProperties();
+        var systemProps = System.getProperties();
         String jmxPort = systemProps.getProperty("com.sun.management.jmxremote.port");
         String jmxErrMsg;
         if (jmxPort == null) {
@@ -475,7 +478,7 @@ public class IntegrityMonitor {
             throw new IntegrityMonitorException("getJmxUrl exception: " + jmxErrMsg);
         }
 
-        int port = 0;
+        var port = 0;
         try {
             port = Integer.parseInt(jmxPort);
         } catch (NumberFormatException e) {
@@ -490,12 +493,12 @@ public class IntegrityMonitor {
                 jmxFqdn = InetAddress.getLocalHost().getCanonicalHostName();
             }
         } catch (Exception e) {
-            String msg = "getJmxUrl could not get hostname";
+            var msg = "getJmxUrl could not get hostname";
             logger.error("{}", msg, e);
             throw new IntegrityMonitorException("getJmxUrl Exception: " + msg);
         }
         if (jmxFqdn == null) {
-            String msg = "getJmxUrl encountered null hostname";
+            var msg = "getJmxUrl encountered null hostname";
             logger.error("{}", msg);
             throw new IntegrityMonitorException("getJmxUrl error: " + msg);
         }
@@ -663,7 +666,7 @@ public class IntegrityMonitor {
     private void checkForwardProgress(String dep, ForwardProgressEntity forwardProgressEntity,
             StateManagementEntity stateManagementEntity) {
         if (forwardProgressEntity != null && stateManagementEntity != null) {
-            Date date = MonitorTime.getInstance().getDate();
+            var date = MonitorTime.getInstance().getDate();
             long diffMs = date.getTime() - forwardProgressEntity.getLastUpdated().getTime();
             logger.debug("IntegrityMonitor.stateCheck(): diffMs = {}", diffMs);
 
@@ -762,7 +765,7 @@ public class IntegrityMonitor {
         ArrayList<ForwardProgressEntity> fpList = new ArrayList<>();
 
         withinTransaction("getAllForwardProgessEntity DB read failed with exception: ", () -> {
-            Query fquery = em.createQuery("Select e from ForwardProgressEntity e");
+            var fquery = em.createQuery("Select e from ForwardProgressEntity e");
             fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList()
                     .forEach(obj -> fpList.add((ForwardProgressEntity) obj));
             return null;
@@ -773,7 +776,7 @@ public class IntegrityMonitor {
         }
 
         logger.debug("getAllForwardProgressEntity: fpList.size(): {}", fpList.size());
-        int index = 0;
+        var index = 0;
         for (ForwardProgressEntity fpe : fpList) {
             logger.debug("getAllForwardProgressEntity: fpList.get({}).getResourceName(): {}", index++,
                     fpe.getResourceName());
@@ -861,7 +864,7 @@ public class IntegrityMonitor {
         synchronized (dependencyCheckLock) {
 
             // Start with the error message empty
-            StringBuilder errorMsg = new StringBuilder();
+            var errorMsg = new StringBuilder();
 
             /*
              * Before we check dependency groups we need to check subsystemTest.
@@ -948,7 +951,7 @@ public class IntegrityMonitor {
      * @return {@code true} if the dependencies are OK, {@code false} otherwise
      */
     private boolean checkDependencies(StringBuilder errorMsg) {
-        boolean dependencyOk = true;
+        var dependencyOk = true;
 
         // check state of resources in dependency groups
         for (String group : depGroups) {
@@ -978,12 +981,12 @@ public class IntegrityMonitor {
             // ignore empty group
             return false;
         }
-        String[] dependencies = group.split(",");
+        String[] dependencies = COMMA_PAT.split(group);
         if (logger.isDebugEnabled()) {
             logger.debug("group dependencies = {}", Arrays.toString(dependencies));
         }
-        int realDepCount = 0;
-        int failDepCount = 0;
+        var realDepCount = 0;
+        var failDepCount = 0;
         for (String dep : dependencies) {
             dep = dep.trim();
             if (dep.isEmpty()) {
@@ -1170,20 +1173,16 @@ public class IntegrityMonitor {
                      * An entity has reported that it is not well. We must not allow the the forward progress counter to
                      * advance.
                      */
-                    String msg = "allNotWellMap:";
-                    for (Entry<String, String> entry : allNotWellMap.entrySet()) {
-                        msg = msg.concat("\nkey = " + entry.getKey() + " msg = " + entry.getValue());
-                    }
+                    var msg = new StringBuilder("allNotWellMap:");
+                    buildMapString(msg, allNotWellMap);
                     logger.error("endTransaction: allNotWellMap is NOT EMPTY.  Not advancing forward"
                             + "progress counter. \n{}\n", msg);
                     return;
                 }
 
                 if (logger.isDebugEnabled() && getAllSeemsWellMap() != null && !(getAllSeemsWellMap().isEmpty())) {
-                    String msg = "allSeemsWellMap:";
-                    for (Entry<String, String> entry : allSeemsWellMap.entrySet()) {
-                        msg = msg.concat("\nkey = " + entry.getKey() + " msg = " + entry.getValue());
-                    }
+                    var msg = new StringBuilder("allSeemsWellMap:");
+                    buildMapString(msg, allSeemsWellMap);
                     logger.debug("endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY.  "
                             + "Advancing forward progress counter. \n{}\n", msg);
                 }
@@ -1193,6 +1192,15 @@ public class IntegrityMonitor {
         }
     }
 
+    private void buildMapString(StringBuilder msg, Map<String, String> map) {
+        for (Entry<String, String> entry : map.entrySet()) {
+            msg.append("\nkey = ");
+            msg.append(entry.getKey());
+            msg.append(" msg = ");
+            msg.append(entry.getValue());
+        }
+    }
+
     // update FP count in DB with local FP count
     private void writeFpc() throws IntegrityMonitorException {
 
@@ -1280,7 +1288,7 @@ public class IntegrityMonitor {
         // site_1.pdp_2
         String depGroupsValue = prop.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS);
         if (!StringUtils.isBlank(depGroupsValue)) {
-            depGroups = depGroupsValue.split(";");
+            depGroups = SEMICOLON_PAT.split(depGroupsValue);
             if (logger.isDebugEnabled()) {
                 logger.debug("dependency groups property = {}", Arrays.toString(depGroups));
             }
@@ -1478,7 +1486,7 @@ public class IntegrityMonitor {
             return;
         }
 
-        Date date = MonitorTime.getInstance().getDate();
+        var date = MonitorTime.getInstance().getDate();
         long timeSinceLastStateAudit = date.getTime() - lastStateAuditTime.getTime();
         if (timeSinceLastStateAudit < stateAuditIntervalMs) {
             logger.debug("IntegrityMonitor.stateAudit(): Not time to run. returning");
@@ -1497,7 +1505,7 @@ public class IntegrityMonitor {
      */
     public void executeStateAudit() {
         logger.debug("IntegrityMonitor.executeStateAudit(): entry");
-        Date date = MonitorTime.getInstance().getDate();
+        var date = MonitorTime.getInstance().getDate();
 
         // Get all entries in the forwardprogressentity table
         List<ForwardProgressEntity> fpList = getAllForwardProgressEntity();
@@ -1606,7 +1614,7 @@ public class IntegrityMonitor {
     private void disableEntity(String dep) {
         try {
             // create instance of StateMangement class for dependent
-            StateManagement depStateManager = new StateManagement(emf, dep);
+            var depStateManager = new StateManagement(emf, dep);
             if (!depStateManager.getOpState().equals(StateManagement.DISABLED)) {
                 logger.debug("Forward progress not detected for dependent resource {}. Setting dependent's "
                         + "state to disable failed.", dep);
@@ -1742,7 +1750,7 @@ public class IntegrityMonitor {
         logger.debug("executeRefreshStateAudit(): entry");
         synchronized (refreshStateAuditLock) {
             logger.debug("refreshStateAudit: entry");
-            Date now = MonitorTime.getInstance().getDate();
+            var now = MonitorTime.getInstance().getDate();
             long nowMs = now.getTime();
             long lastTimeMs = refreshStateAuditLastRunDate.getTime();
             logger.debug("refreshStateAudit: ms since last run = {}", nowMs - lastTimeMs);
index feca72f..9ee095f 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Integrity Monitor
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -155,13 +155,13 @@ public class StateManagement {
                             resourceName);
             logger.debug("StateManagement: {}() operation started, resourceName = {}", methodName, resourceName);
 
-            final EntityManager em = emf.createEntityManager();
+            final var em = emf.createEntityManager();
 
-            try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
+            try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
 
                 logger.debug(FIND_MESSAGE, resourceName);
 
-                final StateManagementEntity sm = findStateManagementEntity(em, resourceName);
+                final var sm = findStateManagementEntity(em, resourceName);
                 String changed = updateState.update(sm);
 
                 em.persist(sm);
@@ -197,7 +197,7 @@ public class StateManagement {
                     throws StateManagementException {
 
         setState(actionName, resourceName, sm -> {
-            final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
+            final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
                             sm.getAvailStatus(), sm.getStandbyStatus(), actionName);
 
             sm.setAdminState(stateElement.getEndingAdminState());
@@ -292,7 +292,7 @@ public class StateManagement {
         AtomicReference<String> newStatus = new AtomicReference<>();
 
         setState(PROMOTE_ACTION, resourceName, sm -> {
-            final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
+            final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
                             sm.getAvailStatus(), sm.getStandbyStatus(), PROMOTE_ACTION);
 
             sm.setAdminState(stateElement.getEndingAdminState());
@@ -357,8 +357,8 @@ public class StateManagement {
 
         logger.debug("StateManagement(6/1/16): {} for resourceName {}", methodName, resourceName);
 
-        final EntityManager em = emf.createEntityManager();
-        try (final EntityMgrCloser emc = new EntityMgrCloser(em)) {
+        final var em = emf.createEntityManager();
+        try (final var emc = new EntityMgrCloser(em)) {
             final TypedQuery<StateManagementEntity> query =
                     em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
 
@@ -369,7 +369,7 @@ public class StateManagement {
                     query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
             if (!resourceList.isEmpty()) {
                 // exist
-                final StateManagementEntity stateManagementEntity = resourceList.get(0);
+                final var stateManagementEntity = resourceList.get(0);
                 // refresh the object from DB in case cached data was returned
                 em.refresh(stateManagementEntity);
                 function.accept(stateManagementEntity);
@@ -458,14 +458,14 @@ public class StateManagement {
                     query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
             if (!resourceList.isEmpty()) {
                 // exist
-                final StateManagementEntity stateManagementEntity = resourceList.get(0);
+                final var stateManagementEntity = resourceList.get(0);
                 // refresh the object from DB in case cached data was returned
                 em.refresh(stateManagementEntity);
                 stateManagementEntity.setModifiedDate(MonitorTime.getInstance().getDate());
                 return stateManagementEntity;
             } else {
                 // not exist - create one
-                final StateManagementEntity stateManagementEntity = new StateManagementEntity();
+                final var stateManagementEntity = new StateManagementEntity();
                 stateManagementEntity.setResourceName(otherResourceName);
                 stateManagementEntity.setAdminState(UNLOCKED);
                 stateManagementEntity.setOpState(ENABLED);
@@ -474,8 +474,7 @@ public class StateManagement {
                 return stateManagementEntity;
             }
         } catch (final Exception ex) {
-            final String message = "findStateManagementEntity exception";
-            throw new EntityRetrievalException(message, ex);
+            throw new EntityRetrievalException("findStateManagementEntity exception", ex);
         }
     }
 
@@ -489,9 +488,9 @@ public class StateManagement {
         /*
          * Start transaction
          */
-        final EntityManager em = emf.createEntityManager();
+        final var em = emf.createEntityManager();
 
-        try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
+        try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
             final TypedQuery<StateManagementEntity> stateManagementEntityListQuery =
                     em.createQuery("SELECT p FROM StateManagementEntity p", StateManagementEntity.class);
             final List<StateManagementEntity> stateManagementEntityList = stateManagementEntityListQuery
index 3542aa2..17897d8 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Integrity Monitor
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -29,6 +29,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
+import java.util.regex.Pattern;
 import org.apache.commons.lang3.tuple.Pair;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -37,6 +38,8 @@ import org.slf4j.LoggerFactory;
  * The StateTransition class coordinates all state transitions.
  */
 public class StateTransition {
+    private static final Pattern COMMA_PAT = Pattern.compile(",");
+
     private static final String DEPENDENCY_FAILED = "dependency.failed";
 
     private static final String ANY_DISABLED_ANY_COLDSTANDBY = "${1},disabled,${3},coldstandby,";
@@ -165,7 +168,7 @@ public class StateTransition {
         }
 
 
-        StateElement stateElement = new StateElement();
+        var stateElement = new StateElement();
 
         // dependency,failed is stored as dependency.failed in StateTable
         String availStatus2 = availStatus;
@@ -177,7 +180,7 @@ public class StateTransition {
         String value = STATE_TABLE.get(key);
 
         if (value != null) {
-            String[] parts = value.split(",", 5);
+            String[] parts = COMMA_PAT.split(value, 5);
             stateElement.setEndingAdminState(parts[0].trim());
             stateElement.setEndingOpState(parts[1].trim());
             stateElement.setEndingAvailStatus(parts[2].trim().replace(".", ","));
index cf7a968..8cbdaa7 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Integrity Monitor
  * ================================================================================
- * Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018, 2020-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.
@@ -87,13 +87,13 @@ public class ComponentAdmin implements ComponentAdminMBean {
         try {
             logger.debug("Registering {} MBean", name);
 
-            MBeanServer mbeanServer = findMBeanServer();
+            var mbeanServer = findMBeanServer();
 
             if (mbeanServer == null) {
                 return;
             }
 
-            ObjectName objectName = new ObjectName(name);
+            var objectName = new ObjectName(name);
 
             if (mbeanServer.isRegistered(objectName)) {
                 logger.debug("Unregistering a previously registered {} MBean", name);
index 8815931..2f9544e 100644 (file)
@@ -76,7 +76,7 @@ public class ForwardProgressEntity implements Serializable {
      */
     @PrePersist
     public void prePersist() {
-        Date date = MonitorTime.getInstance().getDate();
+        var date = MonitorTime.getInstance().getDate();
         this.createdDate = date;
         this.lastUpdated = date;
         this.fpcCount = 0;
index 14dce06..858a3f7 100644 (file)
@@ -73,7 +73,7 @@ public class ImTestEntity implements Serializable {
      */
     @PrePersist
     public void prePersist() {
-        Date date = MonitorTime.getInstance().getDate();
+        var date = MonitorTime.getInstance().getDate();
         this.createdDate = date;
         this.modifiedDate = date;
     }
index 20237af..0e654d3 100644 (file)
@@ -82,7 +82,7 @@ public class ResourceRegistrationEntity implements Serializable {
      */
     @PrePersist
     public void prePersist() {
-        Date date = MonitorTime.getInstance().getDate();
+        var date = MonitorTime.getInstance().getDate();
         this.createdDate = date;
         this.lastUpdated = date;
     }
index 3067781..b13d3a7 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * Integrity Monitor
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -103,7 +103,7 @@ public class StateManagementEntity implements Serializable {
      * @return a new StateManagementEntity
      */
     public static StateManagementEntity clone(StateManagementEntity sm) {
-        StateManagementEntity newStateManagementEntity = new StateManagementEntity();
+        var newStateManagementEntity = new StateManagementEntity();
         newStateManagementEntity.setResourceName(sm.getResourceName());
         newStateManagementEntity.setAdminState(sm.getResourceName());
         newStateManagementEntity.setOpState(sm.getOpState());
index b86532f..cf89762 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -365,7 +365,7 @@ class TopicEndpointProxy implements TopicEndpoint {
 
         final List<Startable> endpoints = this.getEndpoints();
 
-        boolean success = true;
+        var success = true;
         for (final Startable endpoint : endpoints) {
             try {
                 success = endpoint.start() && success;
@@ -391,7 +391,7 @@ class TopicEndpointProxy implements TopicEndpoint {
 
         final List<Startable> endpoints = this.getEndpoints();
 
-        boolean success = true;
+        var success = true;
         for (final Startable endpoint : endpoints) {
             try {
                 success = endpoint.stop() && success;
index 6f0753b..30618d9 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -24,6 +24,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Properties;
+import java.util.regex.Pattern;
 import org.apache.commons.lang3.StringUtils;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.InlineDmaapTopicSink;
@@ -38,6 +39,7 @@ import org.slf4j.LoggerFactory;
  */
 class IndexedDmaapTopicSinkFactory implements DmaapTopicSinkFactory {
 
+    private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
     private static final String MISSING_TOPIC = "A topic must be provided";
 
     /**
@@ -62,7 +64,7 @@ class IndexedDmaapTopicSinkFactory implements DmaapTopicSinkFactory {
                 return dmaapTopicWriters.get(busTopicParams.getTopic());
             }
 
-            DmaapTopicSink dmaapTopicSink = makeSink(busTopicParams);
+            var dmaapTopicSink = makeSink(busTopicParams);
 
             if (busTopicParams.isManaged()) {
                 dmaapTopicWriters.put(busTopicParams.getTopic(), dmaapTopicSink);
@@ -93,7 +95,7 @@ class IndexedDmaapTopicSinkFactory implements DmaapTopicSinkFactory {
 
         List<DmaapTopicSink> newDmaapTopicSinks = new ArrayList<>();
         synchronized (this) {
-            for (String topic : writeTopics.split("\\s*,\\s*")) {
+            for (String topic : COMMA_SPACE_PAT.split(writeTopics)) {
                 addTopic(newDmaapTopicSinks, properties, topic);
             }
             return newDmaapTopicSinks;
@@ -108,7 +110,7 @@ class IndexedDmaapTopicSinkFactory implements DmaapTopicSinkFactory {
 
         String topicPrefix = PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic;
 
-        PropertyUtils props = new PropertyUtils(properties, topicPrefix,
+        var props = new PropertyUtils(properties, topicPrefix,
             (name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
 
         String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
@@ -117,7 +119,7 @@ class IndexedDmaapTopicSinkFactory implements DmaapTopicSinkFactory {
             return;
         }
 
-        DmaapTopicSink dmaapTopicSink = this.build(DmaapPropertyUtils.makeBuilder(props, topic, servers)
+        var dmaapTopicSink = this.build(DmaapPropertyUtils.makeBuilder(props, topic, servers)
                 .partitionId(props.getString(PolicyEndPointProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX, null))
                 .build());
 
index d7f4695..8c168f7 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -24,6 +24,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Properties;
+import java.util.regex.Pattern;
 import org.apache.commons.lang3.StringUtils;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.SingleThreadedDmaapTopicSource;
@@ -38,6 +39,7 @@ import org.slf4j.LoggerFactory;
  */
 
 class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory {
+    private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
     private static final String MISSING_TOPIC = "A topic must be provided";
 
     /**
@@ -62,7 +64,7 @@ class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory {
                 return dmaapTopicSources.get(busTopicParams.getTopic());
             }
 
-            DmaapTopicSource dmaapTopicSource = makeSource(busTopicParams);
+            var dmaapTopicSource = makeSource(busTopicParams);
 
             if (busTopicParams.isManaged()) {
                 dmaapTopicSources.put(busTopicParams.getTopic(), dmaapTopicSource);
@@ -82,7 +84,7 @@ class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory {
 
         List<DmaapTopicSource> dmaapTopicSourceLst = new ArrayList<>();
         synchronized (this) {
-            for (String topic : readTopics.split("\\s*,\\s*")) {
+            for (String topic : COMMA_SPACE_PAT.split(readTopics)) {
                 addTopic(dmaapTopicSourceLst, properties, topic);
             }
         }
@@ -117,7 +119,7 @@ class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory {
 
         String topicPrefix = PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic;
 
-        PropertyUtils props = new PropertyUtils(properties, topicPrefix,
+        var props = new PropertyUtils(properties, topicPrefix,
             (name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
 
         String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
index 150a02c..ad2c2e2 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -24,6 +24,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Properties;
+import java.util.regex.Pattern;
 import org.apache.commons.lang3.StringUtils;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.InlineUebTopicSink;
@@ -37,6 +38,7 @@ import org.slf4j.LoggerFactory;
  * Factory of UEB Reader Topics indexed by topic name.
  */
 class IndexedUebTopicSinkFactory implements UebTopicSinkFactory {
+    private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
     private static final String MISSING_TOPIC = "A topic must be provided";
 
     /**
@@ -99,7 +101,7 @@ class IndexedUebTopicSinkFactory implements UebTopicSinkFactory {
 
         List<UebTopicSink> newUebTopicSinks = new ArrayList<>();
         synchronized (this) {
-            for (String topic : writeTopics.split("\\s*,\\s*")) {
+            for (String topic : COMMA_SPACE_PAT.split(writeTopics)) {
                 addTopic(newUebTopicSinks, topic, properties);
             }
             return newUebTopicSinks;
@@ -114,7 +116,7 @@ class IndexedUebTopicSinkFactory implements UebTopicSinkFactory {
 
         String topicPrefix = PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic;
 
-        PropertyUtils props = new PropertyUtils(properties, topicPrefix,
+        var props = new PropertyUtils(properties, topicPrefix,
             (name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
 
         String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
@@ -194,9 +196,7 @@ class IndexedUebTopicSinkFactory implements UebTopicSinkFactory {
 
     @Override
     public String toString() {
-        StringBuilder builder = new StringBuilder();
-        builder.append("IndexedUebTopicSinkFactory []");
-        return builder.toString();
+        return "IndexedUebTopicSinkFactory []";
     }
 
 }
index 5bdc8ab..367d4ab 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -24,6 +24,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Properties;
+import java.util.regex.Pattern;
 import org.apache.commons.lang3.StringUtils;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.SingleThreadedUebTopicSource;
@@ -37,6 +38,7 @@ import org.slf4j.LoggerFactory;
  * Factory of UEB Source Topics indexed by topic name.
  */
 class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
+    private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
     private static final String MISSING_TOPIC = "A topic must be provided";
 
     /**
@@ -64,7 +66,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
                 return uebTopicSources.get(busTopicParams.getTopic());
             }
 
-            UebTopicSource uebTopicSource = makeSource(busTopicParams);
+            var uebTopicSource = makeSource(busTopicParams);
 
             if (busTopicParams.isManaged()) {
                 uebTopicSources.put(busTopicParams.getTopic(), uebTopicSource);
@@ -85,7 +87,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
 
         List<UebTopicSource> newUebTopicSources = new ArrayList<>();
         synchronized (this) {
-            for (String topic : readTopics.split("\\s*,\\s*")) {
+            for (String topic : COMMA_SPACE_PAT.split(readTopics)) {
                 addTopic(newUebTopicSources, topic, properties);
             }
         }
@@ -120,7 +122,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
 
         String topicPrefix = PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic;
 
-        PropertyUtils props = new PropertyUtils(properties, topicPrefix,
+        var props = new PropertyUtils(properties, topicPrefix,
             (name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
 
         String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
@@ -129,7 +131,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
             return;
         }
 
-        UebTopicSource uebTopicSource = this.build(UebPropertyUtils.makeBuilder(props, topic, servers)
+        var uebTopicSource = this.build(UebPropertyUtils.makeBuilder(props, topic, servers)
                 .consumerGroup(props.getString(
                                 PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX, null))
                 .consumerInstance(props.getString(
@@ -209,8 +211,6 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
 
     @Override
     public String toString() {
-        StringBuilder builder = new StringBuilder();
-        builder.append("IndexedUebTopicSourceFactory []");
-        return builder.toString();
+        return "IndexedUebTopicSourceFactory []";
     }
 }
index 98b6ed6..62ac08b 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -25,6 +25,7 @@ import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 import java.util.Properties;
+import java.util.regex.Pattern;
 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
 
@@ -32,6 +33,7 @@ import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
  * Noop Topic Factory.
  */
 public abstract class NoopTopicFactory<T extends NoopTopicEndpoint> extends TopicBaseHashedFactory<T> {
+    private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
 
     /**
      * Get Topics Property Name.
@@ -50,7 +52,7 @@ public abstract class NoopTopicFactory<T extends NoopTopicEndpoint> extends Topi
             return new ArrayList<>();
         }
 
-        return Arrays.asList(topics.split("\\s*,\\s*"));
+        return Arrays.asList(COMMA_SPACE_PAT.split(topics));
     }
 
     /**
@@ -66,7 +68,7 @@ public abstract class NoopTopicFactory<T extends NoopTopicEndpoint> extends Topi
             servers = CommInfrastructure.NOOP.toString();
         }
 
-        return new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*")));
+        return new ArrayList<>(Arrays.asList(COMMA_SPACE_PAT.split(servers)));
     }
 
     /**
@@ -74,11 +76,11 @@ public abstract class NoopTopicFactory<T extends NoopTopicEndpoint> extends Topi
      */
     @Override
     protected boolean isManaged(String topicName, Properties properties) {
-        String managedString =
+        var managedString =
             properties.getProperty(getTopicsPropertyName()
                 + "." + topicName + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX);
 
-        boolean managed = true;
+        var managed = true;
         if (managedString != null && !managedString.isEmpty()) {
             managed = Boolean.parseBoolean(managedString);
         }
index f53c5ea..c785ef0 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -126,7 +126,7 @@ public abstract class TopicBaseHashedFactory<T extends Topic> implements TopicBa
                 return this.endpoints.get(topic);
             }
 
-            T endpoint = build(servers, topic);
+            var endpoint = build(servers, topic);
             if (managed) {
                 this.endpoints.put(topic, endpoint);
             }
index 0c058ad..8bf805b 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * policy-endpoints
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
  * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
  * ================================================================================
@@ -25,7 +25,6 @@ package org.onap.policy.common.endpoints.event.comm.bus.internal;
 import com.att.nsa.apiClient.http.HttpClient.ConnectionType;
 import com.att.nsa.cambria.client.CambriaBatchingPublisher;
 import com.att.nsa.cambria.client.CambriaClientBuilders;
-import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
 import java.net.MalformedURLException;
 import java.security.GeneralSecurityException;
 import java.util.ArrayList;
@@ -79,7 +78,7 @@ public interface BusPublisher {
          */
         public CambriaPublisherWrapper(BusTopicParams busTopicParams) {
 
-            PublisherBuilder builder = new CambriaClientBuilders.PublisherBuilder();
+            var builder = new CambriaClientBuilders.PublisherBuilder();
 
             builder.usingHosts(busTopicParams.getServers()).onTopic(busTopicParams.getTopic());
 
@@ -237,8 +236,13 @@ public interface BusPublisher {
 
             try {
                 this.publisher.close(1, TimeUnit.SECONDS);
+
+            } catch (InterruptedException e) {
+                logger.warn("{}: CLOSE FAILED", this, e);
+                Thread.currentThread().interrupt();
+
             } catch (Exception e) {
-                logger.warn("{}: CLOSE FAILED because of {}", this, e.getMessage(), e);
+                logger.warn("{}: CLOSE FAILED", this, e);
             }
         }
 
index f258d5d..ea22af8 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -74,7 +74,7 @@ public class InlineUebTopicSink extends InlineBusTopicSink implements UebTopicSi
 
     @Override
     public String toString() {
-        StringBuilder builder = new StringBuilder();
+        var builder = new StringBuilder();
         builder.append("InlineUebTopicSink [getTopicCommInfrastructure()=").append(getTopicCommInfrastructure())
                 .append(", toString()=").append(super.toString()).append("]");
         return builder.toString();
index c5f2b5b..1c3d89d 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2018-2019 Samsung Electronics Co., Ltd.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -128,7 +128,7 @@ public class SingleThreadedDmaapTopicSource extends SingleThreadedBusTopicSource
 
     @Override
     public String toString() {
-        StringBuilder builder = new StringBuilder();
+        var builder = new StringBuilder();
         builder.append("SingleThreadedDmaapTopicSource [userName=").append(userName).append(", password=")
                 .append((password == null || password.isEmpty()) ? "-" : password.length())
                 .append(", getTopicCommInfrastructure()=").append(getTopicCommInfrastructure()).append(", toString()=")
index e210762..496c38f 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2018-2019 Samsung Electronics Co., Ltd.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -66,7 +66,7 @@ public class SingleThreadedUebTopicSource extends SingleThreadedBusTopicSource i
 
     @Override
     public String toString() {
-        StringBuilder builder = new StringBuilder();
+        var builder = new StringBuilder();
         builder.append("SingleThreadedUebTopicSource [getTopicCommInfrastructure()=")
                 .append(getTopicCommInfrastructure()).append(", toString()=").append(super.toString()).append("]");
         return builder.toString();
index efa06e2..dca1437 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -159,7 +159,7 @@ public abstract class TopicBase implements Topic {
     protected boolean broadcast(String message) {
         List<TopicListener> snapshotListeners = this.snapshotTopicListeners();
 
-        boolean success = true;
+        var success = true;
         for (TopicListener topicListener : snapshotListeners) {
             try {
                 topicListener.onTopicEvent(this.getTopicCommInfrastructure(), this.topic, message);
@@ -245,7 +245,7 @@ public abstract class TopicBase implements Topic {
 
     @Override
     public synchronized String[] getRecentEvents() {
-        String[] events = new String[recentEvents.size()];
+        var events = new String[recentEvents.size()];
         return recentEvents.toArray(events);
     }
 
index 5c3f52d..8ca8ca3 100644 (file)
@@ -26,6 +26,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Properties;
+import java.util.regex.Pattern;
 import org.apache.commons.lang3.StringUtils;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 import org.onap.policy.common.endpoints.http.client.internal.JerseyClient;
@@ -38,6 +39,7 @@ import org.slf4j.LoggerFactory;
  * HTTP client factory implementation indexed by name.
  */
 class IndexedHttpClientFactory implements HttpClientFactory {
+    private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
 
     /**
      * Logger.
@@ -75,7 +77,7 @@ class IndexedHttpClientFactory implements HttpClientFactory {
             return clientList;
         }
 
-        for (String clientName : clientNames.split("\\s*,\\s*")) {
+        for (String clientName : COMMA_SPACE_PAT.split(clientNames)) {
             addClient(clientList, clientName, properties);
         }
 
@@ -85,11 +87,11 @@ class IndexedHttpClientFactory implements HttpClientFactory {
     private void addClient(ArrayList<HttpClient> clientList, String clientName, Properties properties) {
         String clientPrefix = PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + clientName;
 
-        PropertyUtils props = new PropertyUtils(properties, clientPrefix,
+        var props = new PropertyUtils(properties, clientPrefix,
             (name, value, ex) ->
                 logger.warn("{}: {} {} is in invalid format for http client {} ", this, name, value, clientName));
 
-        int port = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
+        var port = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
         if (port < 0) {
             logger.warn("No HTTP port for client in {}", clientName);
             return;
index f4f0705..ea76c59 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
  * Modifications Copyright (C) 2019 Nordix Foundation.
  * ================================================================================
@@ -29,6 +29,7 @@ import java.util.Collections;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.concurrent.Future;
+import java.util.regex.Pattern;
 import javax.net.ssl.SSLContext;
 import javax.ws.rs.client.Client;
 import javax.ws.rs.client.ClientBuilder;
@@ -51,6 +52,7 @@ import org.slf4j.LoggerFactory;
  * Http Client implementation using a Jersey Client.
  */
 public class JerseyClient implements HttpClient {
+    private static final Pattern COMMA_PAT = Pattern.compile(",");
 
     /**
      * Logger.
@@ -112,7 +114,7 @@ public class JerseyClient implements HttpClient {
         this.client = detmClient();
 
         if (!StringUtils.isBlank(this.userName) && !StringUtils.isBlank(this.password)) {
-            HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basic(userName, password);
+            var authFeature = HttpAuthenticationFeature.basic(userName, password);
             this.client.register(authFeature);
         }
 
@@ -127,7 +129,7 @@ public class JerseyClient implements HttpClient {
     private Client detmClient() throws NoSuchAlgorithmException, KeyManagementException {
         if (this.https) {
             ClientBuilder clientBuilder;
-            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
+            var sslContext = SSLContext.getInstance("TLSv1.2");
             if (this.selfSignedCerts) {
                 sslContext.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
 
@@ -158,7 +160,7 @@ public class JerseyClient implements HttpClient {
     private void registerSerProviders(String serializationProvider) throws ClassNotFoundException {
         String providers = (StringUtils.isBlank(serializationProvider)
                         ? JERSEY_DEFAULT_SERIALIZATION_PROVIDER : serializationProvider);
-        for (String prov : providers.split(",")) {
+        for (String prov : COMMA_PAT.split(providers)) {
             this.client.register(Class.forName(prov));
         }
     }
@@ -195,7 +197,7 @@ public class JerseyClient implements HttpClient {
 
     @Override
     public Future<Response> get(InvocationCallback<Response> callback, Map<String, Object> headers) {
-        Builder builder = getWebTarget().request();
+        var builder = getWebTarget().request();
         if (headers != null) {
             headers.forEach(builder::header);
         }
@@ -310,7 +312,7 @@ public class JerseyClient implements HttpClient {
 
     @Override
     public String toString() {
-        StringBuilder builder = new StringBuilder();
+        var builder = new StringBuilder();
         builder.append("JerseyClient [name=");
         builder.append(name);
         builder.append(", https=");
@@ -338,7 +340,7 @@ public class JerseyClient implements HttpClient {
     }
 
     private Builder getBuilder(String path, Map<String, Object> headers) {
-        Builder builder = getWebTarget().path(path).request();
+        var builder = getWebTarget().path(path).request();
         for (Entry<String, Object> header : headers.entrySet()) {
             builder.header(header.getKey(), header.getValue());
         }
index 445a351..e5a69da 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine - Common Modules
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2020 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -25,6 +25,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Properties;
+import java.util.regex.Pattern;
 import org.apache.commons.lang3.StringUtils;
 import org.onap.policy.common.endpoints.http.server.internal.JettyJerseyServer;
 import org.onap.policy.common.endpoints.http.server.internal.JettyStaticResourceServer;
@@ -37,8 +38,7 @@ import org.slf4j.LoggerFactory;
  * Indexed factory implementation.
  */
 class IndexedHttpServletServerFactory implements HttpServletServerFactory {
-
-    private static final String SPACES_COMMA_SPACES = "\\s*,\\s*";
+    private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
 
     /**
      * logger.
@@ -58,7 +58,7 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
             return servers.get(port);
         }
 
-        JettyJerseyServer server = new JettyJerseyServer(name, https, host, port, contextPath, swagger);
+        var server = new JettyJerseyServer(name, https, host, port, contextPath, swagger);
         if (managed) {
             servers.put(port, server);
         }
@@ -83,7 +83,7 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
             return serviceList;
         }
 
-        for (String serviceName : serviceNames.split(SPACES_COMMA_SPACES)) {
+        for (String serviceName : COMMA_SPACE_PAT.split(serviceNames)) {
             addService(serviceList, serviceName, properties);
         }
 
@@ -99,7 +99,7 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
             return servers.get(port);
         }
 
-        JettyStaticResourceServer server = new JettyStaticResourceServer(name, https, host, port, contextPath);
+        var server = new JettyStaticResourceServer(name, https, host, port, contextPath);
         if (managed) {
             servers.put(port, server);
         }
@@ -111,22 +111,21 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
 
         String servicePrefix = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + serviceName;
 
-        PropertyUtils props = new PropertyUtils(properties, servicePrefix,
+        var props = new PropertyUtils(properties, servicePrefix,
             (name, value, ex) -> logger
                         .warn("{}: {} {} is in invalid format for http service {} ", this, name, value, serviceName));
 
-        int servicePort = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
+        var servicePort = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
         if (servicePort < 0) {
             logger.warn("No HTTP port for service in {}", serviceName);
             return;
         }
 
-        final String hostName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, null);
-        final String contextUriPath =
-                        props.getString(PolicyEndPointProperties.PROPERTY_HTTP_CONTEXT_URIPATH_SUFFIX, null);
-        boolean managed = props.getBoolean(PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, true);
-        boolean swagger = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, false);
-        boolean https = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, false);
+        final var hostName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, null);
+        final var contextUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_CONTEXT_URIPATH_SUFFIX, null);
+        var managed = props.getBoolean(PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, true);
+        var swagger = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, false);
+        var https = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, false);
 
         // create the service
         HttpServletServer service = build(serviceName, https, hostName, servicePort, contextUriPath, swagger, managed);
@@ -135,7 +134,7 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
         setSerializationProvider(props, service);
         setAuthentication(props, service, contextUriPath);
 
-        final String restUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_URIPATH_SUFFIX, null);
+        final var restUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_URIPATH_SUFFIX, null);
 
         addFilterClasses(props, service, restUriPath);
         addServletClasses(props, service, restUriPath);
@@ -146,7 +145,7 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
 
     private void setSerializationProvider(PropertyUtils props, HttpServletServer service) {
 
-        final String classProv = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER, null);
+        final var classProv = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER, null);
 
         if (!StringUtils.isBlank(classProv)) {
             service.setSerializationProvider(classProv);
@@ -156,10 +155,10 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
     private void setAuthentication(PropertyUtils props, HttpServletServer service, final String contextUriPath) {
         /* authentication method either AAF or HTTP Basic Auth */
 
-        boolean aaf = props.getBoolean(PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, false);
-        final String userName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, null);
-        final String password = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, null);
-        final String authUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_URIPATH_SUFFIX, null);
+        final var aaf = props.getBoolean(PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, false);
+        final var userName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, null);
+        final var password = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, null);
+        final var authUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_URIPATH_SUFFIX, null);
 
         if (aaf) {
             service.setAafAuthentication(contextUriPath);
@@ -170,11 +169,11 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
 
     private void addFilterClasses(PropertyUtils props, HttpServletServer service, final String restUriPath) {
 
-        final String filterClasses =
+        final var filterClasses =
                         props.getString(PolicyEndPointProperties.PROPERTY_HTTP_FILTER_CLASSES_SUFFIX, null);
 
         if (!StringUtils.isBlank(filterClasses)) {
-            for (String filterClass : filterClasses.split(SPACES_COMMA_SPACES)) {
+            for (String filterClass : COMMA_SPACE_PAT.split(filterClasses)) {
                 service.addFilterClass(restUriPath, filterClass);
             }
         }
@@ -182,10 +181,10 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
 
     private void addServletClasses(PropertyUtils props, HttpServletServer service, final String restUriPath) {
 
-        final String restClasses = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, null);
+        final var restClasses = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, null);
 
         if (!StringUtils.isBlank(restClasses)) {
-            for (String restClass : restClasses.split(SPACES_COMMA_SPACES)) {
+            for (String restClass : COMMA_SPACE_PAT.split(restClasses)) {
                 service.addServletClass(restUriPath, restClass);
             }
         }
@@ -193,10 +192,10 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory {
 
     private void addServletPackages(PropertyUtils props, HttpServletServer service, final String restUriPath) {
 
-        final String restPackages = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_PACKAGES_SUFFIX, null);
+        final var restPackages = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_PACKAGES_SUFFIX, null);
 
         if (!StringUtils.isBlank(restPackages)) {
-            for (String restPackage : restPackages.split(SPACES_COMMA_SPACES)) {
+            for (String restPackage : COMMA_SPACE_PAT.split(restPackages)) {
                 service.addServletPackage(restUriPath, restPackage);
             }
         }
index 6776a32..3258810 100644 (file)
@@ -1,7 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2019 Nordix Foundation.
- *  Modifications Copyright (C) 2019-2020 AT&T Intellectual Property.
+ *  Modifications Copyright (C) 2019-2021 AT&T Intellectual Property.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -78,7 +78,7 @@ public class RestServer extends ServiceManagerContainer {
      * @return the properties object
      */
     protected Properties getServerProperties(RestServerParameters restServerParameters, String names) {
-        final Properties props = new Properties();
+        final var props = new Properties();
         props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, restServerParameters.getName());
 
         final String svcpfx =
@@ -111,7 +111,7 @@ public class RestServer extends ServiceManagerContainer {
      * @return the provider class names
      */
     private String getProviderClassNames(Class<?>[] jaxrsProviders) {
-        StringBuilder names = new StringBuilder();
+        var names = new StringBuilder();
 
         for (Class<?> prov : jaxrsProviders) {
             if (names.length() > 0) {
index 8506a28..644e6e2 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -96,7 +96,7 @@ public class YamlMessageBodyHandler implements MessageBodyReader<Object>, Messag
     public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                     MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
 
-        try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
+        try (var writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
             translator.toYaml(writer, object);
         }
     }
@@ -121,7 +121,7 @@ public class YamlMessageBodyHandler implements MessageBodyReader<Object>, Messag
     public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                     MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
 
-        try (InputStreamReader streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
+        try (var streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
             Class<?> clazz = (Class<?>) genericType;
             return translator.fromYaml(streamReader, clazz);
 
index df6823a..afa37a6 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * policy-endpoints
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2019-2020 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -258,7 +258,7 @@ public class JettyJerseyServer extends JettyServletServer {
 
     @Override
     public String toString() {
-        StringBuilder builder = new StringBuilder();
+        var builder = new StringBuilder();
         builder.append("JettyJerseyServer [Jerseyservlets=").append(servlets).append(", swaggerId=").append(swaggerId)
                 .append(", toString()=").append(super.toString()).append("]");
         return builder.toString();
index 29e7bbf..48dc811 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2019-2020 Nordix Foundation.
  * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
  * ================================================================================
@@ -165,8 +165,7 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
 
         this.jettyServer = new Server();
 
-        CustomRequestLog requestLog =
-                        new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
+        var requestLog = new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
         this.jettyServer.setRequestLog(requestLog);
 
         if (https) {
@@ -230,7 +229,7 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
             }
         }
 
-        HttpConfiguration https = new HttpConfiguration();
+        var https = new HttpConfiguration();
         https.addCustomizer(new SecureRequestCustomizer());
 
         return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
@@ -267,22 +266,22 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
             srvltPath = "/*";
         }
 
-        final HashLoginService hashLoginService = new HashLoginService();
-        final UserStore userStore = new UserStore();
+        final var hashLoginService = new HashLoginService();
+        final var userStore = new UserStore();
         userStore.addUser(user, Credential.getCredential(password), new String[] {"user"});
         hashLoginService.setUserStore(userStore);
         hashLoginService.setName(this.connector.getName() + "-login-service");
 
-        Constraint constraint = new Constraint();
+        var constraint = new Constraint();
         constraint.setName(Constraint.__BASIC_AUTH);
         constraint.setRoles(new String[] {"user"});
         constraint.setAuthenticate(true);
 
-        ConstraintMapping constraintMapping = new ConstraintMapping();
+        var constraintMapping = new ConstraintMapping();
         constraintMapping.setConstraint(constraint);
         constraintMapping.setPathSpec(srvltPath);
 
-        ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
+        var securityHandler = new ConstraintSecurityHandler();
         securityHandler.setAuthenticator(new BasicAuthenticator());
         securityHandler.setRealmName(this.connector.getName() + "-realm");
         securityHandler.addConstraintMapping(constraintMapping);
@@ -313,6 +312,11 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
             }
 
             this.jettyServer.join();
+
+        } catch (InterruptedException e) {
+            logger.error("{}: error found while bringing up server", this, e);
+            Thread.currentThread().interrupt();
+
         } catch (Exception e) {
             logger.error("{}: error found while bringing up server", this, e);
         }
@@ -519,7 +523,7 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable
 
     @Override
     public String toString() {
-        StringBuilder builder = new StringBuilder();
+        var builder = new StringBuilder();
         builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
                 .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
                 .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
index 31e670a..41f9abd 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -80,7 +80,7 @@ public class MessageTypeDispatcher extends JsonListener {
     @Override
     public void onTopicEvent(CommInfrastructure infra, String topic, StandardCoderObject sco) {
         // extract the message type
-        final String type = sco.getString(messageFieldNames);
+        final var type = sco.getString(messageFieldNames);
         if (type == null) {
             logger.warn("unable to extract {}: {}", fullMessageFieldName, sco);
             return;
index e4686c1..e575e33 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -111,7 +111,7 @@ public class RequestIdDispatcher<T> extends ScoListener<T> {
     public void onTopicEvent(CommInfrastructure infra, String topic, StandardCoderObject sco, T message) {
 
         // extract the request id
-        String reqid = sco.getString(requestIdFieldNames);
+        var reqid = sco.getString(requestIdFieldNames);
 
         // dispatch the message
         if (Strings.isNullOrEmpty(reqid)) {
index 427f088..e8a3dc2 100644 (file)
@@ -56,7 +56,7 @@ public class TopicParameterGroup extends ParameterGroupImpl {
     public BeanValidationResult validate() {
         BeanValidationResult result = super.validate();
         if (result.isValid()) {
-            StringBuilder errorMsg = new StringBuilder();
+            var errorMsg = new StringBuilder();
             StringBuilder missingSourceParams = checkMissingMandatoryParams(topicSources);
             if (missingSourceParams.length() > 0) {
                 errorMsg.append(missingSourceParams.append("missing in topicSources. "));
@@ -75,7 +75,7 @@ public class TopicParameterGroup extends ParameterGroupImpl {
     }
 
     private StringBuilder checkMissingMandatoryParams(List<TopicParameters> topicParametersList) {
-        StringBuilder missingParams = new StringBuilder();
+        var missingParams = new StringBuilder();
         for (TopicParameters topicParameters : topicParametersList) {
             if (StringUtils.isBlank(topicParameters.getTopic())) {
                 missingParams.append("topic, ");
index fa2f3d2..2caa922 100644 (file)
@@ -1,7 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
- *  Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ *  Modifications Copyright (C) 2018, 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.
@@ -126,7 +126,7 @@ public class HealthCheckReport {
 
     @Override
     public String toString() {
-        final StringBuilder builder = new StringBuilder();
+        final var builder = new StringBuilder();
         builder.append("Report [name=");
         builder.append(getName());
         builder.append(", url=");
index 5cb220b..286f468 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -26,12 +26,14 @@ import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.regex.Pattern;
 import org.apache.commons.lang3.StringUtils;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder;
 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
 
 public class DmaapPropertyUtils {
+    private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
 
     /**
      * Maps a topic property to a DME property.
@@ -86,7 +88,7 @@ public class DmaapPropertyUtils {
 
         for (Map.Entry<String, String> ent : PROP_TO_DME.entrySet()) {
             String propName = ent.getKey();
-            String value = props.getString(propName, null);
+            var value = props.getString(propName, null);
 
             if (!StringUtils.isBlank(value)) {
                 String dmeName = ent.getValue();
@@ -94,7 +96,7 @@ public class DmaapPropertyUtils {
             }
         }
 
-        final List<String> serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*")));
+        final List<String> serverList = new ArrayList<>(Arrays.asList(COMMA_SPACE_PAT.split(servers)));
 
         return BusTopicParams.builder()
                     .servers(serverList)
index d021751..b2e257b 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -23,11 +23,13 @@ package org.onap.policy.common.endpoints.utils;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import java.util.regex.Pattern;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder;
 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
 
 public class UebPropertyUtils {
+    private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
 
     private UebPropertyUtils() {
         // do nothing
@@ -44,7 +46,7 @@ public class UebPropertyUtils {
      */
     public static TopicParamsBuilder makeBuilder(PropertyUtils props, String topic, String servers) {
 
-        final List<String> serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*")));
+        final List<String> serverList = new ArrayList<>(Arrays.asList(COMMA_SPACE_PAT.split(servers)));
 
         return BusTopicParams.builder()
                     .servers(serverList)
index e267179..1357a51 100644 (file)
@@ -27,12 +27,10 @@ import com.google.gson.JsonArray;
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParseException;
-import com.google.re2j.Matcher;
 import com.google.re2j.Pattern;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.net.URL;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.util.ArrayList;
@@ -127,7 +125,7 @@ public class GsonTestUtils {
      */
     public void compareGson(Object object, File expected) {
         // file is not required to have a full path - find it via getResource()
-        URL url = object.getClass().getResource(expected.getName());
+        var url = object.getClass().getResource(expected.getName());
         if (url == null) {
             throw new JsonParseException(new FileNotFoundException(expected.getName()));
         }
@@ -197,7 +195,7 @@ public class GsonTestUtils {
      * @return the text, after interpolating the script elements
      */
     public String applyScripts(String text, Object object) {
-        Matcher mat = SCRIPT_PAT.matcher(text);
+        var mat = SCRIPT_PAT.matcher(text);
         if (!mat.find()) {
             // contains no script elements - just return it as is
             return text;
@@ -209,8 +207,8 @@ public class GsonTestUtils {
         context.set("obj", object);
 
         // work our way through the text, interpolating script elements as we go
-        StringBuilder bldr = new StringBuilder();
-        int ilast = 0;
+        var bldr = new StringBuilder();
+        var ilast = 0;
         mat.reset();
         while (mat.find(ilast)) {
             // append segment that appears between last match and this
@@ -275,7 +273,7 @@ public class GsonTestUtils {
      * @return a new object, without the null items
      */
     public JsonObject reorder(JsonObject jsonObj) {
-        JsonObject newjo = new JsonObject();
+        var newjo = new JsonObject();
 
         // sort the keys before copying to the new object
         List<Entry<String, JsonElement>> sortedSet = new ArrayList<>(jsonObj.entrySet());
@@ -301,7 +299,7 @@ public class GsonTestUtils {
      * @return a new array, with null items removed from all elements
      */
     public JsonArray reorder(JsonArray jsonArray) {
-        JsonArray newarr = new JsonArray();
+        var newarr = new JsonArray();
         for (JsonElement ent : jsonArray) {
             newarr.add(reorder(ent));
         }
index 7e09cd9..39266a6 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine - Common Modules
  * ================================================================================
- * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -51,8 +51,8 @@ public class Serializer {
      * @throws IOException if an error occurs
      */
     public static <T> byte[] serialize(T object) throws IOException {
-        try (ByteArrayOutputStream out = factory.makeByteArrayOutputStream()) {
-            try (ObjectOutputStream oos = factory.makeObjectOutputStream(out)) {
+        try (var out = factory.makeByteArrayOutputStream()) {
+            try (var oos = factory.makeObjectOutputStream(out)) {
                 /*
                  * writeObject() is final and mockito can't mock final methods. In
                  * addition, powermock seemed to be having difficulty with the junit test
@@ -75,8 +75,8 @@ public class Serializer {
      */
     private static <T> T deserialize(Class<T> clazz, byte[] data) throws IOException {
 
-        try (ByteArrayInputStream in = factory.makeByteArrayInputStream(data);
-                        ObjectInputStream ois = factory.makeObjectInputStream(in)) {
+        try (var in = factory.makeByteArrayInputStream(data);
+                        var ois = factory.makeObjectInputStream(in)) {
             /*
              * readObject() is final and mockito can't mock final methods. In addition,
              * powermock seemed to be having difficulty with the junit test class as well,
index cc0fed0..11dff4b 100644 (file)
@@ -70,7 +70,7 @@ public class SelfSignedKeyStore {
         keystoreName = System.getProperty("user.dir") + "/" + relativePath;
 
         // use existing file if it isn't too old
-        File keystore = new File(keystoreName);
+        var keystore = new File(keystoreName);
         if (keystore.exists()) {
             if (System.currentTimeMillis() < keystore.lastModified()
                             + TimeUnit.MILLISECONDS.convert(5, TimeUnit.HOURS)) {
@@ -85,7 +85,7 @@ public class SelfSignedKeyStore {
          * dropping the trailing comma.
          */
         String sanName = getKeystoreSanName();
-        String subAltNames = ResourceUtils.getResourceAsString(sanName);
+        var subAltNames = ResourceUtils.getResourceAsString(sanName);
         if (subAltNames == null) {
             throw new FileNotFoundException(sanName);
         }
@@ -96,7 +96,7 @@ public class SelfSignedKeyStore {
         // build up the "keytool" command
 
         // @formatter:off
-        ProcessBuilder builder = new ProcessBuilder("keytool", "-genkeypair",
+        var builder = new ProcessBuilder("keytool", "-genkeypair",
                         "-alias", "policy@policy.onap.org",
                         "-validity", "1",
                         "-keyalg", "RSA",
index f457dd2..1ab1f28 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START====================================================
  * Common Utils-Test
  * =============================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 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.
@@ -70,7 +70,7 @@ public class ExceptionsTester extends ThrowablesTester {
      *             if the constructed objects fail to pass various tests
      */
     public <T extends Exception> int testAllException(final Class<T> claz) {
-        int ncons = 0;
+        var ncons = 0;
 
         ncons += testAllThrowable(claz);
         ncons += testException(claz);
@@ -111,8 +111,8 @@ public class ExceptionsTester extends ThrowablesTester {
             return 0;
         }
 
-        Exception cause = new Exception(EXPECTED_EXCEPTION_MSG);
-        T ex = newInstance(cons, cause);
+        var cause = new Exception(EXPECTED_EXCEPTION_MSG);
+        var ex = newInstance(cons, cause);
 
         assertNotNull(ex.toString());
         assertEquals(ex.getMessage(), ex.getMessage());
@@ -151,8 +151,8 @@ public class ExceptionsTester extends ThrowablesTester {
             return 0;
         }
 
-        Exception cause = new Exception(EXPECTED_EXCEPTION_MSG);
-        T ex = newInstance(cons, "world", cause);
+        var cause = new Exception(EXPECTED_EXCEPTION_MSG);
+        var ex = newInstance(cons, "world", cause);
 
         assertNotNull(ex.toString());
         assertEquals("world", ex.getMessage());
index fd819b2..06ca804 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START====================================================
  * Common Utils-Test
  * =============================================================================
- * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020-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.
@@ -73,7 +73,7 @@ public class ThrowablesTester {
      */
     public final <T extends Throwable> int testAllThrowable(
                     final Class<T> claz) {
-        int ncons = 0;
+        var ncons = 0;
 
         ncons += testDefault(claz);
         ncons += testString(claz);
@@ -112,7 +112,7 @@ public class ThrowablesTester {
             return 0;
         }
 
-        T ex = newInstance(cons);
+        var ex = newInstance(cons);
 
         assertNotNull(ex.toString());
         assertNull(ex.getMessage());
@@ -151,7 +151,7 @@ public class ThrowablesTester {
             return 0;
         }
 
-        T ex = newInstance(cons, "hello");
+        var ex = newInstance(cons, "hello");
 
         assertNotNull(ex.toString());
         assertEquals("hello", ex.getMessage());
@@ -191,7 +191,7 @@ public class ThrowablesTester {
             return 0;
         }
 
-        T ex = newInstance(cons, CAUSE);
+        var ex = newInstance(cons, CAUSE);
 
         assertEquals(ex.getMessage(), ex.getMessage());
         assertNotNull(ex.toString());
@@ -231,7 +231,7 @@ public class ThrowablesTester {
             return 0;
         }
 
-        T ex = newInstance(cons, "world", CAUSE);
+        var ex = newInstance(cons, "world", CAUSE);
 
         assertNotNull(ex.toString());
         assertEquals("world", ex.getMessage());
@@ -382,7 +382,7 @@ public class ThrowablesTester {
      */
     public final <T extends Throwable> void testSuppressStack(
                     final Constructor<T> cons) {
-        T ex = newInstance(cons, "yes,yes", CAUSE, true, true);
+        var ex = newInstance(cons, "yes,yes", CAUSE, true, true);
 
         ex.addSuppressed(SUPPRESSED);
 
@@ -420,7 +420,7 @@ public class ThrowablesTester {
      */
     public final <T extends Throwable> void testSuppressNoStack(
                     final Constructor<T> cons) {
-        T ex = newInstance(cons, "yes,no", CAUSE, true, false);
+        var ex = newInstance(cons, "yes,no", CAUSE, true, false);
 
         ex.addSuppressed(SUPPRESSED);
 
@@ -458,7 +458,7 @@ public class ThrowablesTester {
      */
     public final <T extends Throwable> void testNoSuppressStack(
                     final Constructor<T> cons) {
-        T ex = newInstance(cons, "no,yes", CAUSE, false, true);
+        var ex = newInstance(cons, "no,yes", CAUSE, false, true);
 
         ex.addSuppressed(SUPPRESSED);
 
@@ -494,7 +494,7 @@ public class ThrowablesTester {
      */
     public final <T extends Throwable> void testNoSuppressNoStack(
                     final Constructor<T> cons) {
-        T ex = newInstance(cons, "no,no", CAUSE, false, false);
+        var ex = newInstance(cons, "no,no", CAUSE, false, false);
 
         ex.addSuppressed(SUPPRESSED);
 
index 19c5096..887cec9 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START====================================================
  * Common Utils-Test
  * =============================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -110,7 +110,7 @@ public class ExtractAppender extends AppenderBase<ILoggingEvent> {
             }
 
             for (Pattern p : patterns.values()) {
-                Matcher matcher = p.matcher(msg);
+                var matcher = p.matcher(msg);
 
                 if (matcher.find()) {
                     addGroupMatch(matcher);
@@ -129,7 +129,7 @@ public class ExtractAppender extends AppenderBase<ILoggingEvent> {
     private void addGroupMatch(final Matcher mat) {
         int ngroups = mat.groupCount();
 
-        for (int x = 1; x <= ngroups; ++x) {
+        for (var x = 1; x <= ngroups; ++x) {
             String txt = mat.group(x);
 
             if (txt != null) {
index d8b792a..b29f742 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2020-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 +61,7 @@ public class PseudoExecutor implements Executor {
      *         tasks have been reached before the queue was emptied
      */
     public boolean runAll(int maxTasks) {
-        for (int count = 0; count < maxTasks && !tasks.isEmpty(); ++count) {
+        for (var count = 0; count < maxTasks && !tasks.isEmpty(); ++count) {
             tasks.remove().run();
         }
 
index 54ec601..9e61eaa 100644 (file)
@@ -282,7 +282,7 @@ public class TestTimeMulti extends TestTime {
             return;
         }
 
-        SleepItem item = new SleepItem(this, sleepMs, Thread.currentThread());
+        var item = new SleepItem(this, sleepMs, Thread.currentThread());
         enqueue(item);
 
         // wait for the item to fire
index 37a9047..b9ba3fd 100644 (file)
@@ -1,6 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2021 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.common.utils.cmd;
 import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.net.URISyntaxException;
-import java.net.URL;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.Arrays;
@@ -184,9 +184,9 @@ public class CommandLineArgumentsHandler {
      * @return the help string
      */
     public String help() {
-        final HelpFormatter helpFormatter = new HelpFormatter();
-        final StringWriter stringWriter = new StringWriter();
-        final PrintWriter printWriter = new PrintWriter(stringWriter);
+        final var helpFormatter = new HelpFormatter();
+        final var stringWriter = new StringWriter();
+        final var printWriter = new PrintWriter(stringWriter);
         final String cmdLineSyntax = this.helpClassName + " [options...]";
 
         helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, cmdLineSyntax, "options", options, 0, 0, "");
@@ -243,13 +243,13 @@ public class CommandLineArgumentsHandler {
         }
 
         // The file name refers to a resource on the local file system
-        final URL fileUrl = ResourceUtils.getUrl4Resource(fileName);
+        final var fileUrl = ResourceUtils.getUrl4Resource(fileName);
         if (fileUrl == null) {
             throw new CommandLineException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
         }
 
         try {
-            Path path = Path.of(fileUrl.toURI());
+            var path = Path.of(fileUrl.toURI());
             if (!Files.isRegularFile(path)) {
                 throw new CommandLineException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file");
             }
index 3036d35..daacf47 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP PAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -55,12 +55,12 @@ public class PropertyCoder {
      * @return a class T object
      */
     public <T> T decode(String json, String keyProperty, Class<T> clazz) {
-        JsonElement jsonElement = GSON.fromJson(json, JsonElement.class);
+        var jsonElement = GSON.fromJson(json, JsonElement.class);
         return new MyDecoder(jsonElement, keyProperty).decrypt(jsonElement, clazz);
     }
 
     public <T> T decode(Reader reader, String keyProperty, Class<T> clazz) {
-        JsonElement jsonElement = GSON.fromJson(reader, JsonElement.class);
+        var jsonElement = GSON.fromJson(reader, JsonElement.class);
         return new MyDecoder(jsonElement, keyProperty).decrypt(jsonElement, clazz);
     }
 
@@ -71,9 +71,9 @@ public class PropertyCoder {
             if (!jsonElement.isJsonObject()) {
                 return;
             }
-            JsonObject jsonObject = jsonElement.getAsJsonObject();
+            var jsonObject = jsonElement.getAsJsonObject();
             // Use keyProperty from input to retrieve secretKey
-            String secretKey = jsonObject.get(keyProperty).getAsString();
+            var secretKey = jsonObject.get(keyProperty).getAsString();
             if (!StringUtils.isBlank(secretKey)) {
                 crypto = new CryptoUtils(secretKey);
             }
@@ -97,7 +97,7 @@ public class PropertyCoder {
             if (!jsonElement.getAsJsonPrimitive().isString()) {
                 return jsonElement;
             }
-            String value = jsonElement.getAsString();
+            var value = jsonElement.getAsString();
             if (!value.startsWith("enc:")) {
                 return jsonElement;
             }
@@ -111,7 +111,7 @@ public class PropertyCoder {
             if (crypto == null) {
                 return jsonArray;
             }
-            JsonArray newArray = new JsonArray();
+            var newArray = new JsonArray();
             for (JsonElement element: jsonArray) {
                 newArray.add(decrypt(element));
             }
@@ -122,14 +122,14 @@ public class PropertyCoder {
             if (crypto == null) {
                 return jsonObject;
             }
-            JsonObject newObject = new JsonObject();
+            var newObject = new JsonObject();
             Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
             for (Map.Entry<String, JsonElement> entry : entrySet) {
                 String key = entry.getKey();
-                JsonElement jsonElement = decrypt(entry.getValue());
+                var jsonElement = decrypt(entry.getValue());
                 newObject.add(key, jsonElement);
             }
             return newObject;
         }
     }
-}
\ No newline at end of file
+}
index 7f5e3b8..0d84f85 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -157,7 +157,7 @@ public class StandardCoder implements Coder {
     @Override
     public void encode(OutputStream target, Object object) throws CoderException {
         try {
-            Writer wtr = makeWriter(target);
+            var wtr = makeWriter(target);
             toJson(wtr, object);
 
             // flush, but don't close
@@ -170,7 +170,7 @@ public class StandardCoder implements Coder {
 
     @Override
     public void encode(File target, Object object) throws CoderException {
-        try (Writer wtr = makeWriter(target)) {
+        try (var wtr = makeWriter(target)) {
             toJson(wtr, object);
 
             // no need to flush or close here
@@ -212,7 +212,7 @@ public class StandardCoder implements Coder {
 
     @Override
     public <T> T decode(File source, Class<T> clazz) throws CoderException {
-        try (Reader input = makeReader(source)) {
+        try (var input = makeReader(source)) {
             return fromJson(input, clazz);
 
         } catch (RuntimeException | IOException e) {
index 5d68263..f6c3ca4 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,7 +20,6 @@
 
 package org.onap.policy.common.utils.coder;
 
-import com.google.gson.JsonArray;
 import com.google.gson.JsonElement;
 import java.io.Serializable;
 
@@ -130,7 +129,7 @@ public class StandardCoderObject implements Serializable {
             return null;
         }
 
-        JsonArray array = element.getAsJsonArray();
+        var array = element.getAsJsonArray();
 
         if (index >= array.size()) {
             return null;
index 647a615..4deeba1 100644 (file)
@@ -1,6 +1,6 @@
 /*--
  * ============LICENSE_START=======================================================
- *  Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ *  Copyright (C) 2020-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.
@@ -72,7 +72,7 @@ public class StandardValCoder extends StandardCoder {
 
     @Override
     protected String toJson(@NonNull Object object) {
-        StringWriter output = new StringWriter();
+        var output = new StringWriter();
         toJson(output, object);
         return output.toString();
     }
@@ -89,7 +89,7 @@ public class StandardValCoder extends StandardCoder {
 
     @Override
     protected <T> T fromJson(String json, Class<T> clazz) {
-        StringReader reader = new StringReader(json);
+        var reader = new StringReader(json);
         return convertFromDouble(clazz, gson.fromJson(validatorApi.createJsonReader(validator, reader), clazz));
     }
 
index 7d61e63..b694dd4 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -86,7 +86,7 @@ public class YamlJsonTranslator {
      * @return YAML representing the original object
      */
     public String toYaml(Object object) {
-        StringWriter output = new StringWriter();
+        var output = new StringWriter();
         toYaml(output, object);
         return output.toString();
     }
@@ -98,8 +98,8 @@ public class YamlJsonTranslator {
      * @param object POJO to be translated
      */
     public void toYaml(Writer target, Object object) {
-        DumperOptions dumper = new DumperOptions();
-        Serializer serializer = new Serializer(new Emitter(target, dumper), new Resolver(), dumper, null);
+        var dumper = new DumperOptions();
+        var serializer = new Serializer(new Emitter(target, dumper), new Resolver(), dumper, null);
 
         try {
             serializer.open();
@@ -140,7 +140,7 @@ public class YamlJsonTranslator {
      * @return a POJO representing the YAML read from the reader
      */
     public <T> T fromYaml(Reader source, Class<T> clazz) {
-        Node node = new Yaml().compose(source);
+        var node = new Yaml().compose(source);
         return fromJson(makeJson(node), clazz);
     }
 
@@ -281,7 +281,7 @@ public class YamlJsonTranslator {
     protected JsonArray makeJsonArray(SequenceNode node) {
         List<Node> nodes = node.getValue();
 
-        JsonArray array = new JsonArray(nodes.size());
+        var array = new JsonArray(nodes.size());
         nodes.forEach(subnode -> array.add(makeJson(subnode)));
 
         return array;
@@ -294,10 +294,10 @@ public class YamlJsonTranslator {
      * @return a gson element corresponding to the node
      */
     protected JsonObject makeJsonObject(MappingNode node) {
-        JsonObject obj = new JsonObject();
+        var obj = new JsonObject();
 
         for (NodeTuple tuple : node.getValue()) {
-            Node key = tuple.getKeyNode();
+            var key = tuple.getKeyNode();
             String skey = ((ScalarNode) key).getValue();
 
             obj.add(skey, makeJson(tuple.getValueNode()));
@@ -314,7 +314,7 @@ public class YamlJsonTranslator {
      */
     protected JsonElement makeJsonPrim(ScalarNode node) {
         try {
-            Tag tag = node.getTag();
+            var tag = node.getTag();
 
             if (tag == Tag.INT) {
                 return new JsonPrimitive(Long.valueOf(node.getValue()));
index a2fb5a8..a0a8390 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -113,7 +113,7 @@ public class NetworkUtil {
      */
     public static boolean isTcpPortOpen(String host, int port, int retries, long interval)
             throws InterruptedException {
-        int retry = 0;
+        var retry = 0;
         while (retry < retries) {
             /*
              * As with the server socket, this is only used to see if the port is open,
index 2ef9191..f8c5209 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP - Common Modules
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -20,6 +20,7 @@
 
 package org.onap.policy.common.utils.properties;
 
+import com.google.re2j.Pattern;
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
@@ -45,6 +46,7 @@ import org.onap.policy.common.utils.properties.exception.PropertyMissingExceptio
  * <i>accept</i> includes the "empty" option.
  */
 public class BeanConfigurator {
+    private static final Pattern COMMA_PAT = Pattern.compile(",");
 
     /**
      * The "empty" option that may appear within the {@link Property}'s <i>accept</i>
@@ -414,7 +416,7 @@ public class BeanConfigurator {
      * @return {@code true} if the <i>accept</i> attribute includes "empty"
      */
     protected boolean isEmptyOk(Property prop) {
-        for (String option : prop.accept().split(",")) {
+        for (String option : COMMA_PAT.split(prop.accept())) {
             if (ACCEPT_EMPTY.equals(option)) {
                 return true;
             }
@@ -495,7 +497,7 @@ public class BeanConfigurator {
      * @throws PropertyAccessException if a "get" method cannot be identified
      */
     private Method getGetter(Field field, Property prop) throws PropertyAccessException {
-        String capnm = StringUtils.capitalize(field.getName());
+        var capnm = StringUtils.capitalize(field.getName());
 
         try {
             return getGetter(field, "get" + capnm);
index 996f1b8..0734692 100644 (file)
@@ -1,6 +1,6 @@
 /*-
  * ============LICENSE_START=======================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -24,7 +24,6 @@ import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
-import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -36,6 +35,7 @@ public class PropertyObjectUtils {
 
     public static final Logger logger = LoggerFactory.getLogger(PropertyObjectUtils.class);
     private static final Pattern NAME_PAT = Pattern.compile("\\[(\\d{1,3})\\]$");
+    private static final Pattern DOT_PAT = Pattern.compile("[.]");
 
     private PropertyObjectUtils() {
         // do nothing
@@ -58,7 +58,7 @@ public class PropertyObjectUtils {
 
         for (String name : properties.stringPropertyNames()) {
             if (name.startsWith(dottedPrefix)) {
-                String[] components = name.substring(pfxlen).split("[.]");
+                String[] components = DOT_PAT.split(name.substring(pfxlen));
                 setProperty(map, components, properties.getProperty(name));
             }
         }
@@ -79,13 +79,13 @@ public class PropertyObjectUtils {
         final int lastComp = names.length - 1;
 
         // process all but the final component
-        for (int comp = 0; comp < lastComp; ++comp) {
+        for (var comp = 0; comp < lastComp; ++comp) {
             node = getNode(node, names[comp]);
         }
 
         // process the final component
         String name = names[lastComp];
-        Matcher matcher = NAME_PAT.matcher(name);
+        var matcher = NAME_PAT.matcher(name);
 
         if (!matcher.find()) {
             // no subscript
@@ -95,7 +95,7 @@ public class PropertyObjectUtils {
 
         // subscripted
         List<Object> array = getArray(node, name.substring(0, matcher.start()));
-        int index = Integer.parseInt(matcher.group(1));
+        var index = Integer.parseInt(matcher.group(1));
         expand(array, index);
         array.set(index, value);
     }
@@ -109,7 +109,7 @@ public class PropertyObjectUtils {
      */
     @SuppressWarnings("unchecked")
     private static Map<String, Object> getNode(Map<String, Object> map, String name) {
-        Matcher matcher = NAME_PAT.matcher(name);
+        var matcher = NAME_PAT.matcher(name);
 
         if (!matcher.find()) {
             // no subscript
@@ -118,7 +118,7 @@ public class PropertyObjectUtils {
 
         // subscripted
         List<Object> array = getArray(map, name.substring(0, matcher.start()));
-        int index = Integer.parseInt(matcher.group(1));
+        var index = Integer.parseInt(matcher.group(1));
         expand(array, index);
 
         Object item = array.get(index);
index ec7157d..f711a05 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020-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.
@@ -89,7 +89,7 @@ public class SpecProperties extends Properties {
             return super.getProperty(key);
         }
 
-        String suffix = key.substring(prefix.length());
+        var suffix = key.substring(prefix.length());
 
         String val = super.getProperty(specPrefix + suffix);
         if (val != null) {
index 44edd42..d689584 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine - Common Modules
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 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.
@@ -38,7 +38,7 @@ public class PropertyException extends Exception {
 
     /**
      * Constructor.
-     * 
+     *
      * @param propName name of the property causing the exception, or {@code null}
      * @param fieldName name of the field causing the exception, or {@code null}
      */
@@ -51,7 +51,7 @@ public class PropertyException extends Exception {
 
     /**
      * Constructor.
-     * 
+     *
      * @param propnm name of the property causing the exception, or {@code null}
      * @param fieldName name of the field causing the exception, or {@code null}
      * @param message error message
@@ -65,7 +65,7 @@ public class PropertyException extends Exception {
 
     /**
      * Constructor.
-     * 
+     *
      * @param propnm name of the property causing the exception, or {@code null}
      * @param fieldName name of the field causing the exception, or {@code null}
      * @param cause cause of the exception
@@ -79,7 +79,7 @@ public class PropertyException extends Exception {
 
     /**
      * Constructor.
-     * 
+     *
      * @param propnm name of the property causing the exception, or {@code null}
      * @param fieldName name of the field causing the exception, or {@code null}
      * @param message error message
@@ -94,7 +94,7 @@ public class PropertyException extends Exception {
 
     /**
      * Get the property name.
-     * 
+     *
      * @return name of the property for which the exception was thrown, or {@code null} if
      *         no name was provided
      */
@@ -104,7 +104,7 @@ public class PropertyException extends Exception {
 
     /**
      * Get the field name.
-     * 
+     *
      * @return name of the field for which the exception was thrown, or {@code null} if no
      *         field was provided
      */
@@ -114,7 +114,7 @@ public class PropertyException extends Exception {
 
     /**
      * Make the message.
-     * 
+     *
      * @param propnm name of the property causing the exception, or {@code null}
      * @param fieldName name of the field causing the exception, or {@code null}
      * @param message error message, never {@code null}
@@ -126,13 +126,13 @@ public class PropertyException extends Exception {
 
     /**
      * Make the message.
-     * 
+     *
      * @param propnm name of the property causing the exception, or {@code null}
      * @param fieldName name of the field causing the exception, or {@code null}
      * @return an error message composed of the two items
      */
     private static String makeMessage(String propnm, String fieldName) {
-        StringBuilder bldr = new StringBuilder(50);
+        var bldr = new StringBuilder(50);
 
         if (propnm == null) {
             bldr.append("property exception");
index 2acc67a..b648fcc 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Ericsson. All rights reserved.
  *  Modifications Copyright (C) 2020 Nordix Foundation.
- *  Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ *  Modifications Copyright (C) 2020-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 +33,7 @@ import java.util.Set;
 import java.util.TreeSet;
 import java.util.jar.JarEntry;
 import java.util.jar.JarFile;
+import java.util.regex.Pattern;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -44,6 +45,8 @@ public abstract class ResourceUtils {
     // Get a reference to the logger
     private static final Logger LOGGER = LoggerFactory.getLogger(ResourceUtils.class);
 
+    private static final Pattern SLASH_PAT = Pattern.compile("/");
+
     // The length of byte buffers used to read resources into strings
     private static final int BYTE_BUFFER_LENGH = 1024;
 
@@ -66,7 +69,7 @@ public abstract class ResourceUtils {
      */
     public static URL getUrl4Resource(final String resourceName) {
         // Check the local fine system first
-        final URL urlToResource = getLocalFile(resourceName);
+        final var urlToResource = getLocalFile(resourceName);
 
         // Check if this is a local file
         if (urlToResource != null) {
@@ -92,8 +95,8 @@ public abstract class ResourceUtils {
         }
 
         // Read the stream contents in to an output stream
-        final ByteArrayOutputStream resourceOutputStreamBuffer = new ByteArrayOutputStream();
-        final byte[] resourceBuffer = new byte[BYTE_BUFFER_LENGH];
+        final var resourceOutputStreamBuffer = new ByteArrayOutputStream();
+        final var resourceBuffer = new byte[BYTE_BUFFER_LENGH];
         int length;
         try {
             while ((length = resourceStream.read(resourceBuffer)) != -1) {
@@ -116,7 +119,7 @@ public abstract class ResourceUtils {
      */
     public static InputStream getResourceAsStream(final String resourceName) {
         // Find a URL to the resource first
-        final URL urlToResource = getUrl4Resource(resourceName);
+        final var urlToResource = getUrl4Resource(resourceName);
 
         // Check if the resource exists
         if (urlToResource == null) {
@@ -143,11 +146,11 @@ public abstract class ResourceUtils {
      */
     public static URL getUrlResource(final String resourceName) {
         try {
-            final ClassLoader classLoader = ResourceUtils.class.getClassLoader();
+            final var classLoader = ResourceUtils.class.getClassLoader();
 
-            final String[] fileParts = resourceName.split("/");
+            final String[] fileParts = SLASH_PAT.split(resourceName);
             // Read the resource
-            URL url = classLoader.getResource(resourceName);
+            var url = classLoader.getResource(resourceName);
 
             // Check if the resource is defined
             if (url != null) {
@@ -178,8 +181,8 @@ public abstract class ResourceUtils {
     public static URL getLocalFile(final String resourceName) {
         try {
             // Input might already be in URL format
-            final URL ret = new URL(resourceName);
-            final File f = new File(ret.toURI());
+            final var ret = new URL(resourceName);
+            final var f = new File(ret.toURI());
             if (f.exists()) {
                 return ret;
             }
@@ -188,10 +191,10 @@ public abstract class ResourceUtils {
         }
 
         try {
-            final File f = new File(resourceName);
+            final var f = new File(resourceName);
             // Check if the file exists
             if (f.exists()) {
-                final URL urlret = f.toURI().toURL();
+                final var urlret = f.toURI().toURL();
                 LOGGER.debug("resource \"{}\" was found on the local file system", f.toURI().toURL());
                 return urlret;
             } else {
@@ -215,7 +218,7 @@ public abstract class ResourceUtils {
             return null;
         }
 
-        URL modelFileUrl = getUrl4Resource(resource);
+        var modelFileUrl = getUrl4Resource(resource);
         if (modelFileUrl != null) {
             return modelFileUrl.getPath();
         } else {
@@ -231,7 +234,7 @@ public abstract class ResourceUtils {
      */
     public static Set<String> getDirectoryContents(final String resourceDirectoryName) {
         // Find the location of the resource, is it in a Jar or on the local file system?
-        URL directoryUrl = ResourceUtils.getUrl4Resource(resourceDirectoryName);
+        var directoryUrl = ResourceUtils.getUrl4Resource(resourceDirectoryName);
 
         if (directoryUrl == null) {
             LOGGER.debug("resource \"{}\" was not found", resourceDirectoryName);
@@ -259,7 +262,7 @@ public abstract class ResourceUtils {
      */
     public static Set<String> getDirectoryContentsLocal(final URL localResourceDirectoryUrl,
             final String resourceDirectoryName) {
-        File localDirectory = new File(localResourceDirectoryUrl.getFile());
+        var localDirectory = new File(localResourceDirectoryUrl.getFile());
 
         if (!localDirectory.isDirectory()) {
             LOGGER.debug("resource \"{}\" is not a directory", resourceDirectoryName);
@@ -290,12 +293,12 @@ public abstract class ResourceUtils {
             final String resourceDirectoryName) {
         String dirNameWithSlash = resourceDirectoryName + "/";
         int minLength = dirNameWithSlash.length() + 1;
-        File jarResourceDirectory = new File(jarResourceDirectoryUrl.getPath());
+        var jarResourceDirectory = new File(jarResourceDirectoryUrl.getPath());
         String jarFileName = jarResourceDirectory.getParent().replaceFirst("^file:", "").replaceFirst("!.*$", "");
 
         Set<String> localDirectorySet = new TreeSet<>();
 
-        try (JarFile jarFile = new JarFile(jarFileName)) {
+        try (var jarFile = new JarFile(jarFileName)) {
             Enumeration<JarEntry> entries = jarFile.entries();
 
             while (entries.hasMoreElements()) {
index 2810c7b..6039e08 100644 (file)
@@ -1,7 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2019 Nordix Foundation.
- *  Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ *  Modifications Copyright (C) 2020-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 +50,7 @@ public abstract class TextFileUtils {
      * @throws IOException on errors reading text from the file
      */
     public static String getTextFileAsString(final String textFilePath) throws IOException {
-        final File textFile = new File(textFilePath);
+        final var textFile = new File(textFilePath);
         return Files.readString(textFile.toPath());
     }
 
@@ -62,7 +62,7 @@ public abstract class TextFileUtils {
      * @throws IOException on errors reading text from the file
      */
     public static void putStringAsTextFile(final String outString, final String textFilePath) throws IOException {
-        final File textFile = new File(textFilePath);
+        final var textFile = new File(textFilePath);
         if (!textFile.getParentFile().exists()) {
             textFile.getParentFile().mkdirs();
         }
@@ -100,9 +100,9 @@ public abstract class TextFileUtils {
      * @throws IOException on errors reading text from the file
      */
     public static String getReaderAsString(final Reader textReader) throws IOException {
-        final StringBuilder builder = new StringBuilder();
+        final var builder = new StringBuilder();
         int charsRead = -1;
-        final char[] chars = new char[READER_CHAR_BUFFER_SIZE_4096];
+        final var chars = new char[READER_CHAR_BUFFER_SIZE_4096];
         do {
             charsRead = textReader.read(chars);
             if (charsRead > 0) {
index 50e85d9..3de6df3 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * 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.
@@ -106,7 +106,7 @@ public class CryptoUtils implements CryptoCoder {
      * @return The encrypted String
      */
     public static String encrypt(String value, String secretKey) {
-        SecretKeySpec keySpec = readSecretKeySpec(secretKey);
+        var keySpec = readSecretKeySpec(secretKey);
         return encryptValue(value, keySpec);
     }
 
@@ -119,10 +119,10 @@ public class CryptoUtils implements CryptoCoder {
             return value;
         }
         try {
-            Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS);
-            byte[] iv = new byte[IV_BLOCK_SIZE_IN_BYTES];
+            var cipher = Cipher.getInstance(ALGORITHM_DETAILS);
+            var iv = new byte[IV_BLOCK_SIZE_IN_BYTES];
             RANDOM.nextBytes(iv);
-            GCMParameterSpec ivspec = new GCMParameterSpec(TAG_SIZE_IN_BITS, iv);
+            var ivspec = new GCMParameterSpec(TAG_SIZE_IN_BITS, iv);
             cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
 
             return "enc:" + DatatypeConverter.printBase64Binary(
@@ -157,7 +157,7 @@ public class CryptoUtils implements CryptoCoder {
      * @return The String decrypted if string begin with 'enc:'
      */
     public static String decrypt(String value, String secretKey) {
-        SecretKeySpec keySpec = readSecretKeySpec(secretKey);
+        var keySpec = readSecretKeySpec(secretKey);
         if (keySpec != null) {
             return decryptValue(value, keySpec);
         } else {
@@ -173,11 +173,11 @@ public class CryptoUtils implements CryptoCoder {
             throw new IllegalArgumentException("Invalid size on input value");
         }
         try {
-            String pureValue = value.substring(4);
+            var pureValue = value.substring(4);
             byte[] encryptedValue = DatatypeConverter.parseBase64Binary(pureValue);
 
-            Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS);
-            GCMParameterSpec ivspec = new GCMParameterSpec(TAG_SIZE_IN_BITS,
+            var cipher = Cipher.getInstance(ALGORITHM_DETAILS);
+            var ivspec = new GCMParameterSpec(TAG_SIZE_IN_BITS,
                     ArrayUtils.subarray(encryptedValue, 0, IV_BLOCK_SIZE_IN_BYTES));
             byte[] realData = ArrayUtils.subarray(encryptedValue, IV_BLOCK_SIZE_IN_BYTES, encryptedValue.length);
 
index 527113d..46e006b 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP COMMON
  * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2019 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,7 +21,6 @@
 
 package org.onap.policy.common.utils.validation;
 
-import com.google.re2j.Matcher;
 import com.google.re2j.Pattern;
 import lombok.Data;
 import lombok.NoArgsConstructor;
@@ -56,7 +55,7 @@ public class Version implements Comparable<Version> {
      * @param versionString the version string
      */
     public Version(@NonNull final String versionString) {
-        Version newVersion = makeVersion("String", "constructor", versionString);
+        var newVersion = makeVersion("String", "constructor", versionString);
 
         if (newVersion != null) {
             this.major = newVersion.major;
@@ -79,7 +78,7 @@ public class Version implements Comparable<Version> {
      *         that does not match the major.minor.patch form)
      */
     public static Version makeVersion(String type, String name, String versionText) {
-        Matcher matcher = VERSION_PAT.matcher(versionText);
+        var matcher = VERSION_PAT.matcher(versionText);
         if (!matcher.matches()) {
             logger.info("invalid version for {} {}: {}", type, name, versionText);
             return null;
@@ -113,7 +112,7 @@ public class Version implements Comparable<Version> {
 
     @Override
     public int compareTo(Version other) {
-        int result = Integer.compare(major, other.major);
+        var result = Integer.compare(major, other.major);
         if (result != 0) {
             return result;
         }