* ============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.
}
}
+ private PolicyLogger() {
+
+ }
+
public static Level getDebugLevel() {
return debugLevel;
}
/**
* Populates MDC info.
- *
+ *
* @param transId the transaction ID
* @return String
*/
/**
* Populate MDC Info using the passed in mdcInfo.
- *
+ *
* @param transId the transaction ID
* @param mdcInfo the MDC info
* @return String
/**
* Sets transaction Id to MDC.
- *
+ *
* @param eventObject event object
*/
public static void postMDCInfoForEvent(Object eventObject) {
/**
* Sets transaction Id to MDC.
- *
+ *
* @param transId the transaction ID
*/
public static void setTransId(String transId) {
/**
* Returns current transaction Id used in MDC.
- *
+ *
* @return transId
*/
public static String getTransId() {
/**
* Resets transaction Id in MDC for the rule triggered by this event.
- *
+ *
* @param transId the transaction ID
* @return String
*/
/**
* Resets transaction Id in MDC for the rule triggered by this event.
- *
+ *
* @param obj object
*/
public static void postMDCUUIDForTriggeredRule(Object obj) {
// ************************************************************************************************
/**
* Records the Info event with String [] arguments.
- *
+ *
* @param msg the message code
* @param className the class name
* @param arguments the messages
/**
* Records only one String message with its class name.
- *
+ *
* @param className the class name
* @param arg0 the message
*/
/**
* Records only one String message.
- *
+ *
* @param arg0 the message
*/
public static void info(Object arg0) {
/**
* 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
/**
* 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
/**
* Records only one String message with its class name.
- *
+ *
* @param arg0 log message
* @param className class name
*/
/**
* Records only one String message.
- *
+ *
* @param arg0 the message
*/
public static void warn(Object arg0) {
/**
* Records only one String message without its class name passed in.
- *
+ *
* @param arg0 the message
*/
public static void warn(String arg0) {
/**
* 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
/**
* 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
/**
* 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
/**
* Records only one String message with its class name.
- *
+ *
* @param className class name
* @param arg0 log message
*/
/**
* Records only one String message.
- *
+ *
* @param arg0 the message
*/
public static void error(String arg0) {
/**
* Records only one String message.
- *
+ *
* @param arg0 the message
*/
public static void error(Object arg0) {
/**
* 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
/**
* 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
/**
* Records a message with passed in message code and a list of string values.
- *
+ *
* @param msg the message code
* @param arguments the messages
*/
/**
* Records a message with passed in message code and a list of string values.
- *
+ *
* @param msg the message code
* @param arguments the messages
*/
/**
* Records only one String message with its class name.
- *
+ *
* @param className the class name
* @param arg0 the message
*/
/**
* Records only one String message.
- *
+ *
* @param arg0 the message
*/
public static void debug(String arg0) {
/**
* Records only one String message.
- *
+ *
* @param arg0 the message
*/
public static void debug(Object arg0) {
/**
* 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
/**
* 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
/**
* Records only one String message with its class name.
- *
+ *
* @param className the class name
* @param arg0 the message
*/
/**
* Records only one String message.
- *
+ *
* @param arg0 the message
*/
public static void audit(Object arg0) {
/**
* Records only one String message with its class name.
- *
+ *
* @param className the class name
* @param arg0 the message
*/
/**
* Records only one String message.
- *
+ *
* @param arg0 the message
*/
public static void trace(Object arg0) {
/**
* 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) {
/**
* 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) {
/**
* Records the ending time of the event with its request Id as the key.
- *
+ *
* @param eventId the event ID
* @param rule the rule
*/
/**
* 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
/**
* 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
/**
* Records the ending time of the event with its request Id as the key.
- *
+ *
* @param eventId the event ID
* @param rule the rule
*/
/**
* 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
/**
* Records the ending time of the event with its request Id as the key.
- *
+ *
* @param eventId the event ID
* @param rule the rule
*/
/**
* Records the audit with an event starting and ending times.
- *
+ *
* @param eventId the event ID
* @param rule the rule
* @param startTime the start time
/**
* Records the metrics with an event Id and log message.
- *
+ *
* @param eventId the event ID
* @param arg1 the message
*/
/**
* 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
/**
* Records the metrics with an event Id and log message.
- *
+ *
* @param eventId the event ID
* @param arg1 the message
*/
/**
* Records a String message for metrics logs.
- *
+ *
* @param arg0 the message
*/
public static void recordMetricEvent(String arg0) {
/**
* Records the metrics event with a String message.
- *
+ *
* @param arg0 the message
*/
public static void metrics(String arg0) {
/**
* Records the metrics event with a class name and a String message.
- *
+ *
* @param arg0 the message
*/
public static void metrics(String className, Object arg0) {
/**
* Records the metrics event with a String message.
- *
+ *
* @param arg0 the message
*/
public static void metrics(Object arg0) {
/**
* Records the metrics event with a String message.
- *
+ *
* @param arg0 the message
*/
public static void metricsPrintln(String arg0) {
/**
* Removes all the return lines from the printStackTrace.
- *
+ *
* @param throwable the throwable
* @param arguments the messages
*/
--- /dev/null
+/*-
+ * ============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<String, ValidationResult> 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);
+}
/*-
* ============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=========================================================
*/
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<String, ValidationResult> validationResultMap = new LinkedHashMap<>();
/**
* Constructor, create the group map validation result.
* @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
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
}
// 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
*/
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
-/*
+/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
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<String, ValidationResult> 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
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.
*
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("\" ");
}
}
} 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());
}
}
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;
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)) {
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;
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)) {
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
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
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
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
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
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
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
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
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
* 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.
/**
* AuditThread is the main thread for the IntegrityAudit.
- *
+ *
*/
public class AuditThread extends Thread {
* May be modified by JUnit tests.
*/
private static final long AUDIT_THREAD_SLEEP_INTERVAL_MS = 5000L;
-
+
/*
* String constants.
*/
/*
* Used to create a list that is sorted lexicographically by resourceName.
*/
- Comparator<IntegrityAuditEntity> comparator = new Comparator<IntegrityAuditEntity>() {
- @Override
- public int compare(final IntegrityAuditEntity r1, final IntegrityAuditEntity r2) {
- return r1.getResourceName().compareTo(r2.getResourceName());
- }
- };
+ Comparator<IntegrityAuditEntity> comparator = (r1, r2) -> r1.getResourceName().compareTo(r2.getResourceName());
/**
* AuditThread constructor.
- *
+ *
* @param resourceName the resource name
* @param persistenceUnit the persistence unit
* @param properties the properties
*/
public AuditThread(String resourceName, String persistenceUnit, Properties properties,
int integrityAuditPeriodSeconds, IntegrityAudit integrityAudit) throws IntegrityAuditException {
-
+
this.resourceName = resourceName;
this.persistenceUnit = persistenceUnit;
this.properties = properties;
/**
* 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
*/
/**
* getEntityCurrentlyDesignated() Returns entity that is currently designated.
- *
+ *
* @param integrityAuditEntityList the integrity audit entity list
* @return the currently designated integrity audit entity
*/
/**
* getIntegrityAuditEnityList gets the list of IntegrityAuditEntity.
- *
+ *
* @return the list of IntegrityAuditEntity
* @throws DbDaoTransactionException if an error occurs getting the list of IntegrityAuditEntity
*/
/**
* Returns the IntegrityAuditEntity for this entity.
- *
+ *
* @param integrityAuditEntityList the list of IntegrityAuditEntity
* @return the IntegrityAuditEntity for this entity
*/
* 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
/*
* 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) {
/**
* 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 {
/**
* 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 {
* 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.
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;
/**
* Construct an instance with the given DbDao.
- *
+ *
* @param dbDao the DbDao
*/
public DbAudit(DbDao dbDao) {
/**
* dbAudit actually does the audit.
- *
+ *
* @param resourceName the resource name
* @param persistenceUnit the persistence unit
* @param nodeType the node type
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
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());
}
}
/**
* Sleeps a bit.
- *
+ *
* @throws IntegrityAuditException if interrupted
*/
private void sleep() throws IntegrityAuditException {
/**
* 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
* 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<Object> misMatchedKeySet = new HashSet<>();
for (Entry<Object, Object> ent : myEntries.entrySet()) {
/**
* 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
/**
* 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
* ============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.
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;
public static final String AVAILABLE_STATUS = "availStatus";
public static final String STANDBY_STATUS = "standbyStatus";
public static final String ACTOIN_NAME = "actionName";
-
+
/*
* Common strings.
*/
private static final String STANDBY_STRING = "], standbyStatus=[";
private static final String ACTION_STRING = "], actionName=[";
- private HashMap<String, String> stateTable = new HashMap<>();
+ /*
+ * Valid values for each type.
+ */
+ private static final Set<String> VALID_ADMIN_STATE = Collections
+ .unmodifiableSet(new HashSet<>(Arrays.asList(StateManagement.LOCKED, StateManagement.UNLOCKED)));
+
+ private static final Set<String> VALID_OP_STATE = Collections
+ .unmodifiableSet(new HashSet<>(Arrays.asList(StateManagement.ENABLED, StateManagement.DISABLED)));
+
+ private static final Set<String> 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<String> VALID_AVAIL_STATUS = Collections
+ .unmodifiableSet(new HashSet<>(Arrays.asList(StateManagement.NULL_VALUE, StateManagement.DEPENDENCY,
+ StateManagement.DEPENDENCY_FAILED, StateManagement.FAILED)));
+
+ private static final Set<String> 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<String, String> 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
*/
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
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 {
* endingAdminState,endingOpState,endingAvailStatus,endingStandbyStatus,exception Note : Use
* period instead of comma as seperator when store multi-value endingStandbyStatus (convert to
* comma during retrieval)
- *
+ *
* <p>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
* 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.
- *
+ *
* <p>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.
- *
+ *
* <p>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.
- *
+ *
* <p>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
* 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<String, String> makeStateTable() {
+ Map<String,String> 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,");
"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<String, String> me : STATE_TABLE.entrySet()) {
+ String key = me.getKey() + me.getValue().replace(".", ",");
+ logger.debug("{}", key);
}
}
}
* ============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.
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;
/**
* Generate jmxAgent url. service:jmx:rmi:///jndi/rmi://host.domain:9999/jmxAgent
- *
+ *
* @param host host.domain
* @param port 9999
* @return jmxAgent url.
/**
* Get a connection to the jmxAgent MBeanServer.
- *
+ *
* @return the connection
* @throws IntegrityMonitorException on error
*/
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);
* ============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.
@Column(name = "modifiedDate", nullable = false)
private Date modifiedDate;
+ public StateManagementEntity() {
+ // default constructor
+ }
+
@PrePersist
public void prePersist() {
this.createdDate = MonitorTime.getInstance().getDate();
this.modifiedDate = MonitorTime.getInstance().getDate();
}
- public StateManagementEntity() {
- // default constructor
- }
-
public String getResourceName() {
return this.resourceName;
}
/**
* Clone a StateManagementEntity.
- *
+ *
* @param sm the StateManagementEntity to clone
* @return a new StateManagementEntity
*/
============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.
============LICENSE_END=========================================================
-->
-<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
- <persistence-unit name="schemaPU" transaction-type="RESOURCE_LOCAL">
- <!-- Limited use for generating the DB and schema files for imtest DB - uses eclipselink -->
- <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
- <class>org.onap.policy.common.im.jpa.ImTestEntity</class>
- <class>org.onap.policy.common.im.jpa.StateManagementEntity</class>
- <class>org.onap.policy.common.im.jpa.ForwardProgressEntity</class>
- <class>org.onap.policy.common.im.jpa.ResourceRegistrationEntity</class>
- <shared-cache-mode>NONE</shared-cache-mode>
- <properties>
- <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
+<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
+ <persistence-unit name="schemaPU" transaction-type="RESOURCE_LOCAL">
+ <!-- Limited use for generating the DB and schema files for imtest DB - uses eclipselink -->
+ <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+ <class>org.onap.policy.common.im.jpa.ImTestEntity</class>
+ <class>org.onap.policy.common.im.jpa.StateManagementEntity</class>
+ <class>org.onap.policy.common.im.jpa.ForwardProgressEntity</class>
+ <class>org.onap.policy.common.im.jpa.ResourceRegistrationEntity</class>
+ <shared-cache-mode>NONE</shared-cache-mode>
+ <properties>
+ <property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
</properties>
- </persistence-unit>
+ </persistence-unit>
- <persistence-unit name="operationalPU" transaction-type="RESOURCE_LOCAL">
- <!-- For operational use -->
- <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
- <class>org.onap.policy.common.im.jpa.ImTestEntity</class>
- <class>org.onap.policy.common.im.jpa.StateManagementEntity</class>
- <class>org.onap.policy.common.im.jpa.ForwardProgressEntity</class>
- <class>org.onap.policy.common.im.jpa.ResourceRegistrationEntity</class>
- <shared-cache-mode>NONE</shared-cache-mode>
- <properties>
- <!-- none -->
+ <persistence-unit name="operationalPU" transaction-type="RESOURCE_LOCAL">
+ <!-- For operational use -->
+ <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+ <class>org.onap.policy.common.im.jpa.ImTestEntity</class>
+ <class>org.onap.policy.common.im.jpa.StateManagementEntity</class>
+ <class>org.onap.policy.common.im.jpa.ForwardProgressEntity</class>
+ <class>org.onap.policy.common.im.jpa.ResourceRegistrationEntity</class>
+ <shared-cache-mode>NONE</shared-cache-mode>
+ <properties>
+ <!-- none -->
</properties>
- </persistence-unit>
+ </persistence-unit>
</persistence>
============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.
<configuration>
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
- <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
- <Pattern>
- %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n
- </Pattern>
- </encoder>
- </appender>
- <appender name="FILE" class="ch.qos.logback.core.FileAppender">
- <file>logs/debug.log</file>
- <encoder>
- <Pattern>
- %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n
- </Pattern>
- </encoder>
- </appender>
-
- <root level="debug">
- <appender-ref ref="STDOUT" />
- <appender-ref ref="FILE" />
- </root>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+ <Pattern>
+ %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n
+ </Pattern>
+ </encoder>
+ </appender>
+ <appender name="FILE" class="ch.qos.logback.core.FileAppender">
+ <file>logs/debug.log</file>
+ <encoder>
+ <Pattern>
+ %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n
+ </Pattern>
+ </encoder>
+ </appender>
-</configuration>
+ <root level="debug">
+ <appender-ref ref="STDOUT" />
+ <appender-ref ref="FILE" />
+ </root>
+</configuration>
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;
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;
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);
}
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());
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());
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);
}
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());
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());
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());
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
}
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();
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();
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();
* @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());
}
/**
* @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);
}
/**
*
* @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;
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;
* @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);