From fe5d78724f723a451ddc0d7cc41d6fc60092b314 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Thu, 13 Jun 2019 12:34:17 -0400 Subject: More sonar fixes in policy/common Note: this does not increase code coverage, but should fix other code issues. Resolved cyclomatic complexity issue in ParameterValidationResult. Refactored duplicate code in GroupValidationResult. Removed IOException from NetworkUtil "throws". Replaced null/empty string tests with StringUtils.isBlank(). Added @FunctionalInterface where needed. Replaced anonymous classes with lambda expressions. Replaced duplicate strings with a constant. Added private constructors for utility classes. Removed sleep() from tests. Removed unused parameter from method call. Made some protected methods private. Compute integrity monitor's state-transition table once. Use for-loop instead of iterator. Moved constructors. Fixed some checkstyle issues (tabs => spaces, trailing spaces). Change-Id: I9a962ca45c4ff3f212c6014da799d06f07b232ef Issue-ID: POLICY-1791 Signed-off-by: Jim Hahn --- .../policy/common/logging/eelf/PolicyLogger.java | 114 ++++++++-------- .../parameters/CommonGroupValidationResult.java | 137 +++++++++++++++++++ .../parameters/GroupMapValidationResult.java | 98 ++----------- .../common/parameters/GroupValidationResult.java | 93 ++----------- .../parameters/ParameterValidationResult.java | 35 +++-- .../parameters/testclasses/TestParametersL00.java | 5 +- .../parameters/testclasses/TestParametersL10.java | 3 +- .../TestParametersL0_2_Invalid.txt | 2 +- .../TestParametersL0_2_Observation.txt | 2 +- .../TestParametersL0_2_Warning.txt | 2 +- .../TestParametersL0_3_Invalid.txt | 4 +- .../TestParametersL0_3_Observation.txt | 4 +- .../TestParametersL0_3_Warning.txt | 4 +- .../org/onap/policy/common/ia/AuditThread.java | 39 +++--- .../java/org/onap/policy/common/ia/DbAudit.java | 30 ++-- .../org/onap/policy/common/im/StateTransition.java | 152 ++++++++++----------- .../policy/common/im/jmx/JmxAgentConnection.java | 26 ++-- .../common/im/jpa/StateManagementEntity.java | 16 +-- .../src/main/resources/META-INF/persistence.xml | 53 +++---- .../src/test/resources/logback-test.xml | 47 ++++--- .../endpoints/http/server/test/HttpServerTest.java | 94 +++++-------- .../policy/common/utils/network/NetworkUtil.java | 5 +- 22 files changed, 467 insertions(+), 498 deletions(-) create mode 100644 common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java index e3a7ab3f..87c4c571 100644 --- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -132,6 +132,10 @@ public class PolicyLogger { } } + private PolicyLogger() { + + } + public static Level getDebugLevel() { return debugLevel; } @@ -238,7 +242,7 @@ public class PolicyLogger { /** * Populates MDC info. - * + * * @param transId the transaction ID * @return String */ @@ -301,7 +305,7 @@ public class PolicyLogger { /** * Populate MDC Info using the passed in mdcInfo. - * + * * @param transId the transaction ID * @param mdcInfo the MDC info * @return String @@ -345,7 +349,7 @@ public class PolicyLogger { /** * Sets transaction Id to MDC. - * + * * @param eventObject event object */ public static void postMDCInfoForEvent(Object eventObject) { @@ -383,7 +387,7 @@ public class PolicyLogger { /** * Sets transaction Id to MDC. - * + * * @param transId the transaction ID */ public static void setTransId(String transId) { @@ -393,7 +397,7 @@ public class PolicyLogger { /** * Returns current transaction Id used in MDC. - * + * * @return transId */ public static String getTransId() { @@ -403,7 +407,7 @@ public class PolicyLogger { /** * Resets transaction Id in MDC for the rule triggered by this event. - * + * * @param transId the transaction ID * @return String */ @@ -436,7 +440,7 @@ public class PolicyLogger { /** * Resets transaction Id in MDC for the rule triggered by this event. - * + * * @param obj object */ public static void postMDCUUIDForTriggeredRule(Object obj) { @@ -448,7 +452,7 @@ public class PolicyLogger { // ************************************************************************************************ /** * Records the Info event with String [] arguments. - * + * * @param msg the message code * @param className the class name * @param arguments the messages @@ -460,7 +464,7 @@ public class PolicyLogger { /** * Records only one String message with its class name. - * + * * @param className the class name * @param arg0 the message */ @@ -472,7 +476,7 @@ public class PolicyLogger { /** * Records only one String message. - * + * * @param arg0 the message */ public static void info(Object arg0) { @@ -482,7 +486,7 @@ public class PolicyLogger { /** * Records a message with passed in message code, Throwable object, a list of string values. - * + * * @param msg the message code * @param arg0 the throwable * @param arguments the messages @@ -496,7 +500,7 @@ public class PolicyLogger { /** * Records a message with passed in message code, class name, Throwable object, a list of string * values. - * + * * @param msg the message code * @param className the class name * @param arg0 the throwable @@ -510,7 +514,7 @@ public class PolicyLogger { /** * Records only one String message with its class name. - * + * * @param arg0 log message * @param className class name */ @@ -521,7 +525,7 @@ public class PolicyLogger { /** * Records only one String message. - * + * * @param arg0 the message */ public static void warn(Object arg0) { @@ -531,7 +535,7 @@ public class PolicyLogger { /** * Records only one String message without its class name passed in. - * + * * @param arg0 the message */ public static void warn(String arg0) { @@ -541,7 +545,7 @@ public class PolicyLogger { /** * Records a message with passed in message code, class name and a list of string values. - * + * * @param msg the message code * @param className the class name * @param arguments the messages @@ -553,7 +557,7 @@ public class PolicyLogger { /** * Records a message with passed in message code, Throwable object, a list of string values. - * + * * @param msg the message code * @param arg0 the throwable * @param arguments the messages @@ -566,7 +570,7 @@ public class PolicyLogger { /** * Records a message with passed in message code, Throwable object, a list of string values. - * + * * @param msg the message code * @param className the class name * @param arg0 the throwable @@ -580,7 +584,7 @@ public class PolicyLogger { /** * Records only one String message with its class name. - * + * * @param className class name * @param arg0 log message */ @@ -596,7 +600,7 @@ public class PolicyLogger { /** * Records only one String message. - * + * * @param arg0 the message */ public static void error(String arg0) { @@ -613,7 +617,7 @@ public class PolicyLogger { /** * Records only one String message. - * + * * @param arg0 the message */ public static void error(Object arg0) { @@ -630,7 +634,7 @@ public class PolicyLogger { /** * Records a message with passed in message code, Throwable object, a list of string values. - * + * * @param msg the message code * @param arg0 the throwable * @param arguments the messages @@ -651,7 +655,7 @@ public class PolicyLogger { /** * Records a message with passed in message code, class name, Throwable object, a list of string * values. - * + * * @param msg the message code * @param className the class name * @param arg0 the throwable @@ -672,7 +676,7 @@ public class PolicyLogger { /** * Records a message with passed in message code and a list of string values. - * + * * @param msg the message code * @param arguments the messages */ @@ -690,7 +694,7 @@ public class PolicyLogger { /** * Records a message with passed in message code and a list of string values. - * + * * @param msg the message code * @param arguments the messages */ @@ -701,7 +705,7 @@ public class PolicyLogger { /** * Records only one String message with its class name. - * + * * @param className the class name * @param arg0 the message */ @@ -712,7 +716,7 @@ public class PolicyLogger { /** * Records only one String message. - * + * * @param arg0 the message */ public static void debug(String arg0) { @@ -722,7 +726,7 @@ public class PolicyLogger { /** * Records only one String message. - * + * * @param arg0 the message */ public static void debug(Object arg0) { @@ -733,7 +737,7 @@ public class PolicyLogger { /** * Records a message with passed in message code, hrowable object, a list of string values. - * + * * @param msg the message code * @param arg0 the throwable * @param arguments the messages @@ -747,7 +751,7 @@ public class PolicyLogger { /** * Records a message with passed in message code, class name, Throwable object, a list of * string. values - * + * * @param msg the message code * @param className the class name * @param arg0 the throwable @@ -761,7 +765,7 @@ public class PolicyLogger { /** * Records only one String message with its class name. - * + * * @param className the class name * @param arg0 the message */ @@ -773,7 +777,7 @@ public class PolicyLogger { /** * Records only one String message. - * + * * @param arg0 the message */ public static void audit(Object arg0) { @@ -832,7 +836,7 @@ public class PolicyLogger { /** * Records only one String message with its class name. - * + * * @param className the class name * @param arg0 the message */ @@ -843,7 +847,7 @@ public class PolicyLogger { /** * Records only one String message. - * + * * @param arg0 the message */ public static void trace(Object arg0) { @@ -854,7 +858,7 @@ public class PolicyLogger { /** * Records the starting time of the event with its request Id as the key. - * + * * @param eventId the event ID */ public static void recordAuditEventStart(String eventId) { @@ -895,7 +899,7 @@ public class PolicyLogger { /** * Records the starting time of the event with its request Id as the key. - * + * * @param eventId the event ID */ public static void recordAuditEventStart(UUID eventId) { @@ -914,7 +918,7 @@ public class PolicyLogger { /** * Records the ending time of the event with its request Id as the key. - * + * * @param eventId the event ID * @param rule the rule */ @@ -933,7 +937,7 @@ public class PolicyLogger { /** * Records the ending time of the event with its request Id as the key. - * + * * @param eventId the event ID * @param rule the rule * @param policyVersion the policy version @@ -953,7 +957,7 @@ public class PolicyLogger { /** * Records the ending time of the event with its request Id as the key. - * + * * @param eventId the event ID * @param rule the rule * @param policyVersion the policy version @@ -971,7 +975,7 @@ public class PolicyLogger { /** * Records the ending time of the event with its request Id as the key. - * + * * @param eventId the event ID * @param rule the rule */ @@ -987,7 +991,7 @@ public class PolicyLogger { /** * Records the ending time of the event with its request Id as the key. - * + * * @param eventId the event ID * @param rule the rule * @param policyVersion the policy version @@ -1012,7 +1016,7 @@ public class PolicyLogger { /** * Records the ending time of the event with its request Id as the key. - * + * * @param eventId the event ID * @param rule the rule */ @@ -1044,7 +1048,7 @@ public class PolicyLogger { /** * Records the audit with an event starting and ending times. - * + * * @param eventId the event ID * @param rule the rule * @param startTime the start time @@ -1091,7 +1095,7 @@ public class PolicyLogger { /** * Records the metrics with an event Id and log message. - * + * * @param eventId the event ID * @param arg1 the message */ @@ -1107,7 +1111,7 @@ public class PolicyLogger { /** * Records the metrics with an event Id, class name and log message. - * + * * @param eventId the event ID * @param className the class name * @param arg1 the message @@ -1124,7 +1128,7 @@ public class PolicyLogger { /** * Records the metrics with an event Id and log message. - * + * * @param eventId the event ID * @param arg1 the message */ @@ -1140,7 +1144,7 @@ public class PolicyLogger { /** * Records a String message for metrics logs. - * + * * @param arg0 the message */ public static void recordMetricEvent(String arg0) { @@ -1152,7 +1156,7 @@ public class PolicyLogger { /** * Records the metrics event with a String message. - * + * * @param arg0 the message */ public static void metrics(String arg0) { @@ -1162,7 +1166,7 @@ public class PolicyLogger { /** * Records the metrics event with a class name and a String message. - * + * * @param arg0 the message */ public static void metrics(String className, Object arg0) { @@ -1174,7 +1178,7 @@ public class PolicyLogger { /** * Records the metrics event with a String message. - * + * * @param arg0 the message */ public static void metrics(Object arg0) { @@ -1186,7 +1190,7 @@ public class PolicyLogger { /** * Records the metrics event with a String message. - * + * * @param arg0 the message */ public static void metricsPrintln(String arg0) { @@ -1196,7 +1200,7 @@ public class PolicyLogger { /** * Removes all the return lines from the printStackTrace. - * + * * @param throwable the throwable * @param arguments the messages */ diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java new file mode 100644 index 00000000..f35d1970 --- /dev/null +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/CommonGroupValidationResult.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * This class holds the result of the validation of a parameter group. + */ +public abstract class CommonGroupValidationResult implements ValidationResult { + + + private final String messagePrefix; + + /** + * Validation status for the entire class. + */ + protected ValidationStatus status = ValidationStatus.CLEAN; + + /** + * Status message. + */ + protected String message; + + /** + * Validation results for each parameter in the group. + */ + protected final Map validationResultMap = new LinkedHashMap<>(); + + + /** + * Constructs the object. + * + * @param messagePrefix status message prefix + */ + public CommonGroupValidationResult(String messagePrefix) { + this.messagePrefix = messagePrefix; + this.message = messagePrefix + status.toString(); + } + + /** + * Gets the status of validation. + * + * @return the status + */ + @Override + public ValidationStatus getStatus() { + return status; + } + + /** + * Set the validation result on a parameter group. + * + * @param status The validation status the parameter group is receiving + * @param message The validation message explaining the validation status + */ + @Override + public void setResult(ValidationStatus status, String message) { + setResult(status); + this.message = message; + } + + /** + * Set the validation result on a parameter group. On a sequence of calls, the most + * serious validation status is recorded, assuming the status enum ordinal increase in + * order of severity + * + * @param status The validation status the parameter group is receiving + */ + public void setResult(final ValidationStatus status) { + if (this.status.ordinal() < status.ordinal()) { + this.status = status; + this.message = messagePrefix + status; + } + } + + /** + * Gets the validation result. + * + * @param initialIndentation the indentation to use on the main result output + * @param subIndentation the indentation to use on sub parts of the result output + * @param showClean output information on clean fields + * @return the result + */ + @Override + public String getResult(final String initialIndentation, final String subIndentation, final boolean showClean) { + if (status == ValidationStatus.CLEAN && !showClean) { + return null; + } + + StringBuilder result = new StringBuilder(); + + result.append(initialIndentation); + + addGroupTypeName(result); + + result.append(status); + result.append(", "); + result.append(message); + result.append('\n'); + + for (ValidationResult fieldResult : validationResultMap.values()) { + String msg = fieldResult.getResult(initialIndentation + subIndentation, subIndentation, showClean); + if (msg != null) { + result.append(msg); + } + } + + return result.toString(); + } + + /** + * Adds the group type and name to the result string. + * + * @param result result string + */ + protected abstract void addGroupTypeName(StringBuilder result); +} diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java index 3baacb1f..2a616dba 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupMapValidationResult.java @@ -1,19 +1,20 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 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========================================================= */ @@ -21,23 +22,15 @@ package org.onap.policy.common.parameters; import java.lang.reflect.Field; -import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; /** * This class holds the result of the validation of a map of parameter groups. */ -public class GroupMapValidationResult implements ValidationResult { +public class GroupMapValidationResult extends CommonGroupValidationResult { // The name of the parameter group map final String mapParameterName; - - // Validation status for the entire parameter class - private ValidationStatus status = ValidationStatus.CLEAN; - private String message = ParameterConstants.PARAMETER_GROUP_MAP_HAS_STATUS_MESSAGE + status.toString(); - - // Validation results for each parameter in the group - private final Map validationResultMap = new LinkedHashMap<>(); /** * Constructor, create the group map validation result. @@ -46,6 +39,8 @@ public class GroupMapValidationResult implements ValidationResult { * @param mapObject the value of the map parameter field */ protected GroupMapValidationResult(final Field field, final Object mapObject) { + super(ParameterConstants.PARAMETER_GROUP_MAP_HAS_STATUS_MESSAGE); + this.mapParameterName = field.getName(); // Cast the map object to a map of parameter groups keyed by string, we can't type check maps @@ -72,45 +67,9 @@ public class GroupMapValidationResult implements ValidationResult { return mapParameterName; } - /** - * Gets the status of validation. - * - * @return the status - */ - @Override - public ValidationStatus getStatus() { - return status; - } - - /** - * Set the validation result on on a parameter group. - * - * @param status The validation status the field is receiving - * @param message The validation message explaining the validation status - */ - @Override - public void setResult(final ValidationStatus status, final String message) { - setResult(status); - this.message = message; - } - - /** - * Set the validation result on on a parameter group. - * - * @param status The validation status the field is receiving - */ - public void setResult(final ValidationStatus status) { - // We record the most serious validation status, assuming the status enum ordinals - // increase in order of severity - if (this.status.ordinal() < status.ordinal()) { - this.status = status; - this.message = ParameterConstants.PARAMETER_GROUP_HAS_STATUS_MESSAGE + status.toString(); - } - } - /** * Set the validation result on a parameter map entry. - * + * * @param entryName The name of the parameter map entry * @param status The validation status for the entry * @param message The validation message for the entry @@ -122,14 +81,14 @@ public class GroupMapValidationResult implements ValidationResult { } // Set the status of the parameter group and replace the field result - validationResult.setResult(status, message); + validationResult.setResult(status, message); this.setResult(status); } /** * Set the validation result on a parameter map entry. - * + * * @param entryName The name of the parameter map entry * @param mapEntryValidationResult The validation result for the entry */ @@ -144,39 +103,10 @@ public class GroupMapValidationResult implements ValidationResult { this.setResult(mapEntryValidationResult.getStatus()); } - /** - * Gets the validation result. - * - * @param initialIndentation the indentation to use on the main result output - * @param subIndentation the indentation to use on sub parts of the result output - * @param showClean output information on clean fields - * @return the result - */ @Override - public String getResult(final String initialIndentation, final String subIndentation, final boolean showClean) { - if (status == ValidationStatus.CLEAN && !showClean) { - return null; - } - - StringBuilder validationResultBuilder = new StringBuilder(); - - validationResultBuilder.append(initialIndentation); - validationResultBuilder.append("parameter group map \""); - validationResultBuilder.append(mapParameterName); - validationResultBuilder.append("\" "); - validationResultBuilder.append(status); - validationResultBuilder.append(", "); - validationResultBuilder.append(message); - validationResultBuilder.append('\n'); - - for (ValidationResult fieldResult : validationResultMap.values()) { - String fieldResultMessage = fieldResult.getResult(initialIndentation + subIndentation, subIndentation, - showClean); - if (fieldResultMessage != null) { - validationResultBuilder.append(fieldResultMessage); - } - } - - return validationResultBuilder.toString(); + protected void addGroupTypeName(StringBuilder result) { + result.append("parameter group map \""); + result.append(mapParameterName); + result.append("\" "); } } \ No newline at end of file diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java index 6da36c19..3dc01299 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/GroupValidationResult.java @@ -1,4 +1,4 @@ -/* +/*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. * Modifications Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. @@ -27,33 +27,26 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; - import org.apache.commons.lang3.StringUtils; /** * This class holds the result of the validation of a parameter group. */ -public class GroupValidationResult implements ValidationResult { +public class GroupValidationResult extends CommonGroupValidationResult { // The parameter group which the validation result applies private final ParameterGroup parameterGroup; - // Validation status for the entire parameter class - private ValidationStatus status = ValidationStatus.CLEAN; - private String message = ParameterConstants.PARAMETER_GROUP_HAS_STATUS_MESSAGE + status.toString(); - - // Validation results for each parameter in the group - private final Map validationResultMap = new LinkedHashMap<>(); - /** * Constructor, create the field validation result with default arguments. * * @param parameterGroup the parameter group being validated */ public GroupValidationResult(final ParameterGroup parameterGroup) { + super(ParameterConstants.PARAMETER_GROUP_HAS_STATUS_MESSAGE); + this.parameterGroup = parameterGroup; // Parameter group definitions may be optional @@ -244,42 +237,6 @@ public class GroupValidationResult implements ValidationResult { return parameterGroup.getName(); } - /** - * Gets the status of validation. - * - * @return the status - */ - @Override - public ValidationStatus getStatus() { - return status; - } - - /** - * Set the validation result on a parameter group. - * - * @param status The validation status the parameter group is receiving - * @param message The validation message explaining the validation status - */ - @Override - public void setResult(ValidationStatus status, String message) { - setResult(status); - this.message = message; - } - - /** - * Set the validation result on a parameter group. On a sequence of calls, the most serious validation status is - * recorded, assuming the status enum ordinal increase in order of severity - * - * @param status The validation status the parameter group is receiving - */ - public void setResult(final ValidationStatus status) { - // - if (this.status.ordinal() < status.ordinal()) { - this.status = status; - this.message = ParameterConstants.PARAMETER_GROUP_HAS_STATUS_MESSAGE + status.toString(); - } - } - /** * Set the validation result on a parameter in a parameter group. * @@ -375,47 +332,19 @@ public class GroupValidationResult implements ValidationResult { this.setResult(status); } - /** - * Gets the validation result. - * - * @param initialIndentation the indentation to use on the main result output - * @param subIndentation the indentation to use on sub parts of the result output - * @param showClean output information on clean fields - * @return the result - */ @Override - public String getResult(final String initialIndentation, final String subIndentation, final boolean showClean) { - if (status == ValidationStatus.CLEAN && !showClean) { - return null; - } - - StringBuilder validationResultBuilder = new StringBuilder(); - - validationResultBuilder.append(initialIndentation); - validationResultBuilder.append("parameter group \""); + protected void addGroupTypeName(StringBuilder result) { + result.append("parameter group \""); if (parameterGroup != null) { - validationResultBuilder.append(parameterGroup.getName()); - validationResultBuilder.append("\" type \""); - validationResultBuilder.append(parameterGroup.getClass().getCanonicalName()); + result.append(parameterGroup.getName()); + result.append("\" type \""); + result.append(parameterGroup.getClass().getCanonicalName()); } else { - validationResultBuilder.append("UNDEFINED"); - } - validationResultBuilder.append("\" "); - validationResultBuilder.append(status); - validationResultBuilder.append(", "); - validationResultBuilder.append(message); - validationResultBuilder.append('\n'); - - for (ValidationResult fieldResult : validationResultMap.values()) { - String fieldResultMessage = fieldResult.getResult(initialIndentation + subIndentation, subIndentation, - showClean); - if (fieldResultMessage != null) { - validationResultBuilder.append(fieldResultMessage); - } + result.append("UNDEFINED"); } - return validationResultBuilder.toString(); + result.append("\" "); } diff --git a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java index 0b66a533..2c367a30 100644 --- a/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java +++ b/common-parameters/src/main/java/org/onap/policy/common/parameters/ParameterValidationResult.java @@ -61,15 +61,34 @@ public class ParameterValidationResult implements ValidationResult { } } else if (parameterValue instanceof Number) { - Min minAnnot = field.getAnnotation(Min.class); - if (minAnnot != null && ((Number) parameterValue).longValue() < minAnnot.value()) { - setResult(ValidationStatus.INVALID, "must be >= " + minAnnot.value()); - } + checkMinValue(field, parameterValue); + checkMaxValue(field, parameterValue); + } + } - Max maxAnnot = field.getAnnotation(Max.class); - if (maxAnnot != null && ((Number) parameterValue).longValue() > maxAnnot.value()) { - setResult(ValidationStatus.INVALID, "must be <= " + maxAnnot.value()); - } + /** + * Checks the minimum value of a field, if it has the "@Min" annotation. + * + * @param field field whose value is being validated + * @param parameterValue field's value + */ + private void checkMinValue(final Field field, final Object parameterValue) { + Min minAnnot = field.getAnnotation(Min.class); + if (minAnnot != null && ((Number) parameterValue).longValue() < minAnnot.value()) { + setResult(ValidationStatus.INVALID, "must be >= " + minAnnot.value()); + } + } + + /** + * Checks the maximum value of a field, if it has the "@Max" annotation. + * + * @param field field whose value is being validated + * @param parameterValue field's value + */ + private void checkMaxValue(final Field field, final Object parameterValue) { + Max maxAnnot = field.getAnnotation(Max.class); + if (maxAnnot != null && ((Number) parameterValue).longValue() > maxAnnot.value()) { + setResult(ValidationStatus.INVALID, "must be <= " + maxAnnot.value()); } } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java index ea5ae853..2b41d0fb 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java @@ -24,6 +24,7 @@ package org.onap.policy.common.parameters.testclasses; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import org.apache.commons.lang3.StringUtils; import org.onap.policy.common.parameters.GroupValidationResult; import org.onap.policy.common.parameters.ParameterConstants; import org.onap.policy.common.parameters.ParameterGroupImpl; @@ -163,11 +164,11 @@ public class TestParametersL00 extends ParameterGroupImpl { public GroupValidationResult validate() { GroupValidationResult validationResult = super.validate(); - if (getName() == null || getName().trim().length() == 0) { + if (StringUtils.isBlank(getName())) { validationResult.setResult("name", ValidationStatus.INVALID, "name must be a non-blank string"); } - if (l00StringField == null || l00StringField.trim().length() == 0) { + if (StringUtils.isBlank(l00StringField)) { validationResult.setResult(L00_STRING_FIELD, ValidationStatus.INVALID, "l00StringField must be a non-blank string"); } else if (l00StringField.equals(L00_STRING_FIELD)) { diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java index 2fba9ba2..e1642beb 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java @@ -24,6 +24,7 @@ package org.onap.policy.common.parameters.testclasses; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import org.apache.commons.lang3.StringUtils; import org.onap.policy.common.parameters.GroupValidationResult; import org.onap.policy.common.parameters.ParameterConstants; import org.onap.policy.common.parameters.ParameterGroupImpl; @@ -146,7 +147,7 @@ public class TestParametersL10 extends ParameterGroupImpl { public GroupValidationResult validate() { GroupValidationResult validationResult = super.validate(); - if (l10StringField == null || l10StringField.trim().length() == 0) { + if (StringUtils.isBlank(l10StringField)) { validationResult.setResult(L10_STRING_FIELD, ValidationStatus.INVALID, "l10StringField must be a non-blank string"); } else if (l10StringField.equals(L10_STRING_FIELD)) { diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt index d9301997..412a36c1 100644 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt +++ b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt @@ -7,7 +7,7 @@ parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclass parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group map "l00LGenericNestedMap" INVALID, parameter group has status INVALID + parameter group map "l00LGenericNestedMap" INVALID, parameter group map has status INVALID parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt index e0e78ccb..c1989226 100644 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt +++ b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt @@ -7,7 +7,7 @@ parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclass parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group map "l00LGenericNestedMap" OBSERVATION, parameter group has status OBSERVATION + parameter group map "l00LGenericNestedMap" OBSERVATION, parameter group map has status OBSERVATION parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt index d03ecdf5..380ded8f 100644 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt +++ b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt @@ -7,7 +7,7 @@ parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclass parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group map "l00LGenericNestedMap" WARNING, parameter group has status WARNING + parameter group map "l00LGenericNestedMap" WARNING, parameter group map has status WARNING parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt index e45a7a6b..12bce5c3 100644 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt +++ b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt @@ -10,7 +10,7 @@ parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclass parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group map "l10LGenericNestedMap" INVALID, parameter group has status INVALID + parameter group map "l10LGenericNestedMap" INVALID, parameter group map has status INVALID parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string @@ -20,7 +20,7 @@ parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclass parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string - parameter group map "l00LGenericNestedMap" INVALID, parameter group has status INVALID + parameter group map "l00LGenericNestedMap" INVALID, parameter group map has status INVALID parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" INVALID, parameter group has status INVALID field "lgenericIntField" type "int" value "-1" INVALID, lgenericIntField must be a positive integer field "lgenericStringField" type "java.lang.String" value "" INVALID, must be a non-blank string diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt index da943135..36517cef 100644 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt +++ b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt @@ -10,7 +10,7 @@ parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclass parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group map "l10LGenericNestedMap" OBSERVATION, parameter group has status OBSERVATION + parameter group map "l10LGenericNestedMap" OBSERVATION, parameter group map has status OBSERVATION parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful @@ -20,7 +20,7 @@ parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclass parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful - parameter group map "l00LGenericNestedMap" OBSERVATION, parameter group has status OBSERVATION + parameter group map "l00LGenericNestedMap" OBSERVATION, parameter group map has status OBSERVATION parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" OBSERVATION, parameter group has status OBSERVATION field "lgenericIntField" type "int" value "2" OBSERVATION, this field has been set to 2 field "lgenericStringField" type "java.lang.String" value "aString" OBSERVATION, this value for name is unhelpful diff --git a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt index 67a0932e..28747670 100644 --- a/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt +++ b/common-parameters/src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt @@ -10,7 +10,7 @@ parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclass parameter group "l10LGenericNested1" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group map "l10LGenericNestedMap" WARNING, parameter group has status WARNING + parameter group map "l10LGenericNestedMap" WARNING, parameter group map has status WARNING parameter group "l10LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous @@ -20,7 +20,7 @@ parameter group "l0Parameters" type "org.onap.policy.common.parameters.testclass parameter group "l00LGenericNested" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous - parameter group map "l00LGenericNestedMap" WARNING, parameter group has status WARNING + parameter group map "l00LGenericNestedMap" WARNING, parameter group map has status WARNING parameter group "l00LGenericNestedMapVal0" type "org.onap.policy.common.parameters.testclasses.TestParametersLGeneric" WARNING, parameter group has status WARNING field "lgenericIntField" type "int" value "3" WARNING, values greater than 2 are not recommended field "lgenericStringField" type "java.lang.String" value "lgenericStringField" WARNING, using the field name for the parameter value is dangerous diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java index 2e996cdb..df979286 100644 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java +++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java @@ -7,9 +7,9 @@ * 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. @@ -32,7 +32,7 @@ import org.onap.policy.common.logging.flexlogger.Logger; /** * AuditThread is the main thread for the IntegrityAudit. - * + * */ public class AuditThread extends Thread { @@ -55,7 +55,7 @@ public class AuditThread extends Thread { * May be modified by JUnit tests. */ private static final long AUDIT_THREAD_SLEEP_INTERVAL_MS = 5000L; - + /* * String constants. */ @@ -102,16 +102,11 @@ public class AuditThread extends Thread { /* * Used to create a list that is sorted lexicographically by resourceName. */ - Comparator comparator = new Comparator() { - @Override - public int compare(final IntegrityAuditEntity r1, final IntegrityAuditEntity r2) { - return r1.getResourceName().compareTo(r2.getResourceName()); - } - }; + Comparator comparator = (r1, r2) -> r1.getResourceName().compareTo(r2.getResourceName()); /** * AuditThread constructor. - * + * * @param resourceName the resource name * @param persistenceUnit the persistence unit * @param properties the properties @@ -121,7 +116,7 @@ public class AuditThread extends Thread { */ public AuditThread(String resourceName, String persistenceUnit, Properties properties, int integrityAuditPeriodSeconds, IntegrityAudit integrityAudit) throws IntegrityAuditException { - + this.resourceName = resourceName; this.persistenceUnit = persistenceUnit; this.properties = properties; @@ -307,7 +302,7 @@ public class AuditThread extends Thread { /** * Determines if an exception is an InterruptedException or was caused by an * InterruptedException. - * + * * @param ex exception to be examined * @return {@code true} if it's an InterruptedException, {@code false} otherwise */ @@ -472,7 +467,7 @@ public class AuditThread extends Thread { /** * getEntityCurrentlyDesignated() Returns entity that is currently designated. - * + * * @param integrityAuditEntityList the integrity audit entity list * @return the currently designated integrity audit entity */ @@ -514,7 +509,7 @@ public class AuditThread extends Thread { /** * getIntegrityAuditEnityList gets the list of IntegrityAuditEntity. - * + * * @return the list of IntegrityAuditEntity * @throws DbDaoTransactionException if an error occurs getting the list of IntegrityAuditEntity */ @@ -550,7 +545,7 @@ public class AuditThread extends Thread { /** * Returns the IntegrityAuditEntity for this entity. - * + * * @param integrityAuditEntityList the list of IntegrityAuditEntity * @return the IntegrityAuditEntity for this entity */ @@ -593,7 +588,7 @@ public class AuditThread extends Thread { * auditCompletionIntervalMillis seconds ago. During an audit, lastUpdated is updated every five * seconds or so, but when an audit finishes, the node doing the audit stops updating * lastUpdated. - * + * * @param integrityAuditEntity the integrityAuditEntity * @return false if the lastUpdated time for the record in question is more than * auditCompletionIntervalMillis seconds ago @@ -645,11 +640,11 @@ public class AuditThread extends Thread { /* * If more than (auditCompletionIntervalMillis * 2) milliseconds have elapsed since we last ran * the audit, reset auditCompleted, so - * + * * 1) we'll eventually re-run the audit, if no other node picks up the designation. - * + * * or - * + * * 2) We'll run the audit when the round robin comes back to us. */ private boolean resetAuditCompleted(boolean auditCompleted, IntegrityAuditEntity thisEntity) { @@ -716,7 +711,7 @@ public class AuditThread extends Thread { /** * Indicates that the {@link #run()} method has started. This method simply returns, * and may overridden by junit tests. - * + * * @throws InterruptedException can be interrupted */ public void runStarted() throws InterruptedException { @@ -726,7 +721,7 @@ public class AuditThread extends Thread { /** * Indicates that an audit has completed. This method simply returns, and may * overridden by junit tests. - * + * * @throws InterruptedException can be interrupted */ public void auditCompleted() throws InterruptedException { diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java index 14e0d33a..9a73b79c 100644 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java +++ b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java @@ -7,9 +7,9 @@ * 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. @@ -46,6 +46,8 @@ public class DbAudit { private static final Logger logger = FlexLogger.getLogger(DbAudit.class); + private static final String COMMA_RESOURCE_NAME = ", resourceName="; + private static final long DB_AUDIT_UPDATE_MS = 5000L; private static final long DB_AUDIT_SLEEP_MS = 2000L; @@ -53,7 +55,7 @@ public class DbAudit { /** * Construct an instance with the given DbDao. - * + * * @param dbDao the DbDao */ public DbAudit(DbDao dbDao) { @@ -72,7 +74,7 @@ public class DbAudit { /** * dbAudit actually does the audit. - * + * * @param resourceName the resource name * @param persistenceUnit the persistence unit * @param nodeType the node type @@ -165,12 +167,12 @@ public class DbAudit { for (IntegrityAuditEntity iae : iaeList) { if (iae.getId() == myIae.getId()) { if (logger.isDebugEnabled()) { - logger.debug("dbAudit: My Id=" + iae.getId() + ", resourceName=" + iae.getResourceName()); + logger.debug("dbAudit: My Id=" + iae.getId() + COMMA_RESOURCE_NAME + iae.getResourceName()); } continue; // no need to compare with self } else { if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Id=" + iae.getId() + ", resourceName=" + iae.getResourceName()); + logger.debug("dbAudit: Id=" + iae.getId() + COMMA_RESOURCE_NAME + iae.getResourceName()); } } // Create properties for the other db node @@ -268,13 +270,13 @@ public class DbAudit { for (IntegrityAuditEntity iae : iaeList) { if (iae.getId() == myIae.getId()) { if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Second comparison; My Id=" + iae.getId() + ", resourceName=" + logger.debug("dbAudit: Second comparison; My Id=" + iae.getId() + COMMA_RESOURCE_NAME + iae.getResourceName()); } continue; // no need to compare with self } else { if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Second comparison; Id=" + iae.getId() + ", resourceName=" + logger.debug("dbAudit: Second comparison; Id=" + iae.getId() + COMMA_RESOURCE_NAME + iae.getResourceName()); } } @@ -345,7 +347,7 @@ public class DbAudit { /** * Sleeps a bit. - * + * * @throws IntegrityAuditException if interrupted */ private void sleep() throws IntegrityAuditException { @@ -360,7 +362,7 @@ public class DbAudit { /** * compareEntries() will compare the lists of entries from the DB. - * + * * @param myEntries the entries * @param theirEntries the entries to compare against myEntries * @return the set of differences @@ -372,10 +374,10 @@ public class DbAudit { * audit will walk the local repository hash map comparing to the remote cluster hashmap and * then turn it around and walk the remote hashmap and look for any entries that are not * present in the local cluster hashmap. - * + * * If the objects are not identical, the audit will put the object IDs on a list to try * after completing the audit of the table it is currently working on. - * + * */ HashSet misMatchedKeySet = new HashSet<>(); for (Entry ent : myEntries.entrySet()) { @@ -409,7 +411,7 @@ public class DbAudit { /** * writeAuditDebugLog() writes the mismatched entry details to the debug log. - * + * * @param clazzName the class name * @param resourceName1 resource name 1 * @param resourceName2 resource name 2 @@ -441,7 +443,7 @@ public class DbAudit { /** * writeAuditSummaryLog() writes a summary of the DB mismatches to the error log. - * + * * @param clazzName the name of the class * @param resourceName1 resource name 1 * @param resourceName2 resource name 2 diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java index a921b3ea..79eeee49 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -20,11 +20,13 @@ package org.onap.policy.common.im; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; +import java.util.HashSet; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,7 +41,7 @@ public class StateTransition { public static final String AVAILABLE_STATUS = "availStatus"; public static final String STANDBY_STATUS = "standbyStatus"; public static final String ACTOIN_NAME = "actionName"; - + /* * Common strings. */ @@ -49,33 +51,39 @@ public class StateTransition { private static final String STANDBY_STRING = "], standbyStatus=["; private static final String ACTION_STRING = "], actionName=["; - private HashMap stateTable = new HashMap<>(); + /* + * Valid values for each type. + */ + private static final Set VALID_ADMIN_STATE = Collections + .unmodifiableSet(new HashSet<>(Arrays.asList(StateManagement.LOCKED, StateManagement.UNLOCKED))); + + private static final Set VALID_OP_STATE = Collections + .unmodifiableSet(new HashSet<>(Arrays.asList(StateManagement.ENABLED, StateManagement.DISABLED))); + + private static final Set VALID_STANDBY_STATUS = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList(StateManagement.NULL_VALUE, StateManagement.COLD_STANDBY, + StateManagement.HOT_STANDBY, StateManagement.PROVIDING_SERVICE))); + + private static final Set VALID_AVAIL_STATUS = Collections + .unmodifiableSet(new HashSet<>(Arrays.asList(StateManagement.NULL_VALUE, StateManagement.DEPENDENCY, + StateManagement.DEPENDENCY_FAILED, StateManagement.FAILED))); + + private static final Set VALID_ACTION_NAME = + Collections.unmodifiableSet(new HashSet<>(Arrays.asList(StateManagement.DEMOTE, + StateManagement.DISABLE_DEPENDENCY, StateManagement.DISABLE_FAILED, + StateManagement.ENABLE_NO_DEPENDENCY, StateManagement.ENABLE_NOT_FAILED, + StateManagement.LOCK, StateManagement.PROMOTE, StateManagement.UNLOCK))); + /** - * StateTransition constructor. - * - * @throws StateTransitionException if an error occurs + * State-transition table. */ - public StateTransition() throws StateTransitionException { - if (logger.isDebugEnabled()) { - logger.debug("StateTransition constructor"); - } - - try { - if (logger.isDebugEnabled()) { - logger.debug("Load StateTable started"); - } + private static final Map STATE_TABLE = Collections.unmodifiableMap(makeStateTable()); - setupStateTable(); - } catch (Exception ex) { - logger.error("StateTransition threw exception.", ex); - throw new StateTransitionException("StateTransition Exception: " + ex.toString()); - } - } /** * Calculates the state transition and returns the end state. - * + * * @param adminState the administration state * @param opState the operational state * @param availStatus the availability status @@ -86,54 +94,30 @@ public class StateTransition { */ public StateElement getEndingState(String adminState, String opState, String availStatus, String standbyStatus, String actionName) throws StateTransitionException { - if (logger.isDebugEnabled()) { - logger.debug("getEndingState"); - } - if (logger.isDebugEnabled()) { - logger.debug("adminState=[{}], opState=[{}], availStatus=[{}], standbyStatus=[{}], actionName[{}]", - adminState, opState, availStatus, standbyStatus, actionName); - } + logger.debug("getEndingState"); + logger.debug("adminState=[{}], opState=[{}], availStatus=[{}], standbyStatus=[{}], actionName[{}]", + adminState, opState, availStatus, standbyStatus, actionName); if (availStatus == null) { - availStatus = "null"; + availStatus = StateManagement.NULL_VALUE; } if (standbyStatus == null) { - standbyStatus = "null"; + standbyStatus = StateManagement.NULL_VALUE; } - if (adminState == null || opState == null || actionName == null) { - throw new StateTransitionException(EXCEPTION_STRING - + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus + STANDBY_STRING - + standbyStatus + ACTION_STRING + actionName + "]"); - } else if (!(adminState.equals(StateManagement.LOCKED) || adminState.equals(StateManagement.UNLOCKED))) { - throw new StateTransitionException(EXCEPTION_STRING - + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus + STANDBY_STRING - + standbyStatus + ACTION_STRING + actionName + "]"); - } else if (!(opState.equals(StateManagement.ENABLED) || opState.equals(StateManagement.DISABLED))) { - throw new StateTransitionException(EXCEPTION_STRING - + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus + STANDBY_STRING - + standbyStatus + ACTION_STRING + actionName + "]"); - } else if (!(standbyStatus.equals(StateManagement.NULL_VALUE) - || standbyStatus.equals(StateManagement.COLD_STANDBY) - || standbyStatus.equals(StateManagement.HOT_STANDBY) - || standbyStatus.equals(StateManagement.PROVIDING_SERVICE))) { - throw new StateTransitionException(EXCEPTION_STRING - + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus + STANDBY_STRING - + standbyStatus + ACTION_STRING + actionName + "]"); - } else if (!(availStatus.equals(StateManagement.NULL_VALUE) || availStatus.equals(StateManagement.DEPENDENCY) - || availStatus.equals(StateManagement.DEPENDENCY_FAILED) - || availStatus.equals(StateManagement.FAILED))) { - throw new StateTransitionException(EXCEPTION_STRING - + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus + STANDBY_STRING - + standbyStatus + ACTION_STRING + actionName + "]"); - } else if (!(actionName.equals(StateManagement.DEMOTE) || actionName.equals(StateManagement.DISABLE_DEPENDENCY) - || actionName.equals(StateManagement.DISABLE_FAILED) - || actionName.equals(StateManagement.ENABLE_NO_DEPENDENCY) - || actionName.equals(StateManagement.ENABLE_NOT_FAILED) || actionName.equals(StateManagement.LOCK) - || actionName.equals(StateManagement.PROMOTE) || actionName.equals(StateManagement.UNLOCK))) { - throw new StateTransitionException(EXCEPTION_STRING - + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus + STANDBY_STRING - + standbyStatus + ACTION_STRING + actionName + "]"); + + if (!VALID_ADMIN_STATE.contains(adminState) || !VALID_OP_STATE.contains(opState) + || !VALID_STANDBY_STATUS.contains(standbyStatus)) { + throw new StateTransitionException( + EXCEPTION_STRING + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus + + STANDBY_STRING + standbyStatus + ACTION_STRING + actionName + "]"); } + if (!VALID_AVAIL_STATUS.contains(availStatus) || !VALID_ACTION_NAME.contains(actionName)) { + throw new StateTransitionException( + EXCEPTION_STRING + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus + + STANDBY_STRING + standbyStatus + ACTION_STRING + actionName + "]"); + } + + StateElement stateElement = new StateElement(); try { // dependency,failed is stored as dependency.failed in StateTable @@ -145,7 +129,7 @@ public class StateTransition { if (logger.isDebugEnabled()) { logger.debug("Ending State search key: {}", key); } - String value = stateTable.get(key); + String value = STATE_TABLE.get(key); if (value != null) { try { @@ -189,7 +173,7 @@ public class StateTransition { * endingAdminState,endingOpState,endingAvailStatus,endingStandbyStatus,exception Note : Use * period instead of comma as seperator when store multi-value endingStandbyStatus (convert to * comma during retrieval) - * + * *

Note on illegal state/status combinations: This table has many state/status combinations * that should never occur. However, they *may* occur due to corruption or manual manipulation * of the DB. So, in each case of an illegal combination, the state/status is first corrected @@ -199,18 +183,18 @@ public class StateTransition { * availability status is left null until a disabledfailed or disableddependency action is * received. Or, if a enableNotFailed or enableNoDependency is received while the availability * status is null, it will remain null, but the Operational state will change to enabled. - * + * *

If the standby status is not in agreement with the administrative and/or operational * states, it is brought into agreement. For example, if the administrative state is locked and * the standby status is providingservice, the standby status is changed to coldstandby. - * + * *

After bringing the states/status attributes into agreement, *then* the action is applied * to them. For example, if the administrative state is locked, the operational state is * enabled, the availability status is null, the standby status is providingservice and the * action is unlock, the standby status is changed to coldstandby and then the unlock action is * applied. This will change the final state/status to administrative state = unlocked, * operational state = disabled, availability status = null and standby status = hotstandby. - * + * *

Note on standby status: If the starting state of standby status is null and either a * promote or demote action is made, the assumption is that standbystatus is supported and * therefore, the standby status will be changed to providingservice, hotstandby or coldstandby @@ -221,9 +205,13 @@ public class StateTransition { * operational state such that they are unlocked and enabled, the standby status is * automatically transitioned to hotstandby since it is only those two states that can hold the * statndby status in the coldstandby value. + * + * @return a new state-transaction table */ - private void setupStateTable() { + private static Map makeStateTable() { + Map stateTable = new HashMap<>(); + stateTable.put("unlocked,enabled,null,null,lock", "locked,enabled,null,null,"); stateTable.put("unlocked,enabled,null,null,unlock", "unlocked,enabled,null,null,"); stateTable.put("unlocked,enabled,null,null,disableFailed", "unlocked,disabled,failed,null,"); @@ -934,21 +922,21 @@ public class StateTransition { "locked,disabled,dependency.failed,coldstandby,StandbyStatusException"); stateTable.put("locked,disabled,dependency.failed,providingservice,demote", "locked,disabled,dependency.failed,coldstandby,"); + + return stateTable; } /** * Display the state table. */ public void displayStateTable() { - Set set = stateTable.entrySet(); - Iterator iter = set.iterator(); + if (!logger.isDebugEnabled()) { + return; + } - while (iter.hasNext()) { - Map.Entry me = (Map.Entry) iter.next(); - String key = (String) me.getKey() + ((String) me.getValue()).replace(".", ","); - if (logger.isDebugEnabled()) { - logger.debug("{}", key); - } + for (Entry me : STATE_TABLE.entrySet()) { + String key = me.getKey() + me.getValue().replace(".", ","); + logger.debug("{}", key); } } } diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java index b71751f0..a2d8c091 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -23,15 +23,11 @@ package org.onap.policy.common.im.jmx; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import javax.management.MBeanServerConnection; -import javax.management.Notification; -import javax.management.NotificationListener; import javax.management.remote.JMXConnectionNotification; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; - import org.onap.policy.common.im.IntegrityMonitorException; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -66,7 +62,7 @@ public final class JmxAgentConnection { /** * Generate jmxAgent url. service:jmx:rmi:///jndi/rmi://host.domain:9999/jmxAgent - * + * * @param host host.domain * @param port 9999 * @return jmxAgent url. @@ -78,7 +74,7 @@ public final class JmxAgentConnection { /** * Get a connection to the jmxAgent MBeanServer. - * + * * @return the connection * @throws IntegrityMonitorException on error */ @@ -95,14 +91,10 @@ public final class JmxAgentConnection { connector = JMXConnectorFactory.newJMXConnector(url, env); connector.connect(); - connector.addConnectionNotificationListener(new NotificationListener() { - - @Override - public void handleNotification(Notification notification, Object handback) { - if (notification.getType().equals(JMXConnectionNotification.FAILED)) { - // handle disconnect - disconnect(); - } + connector.addConnectionNotificationListener((notification, handback) -> { + if (notification.getType().equals(JMXConnectionNotification.FAILED)) { + // handle disconnect + disconnect(); } }, null, null); diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java index 78b90abd..79f843e4 100644 --- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java +++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * Integrity Monitor * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -73,6 +73,10 @@ public class StateManagementEntity implements Serializable { @Column(name = "modifiedDate", nullable = false) private Date modifiedDate; + public StateManagementEntity() { + // default constructor + } + @PrePersist public void prePersist() { this.createdDate = MonitorTime.getInstance().getDate(); @@ -84,10 +88,6 @@ public class StateManagementEntity implements Serializable { this.modifiedDate = MonitorTime.getInstance().getDate(); } - public StateManagementEntity() { - // default constructor - } - public String getResourceName() { return this.resourceName; } @@ -135,7 +135,7 @@ public class StateManagementEntity implements Serializable { /** * Clone a StateManagementEntity. - * + * * @param sm the StateManagementEntity to clone * @return a new StateManagementEntity */ diff --git a/integrity-monitor/src/main/resources/META-INF/persistence.xml b/integrity-monitor/src/main/resources/META-INF/persistence.xml index f5089b12..7aff9219 100644 --- a/integrity-monitor/src/main/resources/META-INF/persistence.xml +++ b/integrity-monitor/src/main/resources/META-INF/persistence.xml @@ -3,14 +3,14 @@ ============LICENSE_START======================================================= Integrity Monitor ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + Copyright (C) 2017, 2019 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. @@ -19,30 +19,31 @@ ============LICENSE_END========================================================= --> - - - - org.eclipse.persistence.jpa.PersistenceProvider - org.onap.policy.common.im.jpa.ImTestEntity - org.onap.policy.common.im.jpa.StateManagementEntity - org.onap.policy.common.im.jpa.ForwardProgressEntity - org.onap.policy.common.im.jpa.ResourceRegistrationEntity - NONE - - + + + + org.eclipse.persistence.jpa.PersistenceProvider + org.onap.policy.common.im.jpa.ImTestEntity + org.onap.policy.common.im.jpa.StateManagementEntity + org.onap.policy.common.im.jpa.ForwardProgressEntity + org.onap.policy.common.im.jpa.ResourceRegistrationEntity + NONE + + - + - - - org.eclipse.persistence.jpa.PersistenceProvider - org.onap.policy.common.im.jpa.ImTestEntity - org.onap.policy.common.im.jpa.StateManagementEntity - org.onap.policy.common.im.jpa.ForwardProgressEntity - org.onap.policy.common.im.jpa.ResourceRegistrationEntity - NONE - - + + + org.eclipse.persistence.jpa.PersistenceProvider + org.onap.policy.common.im.jpa.ImTestEntity + org.onap.policy.common.im.jpa.StateManagementEntity + org.onap.policy.common.im.jpa.ForwardProgressEntity + org.onap.policy.common.im.jpa.ResourceRegistrationEntity + NONE + + - + diff --git a/integrity-monitor/src/test/resources/logback-test.xml b/integrity-monitor/src/test/resources/logback-test.xml index 57a9d1c9..70a71950 100644 --- a/integrity-monitor/src/test/resources/logback-test.xml +++ b/integrity-monitor/src/test/resources/logback-test.xml @@ -2,14 +2,14 @@ ============LICENSE_START======================================================= integrity-monitor ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + Copyright (C) 2017, 2019 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. @@ -22,26 +22,25 @@ - - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n - - - - - logs/debug.log - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n - - - - - - - - + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n + + + + + logs/debug.log + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n + + + - + + + + + diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java index 3ae39ebd..34e35a2e 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java @@ -28,7 +28,6 @@ import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; -import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; @@ -40,6 +39,7 @@ import org.junit.Before; import org.junit.Test; import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.common.utils.gson.GsonTestUtils; +import org.onap.policy.common.utils.network.NetworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -105,7 +105,7 @@ public class HttpServerTest { request.setText(SOME_TEXT); String reqText = gson.toJson(request); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); + String response = http(portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); assertEquals(reqText, response); } @@ -127,7 +127,7 @@ public class HttpServerTest { request.setText(SOME_TEXT); String reqText = gson.toJson(request); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); + String response = http(portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); assertEquals(reqText, response); assertTrue(MyJacksonProvider.hasReadSome()); @@ -155,7 +155,7 @@ public class HttpServerTest { request.setText(SOME_TEXT); String reqText = gson.toJson(request); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); + String response = http(portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); assertEquals(reqText, response); assertTrue(MyGsonProvider.hasReadSome()); @@ -181,7 +181,7 @@ public class HttpServerTest { request.setText(SOME_TEXT); String reqText = gson.toJson(request); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); + String response = http(portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); assertEquals(reqText, response); } @@ -202,7 +202,7 @@ public class HttpServerTest { request.setText(SOME_TEXT); String reqText = gson.toJson(request); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); + String response = http(portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); assertEquals(reqText, response); assertTrue(MyJacksonProvider.hasReadSome()); @@ -229,7 +229,7 @@ public class HttpServerTest { request.setText(SOME_TEXT); String reqText = gson.toJson(request); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); + String response = http(portUrl + JUNIT_ECHO_FULL_REQUEST, reqText); assertEquals(reqText, response); assertTrue(MyGsonProvider.hasReadSome()); @@ -261,18 +261,18 @@ public class HttpServerTest { assertTrue(HttpServletServer.factory.get(port).isAlive()); assertFalse(HttpServletServer.factory.get(port).isAaf()); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_HELLO); + String response = http(portUrl + JUNIT_ECHO_HELLO); assertEquals(HELLO, response); response = null; try { - response = http(HttpServletServer.factory.get(port), portUrl + SWAGGER_JSON); + response = http(portUrl + SWAGGER_JSON); } catch (IOException e) { // Expected } assertTrue(response == null); - response = http(HttpServletServer.factory.get(port), portUrl + "/junit/echo/hello?block=true"); + response = http(portUrl + "/junit/echo/hello?block=true"); assertEquals("FILTERED", response); assertTrue(HttpServletServer.factory.get(port).isAlive()); @@ -302,18 +302,18 @@ public class HttpServerTest { assertTrue(HttpServletServer.factory.get(port).isAlive()); assertTrue(HttpServletServer.factory.get(port2).isAlive()); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_HELLO); + String response = http(portUrl + JUNIT_ECHO_HELLO); assertTrue(HELLO.equals(response)); - response = http(HttpServletServer.factory.get(port), portUrl + SWAGGER_JSON); + response = http(portUrl + SWAGGER_JSON); assertTrue(response != null); - response = http(HttpServletServer.factory.get(port2), LOCALHOST_PREFIX + port2 + JUNIT_ECHO_HELLO); + response = http(LOCALHOST_PREFIX + port2 + JUNIT_ECHO_HELLO); assertTrue(HELLO.equals(response)); response = null; try { - response = http(HttpServletServer.factory.get(port2), LOCALHOST_PREFIX + port2 + SWAGGER_JSON); + response = http(LOCALHOST_PREFIX + port2 + SWAGGER_JSON); } catch (IOException e) { // Expected } @@ -335,10 +335,10 @@ public class HttpServerTest { assertTrue(HttpServletServer.factory.get(port).isAlive()); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_HELLO); + String response = http(portUrl + JUNIT_ECHO_HELLO); assertTrue(HELLO.equals(response)); - response = http(HttpServletServer.factory.get(port), portUrl + "/junit/endpoints/http/servers"); + response = http(portUrl + "/junit/endpoints/http/servers"); assertTrue(response.contains(randomName)); HttpServletServer.factory.destroy(); @@ -356,7 +356,7 @@ public class HttpServerTest { assertTrue(HttpServletServer.factory.get(port).isAlive()); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_HELLO); + String response = http(portUrl + JUNIT_ECHO_HELLO); assertTrue(HELLO.equals(response)); HttpServletServer.factory.destroy(); @@ -376,10 +376,10 @@ public class HttpServerTest { assertTrue(HttpServletServer.factory.get(port).isAlive()); - String response = http(HttpServletServer.factory.get(port), portUrl + JUNIT_ECHO_HELLO); + String response = http(portUrl + JUNIT_ECHO_HELLO); assertTrue(HELLO.equals(response)); - response = http(HttpServletServer.factory.get(port), portUrl + "/junit/endpoints/http/servers"); + response = http(portUrl + "/junit/endpoints/http/servers"); assertTrue(response.contains(randomName)); HttpServletServer.factory.destroy(); @@ -393,27 +393,13 @@ public class HttpServerTest { * @throws IOException thrown is IO exception occurs * @throws InterruptedException thrown if thread interrupted occurs */ - protected String http(HttpServletServer server, String urlString) + private String http(String urlString) throws IOException, InterruptedException { URL url = new URL(urlString); - String response = null; - int numRetries = 1; - int maxNumberRetries = 5; - while (numRetries <= maxNumberRetries) { - try { - URLConnection conn = url.openConnection(); - response = response(conn); - break; - } catch (ConnectException e) { - logger.warn("http server {} @ {} ({}) - cannot connect yet ..", server, urlString, numRetries, e); - numRetries++; - Thread.sleep(10000L); - } catch (Exception e) { - throw e; - } + if (!NetworkUtil.isTcpPortOpen(url.getHost(), url.getPort(), 25, 2)) { + throw new IllegalStateException("port never opened: " + url); } - - return response; + return response(url.openConnection()); } /** @@ -423,32 +409,18 @@ public class HttpServerTest { * @throws IOException thrown is IO exception occurs * @throws InterruptedException thrown if thread interrupted occurs */ - protected String http(HttpServletServer server, String urlString, String post) + private String http(String urlString, String post) throws IOException, InterruptedException { URL url = new URL(urlString); - String response = null; - int numRetries = 1; - int maxNumberRetries = 5; - while (numRetries <= maxNumberRetries) { - try { - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - conn.setDoOutput(true); - conn.setRequestProperty("Content-Type", "application/json"); - IOUtils.write(post, conn.getOutputStream()); - response = response(conn); - break; - } catch (ConnectException e) { - logger.warn("http server {} @ {} ({}) - cannot connect yet ..", server, urlString, numRetries, e); - numRetries++; - Thread.sleep(10000L); - } catch (Exception e) { - logger.error("http error", e); - throw e; - } + if (!NetworkUtil.isTcpPortOpen(url.getHost(), url.getPort(), 25, 2)) { + throw new IllegalStateException("port never opened: " + url); } - - return response; + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("POST"); + conn.setDoOutput(true); + conn.setRequestProperty("Content-Type", "application/json"); + IOUtils.write(post, conn.getOutputStream()); + return response(conn); } /** @@ -458,7 +430,7 @@ public class HttpServerTest { * * @throws IOException if an I/O error occurs */ - protected String response(URLConnection conn) throws IOException { + private String response(URLConnection conn) throws IOException { StringBuilder response = new StringBuilder(); try (BufferedReader ioReader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; diff --git a/utils/src/main/java/org/onap/policy/common/utils/network/NetworkUtil.java b/utils/src/main/java/org/onap/policy/common/utils/network/NetworkUtil.java index 3976c7a2..6014b581 100644 --- a/utils/src/main/java/org/onap/policy/common/utils/network/NetworkUtil.java +++ b/utils/src/main/java/org/onap/policy/common/utils/network/NetworkUtil.java @@ -21,7 +21,6 @@ package org.onap.policy.common.utils.network; import java.io.IOException; -import java.net.ConnectException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; @@ -132,13 +131,13 @@ public class NetworkUtil { * @throws InterruptedException if execution has been interrupted */ public static boolean isTcpPortOpen(String host, int port, int retries, long interval) - throws InterruptedException, IOException { + throws InterruptedException { int retry = 0; while (retry < retries) { try (Socket s = new Socket(host, port)) { logger.debug("{}:{} connected - retries={} interval={}", host, port, retries, interval); return true; - } catch (final ConnectException e) { + } catch (final IOException e) { retry++; logger.trace("{}:{} connected - retries={} interval={}", host, port, retries, interval, e); Thread.sleep(interval); -- cgit 1.2.3-korg